1
class Ship:

    def __init__(self, pos, vel, angle, image, info):
        self.pos = [pos[0],pos[1]]
        self.vel = [vel[0],vel[1]]


def keydown(key):

    global current_key

    current_key=simplegui.KEY_MAP['down']

    pos_increment=15
    posx=Ship.shipx
    posy=Ship.shipy

    print current_key
    print posx,posy

错误是 AttributeError:'Ship' 对象没有属性 'shipx'。请帮助

4

2 回答 2

2

您必须先实例化您的类:

ship1 = Ship( pos, vel, angle, image, info)

之后,您可以使用类方法和属性:

posx, posy = ship1.pos

根据我们的评论,我认为这将满足您的需求:

class Ship:

    def __init__(self, pos, vel, angle, image, info):
        self.pos = list(pos)
        self.vel = list(vel)

    def move(self, key):
        if key=='left':  self.pos[0] -= self.vel[0]
        if key=='right': self.pos[0] += self.vel[0]
        if key=='down':  self.pos[1] -= self.vel[1]
        if key=='up':    self.pos[1] += self.vel[1]


#example
ship1 = Ship( (0,0), (10,10), angle=None, image=None, info='')

def keystroke(key):
    global current_key
    ship1.move(key)

我不确定它是如何simplegui工作的,但是通过这种方式,您可以有效地映射所有击键的可能性。此外,假设速度 ( vel) 表示每次击键要改变多少像素。

于 2013-06-06T18:03:49.237 回答
1

您必须先定义 shipx 和 shipy 才能访问它们或使用 pos 变量:

class Ship:
    def __init__(self, pos, vel, angle, image, info):
        self.pos = pos
        self.vel = vel

# create instance of your ship
ship = Ship(pos, vel, angle, image, info)

def keydown(key):
    global current_key

    current_key = simplegui.KEY_MAP['down']

    pos_increment = 15
    # change y-position of the ship on key press
    ship.pos[1] += pos_increment
于 2013-06-06T18:08:43.793 回答