在python中一次绘制并移动多个图像对象

时间:2017-06-25 08:37:17

标签: python zelle-graphics

我是Python的新手并且是自学的,因此需要很多帮助。我正在尝试使用John Zelle编写的graphics.py包来一次显示,绘制和移动多个图像对象。

我有一个Enemy类对象,它接受速度,startX位置是一个startY位置。我在这个类中也有一个移动方法,它将采用startX位置并将其添加到速度。

class Enemy(object):

    def __init__(self, speed, startXpos, startYpos):
        self.speed = speed
        self.x = startXpos
        self.y = startYpos

    def move(self):
        self.x += self.speed

在main方法中,我使用graphics.py绘制Enemy的Image对象。所有敌人都有相同的图像并从相同的起始位置开始,但敌人的移动速度不同。

    win = GraphWin("Enemy", 1000, 500)
    myEnemies = []

    e = Image(Point(50, 200), "enemy.gif")  # use speed as y position, too
    e.draw(win)  # add it to the window
    e2 = Image(Point(50, 200), "enemy.gif")  # use speed as y position, too
    e2.draw(win)  # add it to the window
    e3 = Image(Point(50, 200), "enemy.gif")  # use speed as y position, too
    e3.draw(win)  # add it to the window

    enemy1 = Enemy(40, 50, 0)
    enemy2= Enemy(50, 50, 0)
    enemy3 = Enemy(60,50, 0)
    myEnemies.append((enemy1,e))
    myEnemies.append((enemy2,e2))
    myEnemies.append((enemy3,e3))

    for i in range(40):  # main animation loop
        for enemy in myEnemies:  # loop through the enemy list
            enemy[0].move()  
            time.sleep(1)  # wait a second...
    win.close()

图像对象无法移动。我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

通过不接受敌人的对象性质,你使问题变得更加困难:

from graphics import *

class Enemy(object):

    def __init__(self, speed, startXpos, startYpos):
        self.speed = speed
        self.x = startXpos
        self.y = startYpos

        self.graphic = Image(Point(startXpos, startYpos), "enemy.gif")
        self.graphic.draw(win)

    def move(self):
        self.x += self.speed
        self.graphic.move(self.speed, 0)


win = GraphWin("Enemy", 1000, 500)

myEnemies = [Enemy(40, 50, 100), Enemy(50, 50, 200), Enemy(60, 50, 300)]

for i in range(40):  # main animation loop
    for enemy in myEnemies:  # loop through the enemy list
        enemy.move()
        time.sleep(1)  # wait a second...

win.close()

不要将图像与对象分开处理,使图像只是对象的一个​​方面。