我想用Pygame做个游戏。但该计划启动后立即关闭
我遵循了YT的一个教程,完全按照原样复制了这个函数,但仍然得到了错误
代码如下:
import pygame
import sys
import random as rd
pygame.init()
width = 800
height = 600
red = (255, 0, 0)
black = (0, 0, 0)
blue = (0, 0, 255)
playerPosition = [400, 500]
playerSize = 35
enemySize = 50
enemyPosition = [rd.randint(0, width - enemySize), 0]
enemySpeed = 10
screen = pygame.display.set_mode((width, height))
title = pygame.display.set_caption("Dodge Game by Ishak")
def collision(playerPosition, enemyPosition):
playerX = playerPosition[0] # player x coordinate
playerY = playerPosition[1] # player y coordinate
enemyX = enemyPosition[0] # enemy x coordinate
enemyY = enemyPosition[1] # enemy y coordinate
if (enemyX >= playerX and enemyX < (playerX + playerSize)) or (playerX >= enemyX and playerX < (enemyX + enemySize)):
if (enemyY >= playerY and enemyY < (playerY + playerSize)) or (playerY >= enemyY and playerY < (enemyY + enemySize)):
return False
return True
clock = pygame.time.Clock()
gameOver = False
# game loop
while not gameOver:
# QUIT
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# keyboard
if event.type == pygame.KEYDOWN:
x = playerPosition[0]
y = playerPosition[1]
if event.key == pygame.K_RIGHT:
x += 13
elif event.key == pygame.K_LEFT:
x -= 13
playerPosition = [x, y]
if enemyPosition[1] >= 0 and enemyPosition[1] < height:
enemyPosition[1] += enemySpeed
else:
enemyPosition[0] = rd.randint(0, width - enemySize) # sets a random postion of the enemy
enemyPosition[1] = 0
if collision(playerPosition, enemyPosition):
gameOver = True
screen.fill(black)
pygame.draw.rect(screen, red, (playerPosition[0], playerPosition[1], playerSize, playerSize)) # player shape
pygame.draw.rect(screen, blue, (enemyPosition[0], enemyPosition[1], enemySize, enemySize)) # enemy shape
clock.tick(30)
pygame.display.update()
这个问题是在我添加了碰撞函数并在主游戏循环中实现它之后出现的,但是我不知道它有什么问题
这是我看到的唯一一个循环停止的地方:
所以我预测你的玩家和敌人产卵时会发生碰撞。为了确定,我建议打印玩家和敌人的位置,看看他们是否真的发生碰撞
相关问题 更多 >
编程相关推荐