嗨,我正在尝试对街机游戏小行星进行编程,并且已经做到了,当用户按下空格键时,会在“船”当前所在的位置创建一个圆圈,并将其位置添加到“ball_list”,而船的水平和垂直速度是存储为“ball_vlist”中的新圆的速度,如图所示
def draw(canvas):
global ship_pos, ship_vel, ball_list
if current_key=='32': # if spacebar is pressed
ball_list.append(ship_pos) # create a new circle and store is position
ball_vlist.append(ship_vel) # add a velocity to this new circle
当我运行整个程序时,船以我最初给它的速度移动,正如我所期望的那样。但是,当我按空格键时,它会加速,我不知道为什么。我发现这条线导致了问题:
ball_list.append(ship_pos)
因为当我将其注释掉时,按下空格键时船会正常继续。追加是否以某种方式改变了船的位置?我检查过船的速度(ship_vel)即使在船加速时也保持不变。
感谢您的任何帮助!如果您需要额外的上下文,这里是整个程序:
import simplegui
ball_list = []
ball_vlist = []
ship_pos = [200, 400]
ship_vel = [.5, -.5]
current_key=' '
frame = simplegui.create_frame("Asteroids", 800, 500)
def tick():
global ball_list, ball_vlist, ship_pos
# update the ship position
ship_pos[0] += ship_vel[0]
ship_pos[1] += ship_vel[1]
# update the ball positions
for i in range(len(ball_list)):
ball_list[i][0]+=ball_vlist[i][0]
ball_list[i][1]+=ball_vlist[i][1]
def draw(canvas):
global ship_pos, ship_vel, ball_list
if current_key=='32':
ball_list.append(ship_pos)
ball_vlist.append(ship_vel)
for ball_pos in ball_list:
canvas.draw_circle(ball_pos, 1, 1, "white", "white") # these are the circles the ship shoots
canvas.draw_circle(ship_pos, 4, 1, "red", "green") # this is my 'ship' (just to test)
def keydown(key):
global current_key
current_key = str(key)
def keyup(key):
global current_key
current_key=' '
timer = simplegui.create_timer(10, tick)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.set_draw_handler(draw)
frame.start()
timer.start()