嗨,我正在尝试编程的街机游戏小行星,并已使它这样当用户按下空格键,一个圆圈被创建在'船'目前的位置,其位置添加到'球'列表',而船舶的水平和垂直速度存储为新的圆圈的速度在'球'列表',如图所示
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
当我运行整个程序时,飞船以我最初给它的速度移动,正如我预期的那样。然而,当我按下空格键时,它会加速,我不知道为什么。我发现是这条线造成了问题:
^{pr2}$因为当我说出来的时候,当空格键按下时,飞船会正常运行。append会改变船的位置吗?我检查过飞船的速度(船速)即使在加速时也保持不变。。在
谢谢你的帮助!如果您需要额外的上下文,以下是整个程序:
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()
问题是在数组中追加一个列表时,该列表仍作为引用。在
示例:
试试这个:
当您附加
ship_pos
(和ship_vel
)时,实际上是在附加相同的列表。ball_list[0]
现在将引用与ship_pos
相同的列表。这意味着如果您更改一个(例如ball_list[0][0] = 5
),那么另一个也将被更改(ship_pos[0] == 5
)。在您可以通过使用
[:]
复制列表来解决此问题,以便现在附加列表的新副本。在我觉得这些都没有道理,所以下面的代码可能会有帮助:
^{pr2}$相关问题 更多 >
编程相关推荐