import pygame
import random
black = (0,0,0)
white = (255,255,255)
green = (0,255,0)
red = (255,0,0)
screen = pygame.display.set_mode((1200, 600))
title = pygame.display.set_caption("Speeding cars")
clock = pygame.time.Clock()
clock.tick(60)
class Car:
def __init__(self, x, y, height, width):
self.x = x
self.y = y
self.height = height
self.width = width
def drive(self, change):
self.change = random.randint(1, 2)
self.x += self.change
pygame.draw.rect(screen, black, (self.x, self.y, self.height, self.width))
def again(self):
while True:
if self.x + 50 > 1200:
for car in cars:
car.drive(False)
cars = []
for i in range(1, 6):
cars.append(Car(0, i*100, 50, 25))
driving = True
while driving:
screen.fill(white)
for car in cars:
car.drive(False)
car.again()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.flip()
每当我尝试运行此代码时,我的pygame窗口就会停止响应。我注意到的事情是,每当我删除def again(self):
代码块时,我的winodw都可以正常工作,但是我希望这些块在屏幕上消失后再次出现。谢谢。
答案 0 :(得分:1)
您已经在again
中实现了无限循环:
def again(self): while True: if self.x + 50 > 1200: for car in cars: car.drive(False)
注意,again
在主应用程序循环中被调用,并且每辆车都被调用:
while driving: # [...] for car in cars: # [...] car.again()
如果要将所有赛车设置在其初始位置,则当1辆赛车到达赛道终点时,则必须验证是否有任何一辆赛车到达赛道终点,并估算{{1 }}所有汽车的坐标0:
.x
或更短
finished = [car for car in cars if car.x + 50 > 1200]
if len(finished) > 0:
for car in cars:
car.x = 0
在主应用程序循环中进行评估:
if any([car for car in cars if car.x + 50 > 1200]):
for car in cars:
car.x = 0
如果您想保持每辆车的位置,则只需在起点到达轨道终点(driving = True
while driving:
screen.fill(white)
for car in cars:
car.drive(False)
if any([car for car in cars if car.x + 50 > 1200]):
for car in cars:
car.x = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
pygame.display.flip()
)时设置一辆车即可:
car.x -= 1200
class Car:
# [...]
def again(self):
if self.x + 50 > 1200:
self.x -= 1200