首页 > 解决方案 > Python OOP - 足球模拟

问题描述

我是 OOP 的新手。我想模拟一场足球比赛。如何访问 Player/Offender/Defender 类中的 Play 实例变量?如果其他结构更好,请帮助。

class Player:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def move_to(self, x, y):
        self.x = (self.x + x) / 2
        self.y = (self.y + y) / 2

    ## Loop through Play.Players to find nearest. How do I access Play.Players?
    def nearest(self):
        return nearest

class Offender(Player):
    def __init__(self, x, y):
        super().__init__(x, y)

    # Move to ball.
    def strategy():
        ball_x = Play.ball_x # how do I access Play.ball_x
        ball_y = Play.ball_y # how do I access Play.ball_y
        self.move_to(ball_x, ball_y)

class Defender(Player):
    def __init__(self, x, y):
        super().__init__(x, y)

    # Move to nearest player
    def strategy(self):
        nearest = self.nearest()
        self.move_to(nearest)          

class Play:
    def __init__(self, offense_players, defense_players, ball_x, ball_y):
        self.offense = [Offender(player) for player in offense_players]
        self.defense = [Defender(player) for player in defense_players]
        self.players = self.offense + self.defense
        self.ball_x = ball_x
        self.ball_y = ball_y

    def simulate(self):
        while True:
            for player in self.players:
                player.strategy()

if __name__ == "__main__":
    Play().simulate()

Offender我没有和班级,而是Defender为每个职位都有一个,即Striker(Player), Midfielder(Player),Goalie(Player)等。这就是为什么我想将它们各自存储strategy在他们的班级而不是Play班级中的原因。

标签: pythonpython-3.xoop

解决方案


不确定这对您有多大帮助,因为实现是在 C++ 中

您可以查看我的实现以获取类似的问题陈述https://github.com/rimpo/footballcpp

要了解为上述机器人编写的街机游戏框架实现,请查看http://richard-shepherd.github.io/coding-world-cup/index.html


推荐阅读