[英]Code will not work as function but does in the main code. (Python, pygame)
I have been experimenting with pygame and I have run into a problem.我一直在试验 pygame 并且遇到了问题。 The code I have written with the intent of creating a timing based event, will only work outside of a function.
我为创建基于时间的事件而编写的代码只能在 function 之外工作。 Am I missing something?
我错过了什么吗?
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
If I paste the code inside the main code it works however.如果我将代码粘贴到主代码中,它会起作用。 (In regards to this code, the goal is just to append a new x and y position to an already existing list ever time the clock ticks)
(关于此代码,目标只是 append 一个新的 x 和 y position 到一个已经存在的列表,只要时钟滴答作响)
Try passing pre-defined global variables as the arguments for the drop_obs()
function尝试将预定义的全局变量作为 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)
Also if x_obs_pos
and y_obs_pos
are local variables (ie they are defined in a function) then you need to globalize it by using the statement global x_obs_pos
and global y_obs_pos
此外,如果
x_obs_pos
和y_obs_pos
是局部变量(即它们在函数中定义),那么您需要使用语句global x_obs_pos
和global y_obs_pos
将其全球化
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.