Python:为什么我的两个对象同时移动?

时间:2017-10-26 04:03:11

标签: python class

基本上每当我按下left,right,a或d时,它会移动两个字符而不是一个字符。我已经尝试在更新之前和之后包含打印语句,我已经四处询问并被告知这是一个别名问题,但我仍然无法找到解决方案。我是否需要制作两个单独的课程,或者我在某些代码中做错了什么?

import simplegui

WIDTH = 800
HEIGHT = 600
#class for character
class Character:
    def __init__(self, pos, radius, vel = [0,0]):
        self.pos = pos
        self.vel = vel
        self.radius = radius
#updates position
    def update(self, state):
        self.pos[0] += self.vel[0]
        self.pos[1] += self.vel[1]
#moving left and right
    def change_left_vel(self):
        self.vel[0] -= 2
    def change_right_vel(self):
        self.vel[0] += 2
#draws character
    def draw(self, canvas, state):
        canvas.draw_circle(self.pos, self.radius, 5, "White", "White")    
#initializes characters and frame
class GameState:
    def __init__(self):
        self.frame = simplegui.create_frame("Super Smash Squad", WIDTH, HEIGHT)
        self.frame.set_keydown_handler(self.keydown)
        self.frame.set_keyup_handler(self.keyup)
        self.frame.set_draw_handler(self.draw)        
        self.char1 = Character([200, 200], 15)
        self.char2 = Character([400, 200], 25)
        self.frame.start()
#movement for both characters
    def keydown(self, key):
        if key == simplegui.KEY_MAP["a"]:
            self.char1.change_left_vel()
        elif key == simplegui.KEY_MAP["d"]:
            self.char1.change_right_vel()
        elif key == simplegui.KEY_MAP["left"]:
            self.char2.change_left_vel()
        elif key == simplegui.KEY_MAP["right"]:
            self.char2.change_right_vel()    
    def keyup(self, key):
        if key == simplegui.KEY_MAP["a"]:
            self.char1.change_right_vel()
        elif key == simplegui.KEY_MAP["d"]:
            self.char1.change_left_vel()
        elif key == simplegui.KEY_MAP["left"]:
            self.char2.change_right_vel()
        elif key == simplegui.KEY_MAP["right"]:
            self.char2.change_left_vel()    
#draws everything
    def draw(self, canvas):
        self.char1.update(self)
        self.char2.update(self)
        self.char1.draw(canvas, self)
        self.char2.draw(canvas, self)
# start frame
GameState()

0 个答案:

没有答案