【问题标题】:How can I pass a value from one class to another using onkeypress?如何使用 onkeypress 将值从一个类传递到另一个类?
【发布时间】:2021-11-25 14:57:31
【问题描述】:

我正在尝试构建一个船舶应该射击一些东西的游戏,我正在尝试获取船舶位置并将其传递给生成射击的函数,但我不能这样做,我尝试了以下方法:

ship.py

def __init__(self):
    super().__init__()
    self.ship = Turtle(shape='turtle')
    self.ship.penup()
    self.ship.color('white')
    self.ship.goto(0, -250)
    self.ship.left(90)
    self.x = self.ship.xcor()

def get_pos(self):
    return self.x

shoot.py

def shoot_now(self, pos):
        print(pos)  

首先尝试使用 ship.get_pos() main.py

screen.onkeypress(functools.partial(shots.shoot_now, ship.get_pos()), 'space')

第二次尝试 wuth ship.get_pos

screen.onkeypress(functools.partial(shots.shoot_now, ship.get_pos), 'space')

第一个结果是很多 0,第二个结果是这样的:

<bound method Ship.get_pos of <ship.Ship object at 0x000001F05339A520>>

我知道函数 get_pos 正在工作,因为每次我单独运行它时它都会打印正确的位置,但是当我尝试使用 onkeypress 将值传递给 shoot.py 时它不起作用。

有人知道让它工作的方法吗?

【问题讨论】:

    标签: python python-turtle


    【解决方案1】:

    我的猜测是,当调用 onkeypress() 时,您将锁定船的位置一次,并且所有后续按键都使用该原始值。

    除了船的位置,你还需要知道子弹发射时船的航向。为了简化编程,我会同时使用 ship 和 bullet be 海龟,而不是 contain 海龟,尽管两者都可以。

    如果您想阻止子弹的运动锁定飞船的运动,您将需要一个计时器。这是一个最小的实现,它可以为您提供一个不会冻结飞船运动的移动子弹:

    from turtle import Screen, Turtle
    
    class Bullet(Turtle):
    
        def __init__(self):
            super().__init__()
    
            self.hideturtle()
            self.shape('circle')
            self.shapesize(0.25)
            self.penup()
    
            self.origin = (0, 0)
    
        def fire(self, origin, heading):
            self.origin = origin
    
            self.setheading(heading)
            self.setposition(origin)
            self.showturtle()
            self.move()
    
        def move(self):
            if self.distance(self.origin) < 500:
                self.forward(5)
                screen.ontimer(self.move, 5)
            else:
                self.hideturtle()
    
    class Ship(Turtle):
    
        def __init__(self):
            super().__init__()
    
            self.shape('triangle')
            self.penup()
            self.sety(-250)
            self.left(90)
    
        def shoot_now(self):
            if not bullet.isvisible():
                bullet.fire(self.position(), self.heading())
    
    screen = Screen()
    bullet = Bullet()
    ship = Ship()
    
    screen.onkeypress(lambda: ship.right(5), 'Right')
    screen.onkeypress(lambda: ship.left(5), 'Left')
    screen.onkeypress(ship.shoot_now, 'space')
    
    screen.listen()
    screen.mainloop()
    

    要将其扩展到多个活动子弹,您可以保留一个不活动子弹列表,在您开火时从中提取,在子弹用完时添加回它。这也让您可以控制游戏中的子弹数量。

    【讨论】:

    猜你喜欢
    • 2013-03-16
    • 1970-01-01
    • 2011-08-26
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多