我有这个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)
答案 0 :(得分:4)
从括号中删除括号。
此外,我认为您可能想使用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)
答案 1 :(得分:1)
输入这些可调用对象的名称:
array = [apple1,apple2]
,然后将调用更改为
random_apple()()