I have been experimenting with pygame and I have run into a problem. The code I have written with the intent of creating a timing based event, will only work outside of a 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)
Try passing pre-defined global variables as the arguments for the 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.