我一直在尝试编写一个火鸡必须躲避子弹的游戏,这是一个2d游戏,所以它只能向上、向下、向左和向右移动。我试着加入游戏的逻辑";小行星";小行星随机产卵,但仍然没有运气。
import pygame
bakcground = pygame.image.load("Bulletspix/Grass BG.png")
PlayerTurk = pygame.image.load ("Bulletspix/turkey.png")
playerTurkx = 450
playerTurky = 800
vel = 1
pygame.display.set_caption("game")
screen = pygame.display.set_mode((800, 900))
playerTurkx = 350
playerTurky = 350
vel = 1
def player():
screen.blit(PlayerTurk, (playerTurkx , playerTurky))
running = True
while running:
#Oprion of quitting
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Background
screen.fill((0, 0, 0))
screen.blit(bakcground, (0, 0))
#movement
Input = pygame.key.get_pressed()
if Input[pygame.K_LEFT] and playerTurkx >0:
playerTurkx -= vel
if Input[pygame.K_RIGHT]and playerTurkx <730:
playerTurkx += vel
if Input[pygame.K_UP]and playerTurky >0:
playerTurky -= vel
if Input[pygame.K_DOWN]and playerTurky <500:
playerTurky += vel
player()
pygame.display.update()
pygame.quit()
首先,创建一个列表来存储项目符号。
bullets = []
# And some other necessary variables.
seconds_since_spawn = 0.0
player_lives = 3
BULLET_START_POSITION = (799, 449)
然后,在循环中的每一次迭代中:
- 每N次迭代/秒,在固定位置生成一个子弹(稍后随机化(。
if seconds_since_spawn >= 1.0: seconds_since_spawn = 0.0 bullets.append(BULLET_START_POSITION)
- 将所有项目符号在屏幕上移动一步。
bullets = [(x - 1, y) for x, y in bullets]
- 检查是否有子弹与玩家相撞。
def collided_with_player(x, y): return check_collision( player.x, player.y, PLAYER_RADIUS, x, y, BULLET_RADIUS ) player_lives -= sum( 1 for x, y in bullets if collided_with_player(x, y) ) if player_lives <= 0: running = False # end game
- 从列表中删除所有在屏幕上看不到的项目符号,或与播放器碰撞的项目符号。
bullets = [ (x, y) for x, y in bullets if is_inside_screen(x, y) and not collided_with_player(x, y) ]
- 绘制所有项目符号。
for x, y in bullets: draw_bullet(x, y)