gpt4 book ai didi

python - 如何在不调用函数的情况下将函数插入数组?

转载 作者:太空宇宙 更新时间:2023-11-03 13:55:57 24 4
gpt4 key购买 nike

我有这个 pygame 代码,它有一些功能,我希望能够将函数 apple1() 和 apple2() 放在列表中而不立即调用它,然后能够从列表中调用它。

这是我尝试过的:

 #for all the apple
def apple1():
pygame.draw.rect(screen,COLOR.GREEN, [ posR,posU, apblock, apblock])

def apple2():
pygame.draw.rect(screen,COLOR.RED, [ posiR,posiU, apblock, apblock])

def random_apple():
array = [apple1(),apple2()]
i = random.randrange(0,1)

x = array[i]
return x

def time_apple():
while time == True:
random_apple()
time.sleep(5)

最佳答案

从他们的名字中删除括号。

此外,我认为您要么想要使用 randrange(0,2) 要么使用 randint(0,1)

def random_apple():
array = [apple1,apple2]
i = random.randrange(0,2)

x = array[i]
return x()

编辑:对于稍微更 Pythonic 的解决方案,避免需要 random_apple 函数,您可以考虑:

# import as needed
import random
import pygame
import time

#for all the apple
def apple1():
pygame.draw.rect(screen,COLOR.GREEN, [ posR,posU, apblock, apblock])

def apple2():
pygame.draw.rect(screen,COLOR.RED, [ posiR,posiU, apblock, apblock])

def time_apple():
while time == True:
random.choice([apple1, apple2])()
time.sleep(5)

关于python - 如何在不调用函数的情况下将函数插入数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55615792/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com