[英]Code will not work as function but does in the main code. (Python, pygame)
我一直在试验 pygame 并且遇到了问题。 我为创建基于时间的事件而编写的代码只能在 function 之外工作。 我错过了什么吗?
def drop_obs(obs_list, timer):
timer += clock.tick(60)/1000
if timer >= 2:
x_obs_pos = WIDTH/2
y_obs_pos = random.randint(0, HEIGHT - block_size)
obs_list.append([x_obs_pos, y_obs_pos])
timer = 0
如果我将代码粘贴到主代码中,它会起作用。 (关于此代码,目标只是 append 一个新的 x 和 y position 到一个已经存在的列表,只要时钟滴答作响)
尝试将预定义的全局变量作为 arguments 传递给drop_obs()
function
timer1 = 0
list1 = [] #can be pre-emptied or pre-filled
[...] #the other part of code
def drop_obs(obs_list,timer):
timer += clock.tick(60)/1000
if time >=2:
x_obs_pos = WIDTH/2
y_obs_pos = random.randint(0,HEIGHT - block_size)
obs_list.append([x_obs_pos, y_obs_pos])
timer = 0
drop_obs(list1,timer1)
此外,如果x_obs_pos
和y_obs_pos
是局部变量(即它们在函数中定义),那么您需要使用语句global x_obs_pos
和global y_obs_pos
将其全球化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.