我对编程很陌生,我需要一种方法来限制变量food_choice的随机性,这样它就不会在我的游戏屏幕上打印大量的图像。
这是我的一段代码。我认为问题是因为我的函数draw_food()在主循环中,这意味着每次游戏以确定的滴答运行时,函数draw_food()就会再次运行,选择另一个食物,导致无休止的随机化。我需要把这种随机化限制在每x秒一次。
def draw_food():
food_choice = random.choice(food_types)
for object in object_list[:]:
screen.blit(food_choice, (foodx, foody))
object.deter -= 0.035
if object.deter < 1:
object_list.remove(object)
def draw_game_window():
screen.blit(bg, (0, 0))
draw_food()
cat.draw(screen)
pygame.display.update()
# main loop
cat = player(200, 355, 67, 65)
run = True
object_list = []
time_interval = 5000 # 200 milliseconds == 0.2 seconds
next_object_time = 0
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
draw_game_window()
current_time = pygame.time.get_ticks()
if current_time > next_object_time:
next_object_time += time_interval
object_list.append(Object())
pygame.quit()```发布于 2021-12-18 02:35:54
您可以像这样每秒钟创建一个randomizeFood事件。
randomizeFood = pygame.USEREVENT + 0
pygame.time.set_timer(randomizeFood, 1000) #time in ms然后在事件循环中,在生成此事件时创建随机食物。
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == randomizeFood:
food_choice = random.choice(food_types)发布于 2021-12-18 08:57:54
正如答案中已经解释的那样,Eiter使用计时器事件,或者使用pygame.time.get_ticks。此函数返回自应用程序启动以来的毫秒数。
使用全局变量来存储时间和食物。您必须使用global statement更改函数中的全局变量。
food_choice = None
next_choice_time = 0
def draw_food():
current_time = pygame.time.get_ticks()
if current_time >= next_choice_time:
next_choice_time = current_time + 1000 # in 1 second (1000 millisecodns)
food_choice = random.choice(food_types)https://stackoverflow.com/questions/70400145
复制相似问题