我制作了一个带有多个下落立方体的小游戏,玩家(正方形)必须避开它。我设法使碰撞起作用,但问题是每次圆形和正方形碰撞时,每次碰撞时都会显示文本。但我希望当圆形和方形第一次发生碰撞时,文本会继续显示。有什么办法吗?import pygamefrom pygame.locals import *import osimport randomimport mathimport sysimport timewhite = (255,255,255)blue = (0,0,255)gravity = 10size =10height = 500width =600varHeigth = heightballNum = 5eBall = []apGame = pygame.display.set_mode((width, height))pygame.display.set_caption("AP Project")clock = pygame.time.Clock()class Player(object): def __init__(self): red = (255, 0, 0) move_x = 300 move_y = 400 self.rect = pygame.draw.rect(apGame,red, (move_x, move_y, 10, 10)) self.dist = 10 def handle_keys(self): for e in pygame.event.get(): if e.type == pygame.QUIT: pygame.quit(); exit() key = pygame.key.get_pressed() if key[pygame.K_LEFT]: self.draw_rect(-1, 0) elif key[pygame.K_RIGHT]: self.draw_rect(1, 0) elif key[pygame.K_ESCAPE]: pygame.quit(); exit() else: self.draw_rect(0, 0) def draw_rect(self, x, y): red = (255, 0, 0) black = (0, 0, 0) '''apGame.fill(black)''' self.rect = self.rect.move(x * self.dist, y * self.dist); pygame.draw.rect(apGame, red , self.rect) pygame.display.update() def draw(self,surface): red = (255, 0, 0) move_x = 300 move_y = 400 pygame.draw.rect(apGame, red, (move_x, move_y, 10, 10))#The game over text here def show_go_screen(): pygame.font.init() myfont = pygame.font.SysFont("Comic Sans MS", 30) label = myfont.render("Game Over", 1, red) apGame.blit(label, (300,100))def instuct(): pygame.font.init() myfont = pygame.font.SysFont("Comic Sans MS", 15) label = myfont.render("Avoid The Circles", 1, red) apGame.blit(label, (250,450))
1 回答
动漫人物
TA贡献1815条经验 获得超10个赞
每当您希望功能只运行一次时,您应该在该函数外部添加一个检查以确保该函数内的代码只运行一次。这是使用您的代码的示例。
collidedOnce = False
if player.rect.colliderect(ball_rect):
if(collidedOnce == False):
collidedOnce = True #This makes the code only run once since it's setting this variable to be true within the condition
#game_over = True
show_go_screen()
eBall[i][1] += 5
if eBall[i][1] > height:
y = random.randrange(-50, -10)
eBall[i][1] = y
x = random.randrange(0, width)
eBall[i][0] = x
instuct()
player.handle_keys()
pygame.display.flip()
clock.tick(30)
希望这可以帮助
添加回答
举报
0/150
提交
取消