用Python带你制作小时候玩的“大富翁”(文末赠书)-LMLPHP

 

目录

首先

接下来需要定义各种类型的物业,包括普通物业、铁路、公用事业等等。

接下来需要定义一些特殊的位置,比如Jail、Free Parking、Go To Jail等等。

然后需要定义一些Chance和Community Chest卡片

最后,需要定义一个Game类

完整代码

本期推荐


首先

需要定义一个Player类来跟踪每个玩家的状态,包括姓名、当前拥有的资金、当前所处的位置以及已经购买的物业信息。此外还需要一些方法,比如移动、支付、收取资金、破产等等。

class Player:
    def __init__(self, name, money):
        self.name = name
        self.money = money
        self.position = 0
        self.properties = []
        
    def move(self, steps):
        self.position = (self.position + steps) % 40  # 地图总共40个位置
        print(self.name, 'moved to position', self.position)
        
    def pay(self, amount):
        self.money -= amount
        print(self.name, 'paid', amount, 'and now has', self.money)
        
    def receive(self, amount):
        self.money += amount
        print(self.name, 'received', amount, 'and now has', self.money)
        
    def bankrupt(self):
        print(self.name, 'is bankrupt!')

接下来需要定义各种类型的物业,包括普通物业、铁路、公用事业等等。

每种物业都有自己的名字、价格、租金等属性,同时还有一些特殊的方法,比如购买、支付租金、升级等等。

class Property:
    def __init__(self, name, cost, rent):
        self.name = name
        self.cost = cost
        self.rent = rent
        self.owner = None
    
    def pay_rent(self, player):
        player.pay(self.rent)
        
    def buy(self, player):
        player.pay(self.cost)
        player.properties.append(self)
        self.owner = player
        
    def land_on(self, player):
        if self.owner is None:
            action = input('Do you want to buy ' + self.name + ' for ' + str(self.cost) + '? (y/n) ')
            if action.lower() == 'y':
                self.buy(player)
                
        elif self.owner == player:
            print('You already own', self.name)
            
        else:
            self.pay_rent(player)
            
    def __str__(self):
        return self.name

class Street(Property):
    def __init__(self, name, cost, rent, color):
        super().__init__(name, cost, rent)
        self.color = color
        self.houses = 0
    
    def pay_rent(self, player):
        amount = self.rent[self.houses]
        player.pay(amount)
        
    def build_house(self):
        self.houses += 1
        print('Built a house on', self.name)
        self.rent = self.rent[:self.houses] + [self.rent[self.houses] * 2] + self.rent[self.houses+1:]
        
    def __str__(self):
        return super().__str__() + ' (' + self.color + ')'

class Utility(Property):
    def __init__(self, name, cost):
        super().__init__(name, cost, None)
        
    def pay_rent(self, player, steps):
        amount = steps * 10 if self.owner.utilities_owned == 1 else steps * 20
        player.pay(amount)
        
class Railroad(Property):
    def __init__(self, name, cost):
        super().__init__(name, cost, [25, 50, 100, 200])
        
    def pay_rent(self, player):
        amount = self.rent[self.owner.railroads_owned-1]
        player.pay(amount)

接下来需要定义一些特殊的位置,比如Jail、Free Parking、Go To Jail等等。

class Jail(Property):
    def __init__(self):
        super().__init__('Jail', None, None)

class FreeParking(Property):
    def __init__(self):
        super().__init__('Free Parking', None, None)

class GoToJail(Property):
    def __init__(self):
        super().__init__('Go To Jail', None, None)

然后需要定义一些Chance和Community Chest卡片

,包括描述、执行的操作以及可能涉及到的金额等等。当玩家经过Chance或Community Chest位置时,需要随机抽取一张卡片并执行对应的操作。

class Chance:
    def __init__(self, description, action, amount=0):
        self.description = description
        self.action = action
        self.amount = amount
        
    def execute(self, player, game):
        if self.action == 'move':
            player.move(self.amount)
            game.land_on(player)
        elif self.action == 'pay':
            player.pay(self.amount)
        elif self.action == 'receive':
            player.receive(self.amount)

class CommunityChest:
    def __init__(self, description, action, amount=0):
        self.description = description
        self.action = action
        self.amount = amount
        
    def execute(self, player):
        if self.action == 'move':
            player.move(self.amount)
        elif self.action == 'pay':
            player.pay(self.amount)
        elif self.action == 'receive':
            player.receive(self.amount)

最后,需要定义一个Game类

用于管理整个游戏的进程。在游戏开始时,需要随机分配玩家的位置和顺序。每一轮玩家依次行动,根据投掷的骰子数目移动到新的位置,然后执行该位置对应的操作,包括支付租金、购买物业、抽取Chance和Community Chest卡片等等。如果一个玩家资金不够支付租金或遇到其他困难而破产,则该玩家退出游戏。当只剩下一个玩家时,游戏结束,该玩家获胜。

class Game:
    def __init__(self, players, properties, chances, community_chests):
        self.players = players
        self.properties = properties
        self.chances = chances
        self.community_chests = community_chests
        
    def land_on(self, player):
        property = self.properties[player.position]
        print(player.name, 'landed on', property)
        if isinstance(property, Property):
            property.land_on(player)
        elif isinstance(property, Chance):
            card = self.chances.pop(0)
            self.chances.append(card)
            print(player.name, 'picked a chance card:', card.description)
            card.execute(player, self)
        elif isinstance(property, CommunityChest):
            card = self.community_chests.pop(0)
            self.community_chests.append(card)
            print(player.name, 'picked a community chest card:', card.description)
            card.execute(player)
        
    def play(self):
        round_num = 1
        
        while True:
            print('\n----- Round', round_num, '-----\n')
            random.shuffle(self.players)
            for player in self.players:
                print('\n---', player.name, '---\n')
                dice_roll = random.randint(2, 12)
                print(player.name, 'rolled a', dice_roll)
                player.move(dice_roll)
                self.land_on(player)
                if player.money <= 0:
                    player.bankrupt()
                    self.players.remove(player)
                
                if len(self.players) == 1:
                    self.players[0].win()
                    return
                    
            round_num += 1

完整代码

因为不可能给大家把完整代码放这里,所以剩下的大家可以自行完善

import random

class Player:
    def __init__(self, name, money):
        self.name = name
        self.money = money
        self.position = 0
        self.properties = []
        self.railroads_owned = 0
        self.utilities_owned = 0
        
    def move(self, steps):
        self.position = (self.position + steps) % 21  # 地图总共21个位置
        print(self.name, 'moved to position', self.position)
        
    def pay(self, amount):
        self.money -= amount
        print(self.name, 'paid', amount, 'and now has', self.money)
        
    def receive(self, amount):
        self.money += amount
        print(self.name, 'received', amount, 'and now has', self.money)
        
    def bankrupt(self):
        print(self.name, 'is bankrupt!')
        
    def win(self):
        print(self.name, 'wins!')

class Property:
    def __init__(self, name, cost, rent):
        self.name = name
        self.cost = cost
        self.rent = rent
        self.owner = None
    
    def pay_rent(self, player):
        player.pay(self.rent)
        
    def buy(self, player):
        player.pay(self.cost)
        player.properties.append(self)
        self.owner = player
        
    def land_on(self, player):
        if self.owner is None:
            action = input('Do you want to buy ' + self.name + ' for ' + str(self.cost) + '? (y/n) ')
            if action.lower() == 'y':
                self.buy(player)
                
        elif self.owner == player:
            print('You already own', self.name)
            
        else:
            self.pay_rent(player)
            
    def __str__(self):
        return self.name

class Street(Property):
    def __init__(self, name, cost, rent, color):
        super().__init__(name, cost, rent)
        self.color = color
        self.houses = 0
    
    def pay_rent(self, player):
        amount = self.rent[self.houses]
        player.pay(amount)
        
    def build_house(self):
        self.houses += 1
        print('Built a house on', self.name)
        self.rent = self.rent[:self.houses] + [self.rent[self.houses] * 2] + self.rent[self.houses+1:]
        
    def __str__(self):
        return super().__str__() + ' (' + self.color + ')'

class Utility(Property):
    def __init__(self, name, cost):
        super().__init__(name, cost, None)
        
    def pay_rent(self, player, steps):
        amount = steps * 10 if self.owner.utilities_owned == 1 else steps * 20
        player.pay(amount)
        
class Railroad(Property):
    def __init__(self, name, cost):
        super().__init__(name, cost, [25, 50, 100, 200])
        
    def pay_rent(self, player):
        amount = self.rent[self.owner.railroads_owned-1]
        player.pay(amount)

class Chance:
    def __init__(self, description, action, amount=0):
        self.description = description
        self.action = action
        self.amount = amount
        
    def execute(self, player, game):
        if self.action == 'move':
            player.move(self.amount)
            game.land_on(player)
        elif self.action == 'pay':
            player.pay(self.amount)
        elif self.action == 'receive':
            player.receive(self.amount)

class Tax:
    def __init__(self, description, amount):
        self.description = description
        self.amount = amount
        
    def pay(self, player):
        player.pay(self.amount)
        
    def __str__(self):
        return self.description + ' (' + str(self.amount) + ')'

class CommunityChest:
    def __init__(self, description, action, amount=0):
        self.description = description
        self.action = action
        self.amount = amount
        
    def execute(self, player):
        if self.action == 'move':
            player.move(self.amount)
        elif self.action == 'pay':
            player.pay(self.amount)
        elif self.action == 'receive':
            player.receive(self.amount)

class Game:
    def __init__(self, players, properties, chances, taxes, community_chests):
        self.players = players
        self.properties = properties
        self.chances = chances
        self.taxes = taxes
        self.community_chests = community_chests
        
    def land_on(self, player):
        property = self.properties[player.position]
        print(player.name, 'landed on', property)
        if isinstance(property, Property):
            property.land_on(player)
        elif isinstance(property, Tax):
            property.pay(player)
        elif isinstance(property, Chance):
            card = self.chances.pop(0)
            self.chances.append(card)
            print(player.name, 'picked a chance card:', card.description)
            card.execute(player, self)
        elif isinstance(property, CommunityChest):
            card = self.community_chests.pop(0)
            self.community_chests.append(card)
            print(player.name, 'picked a community chest card:', card.description)
            card.execute(player)
        
    def play(self):
        round_num = 1
        
        while True:
            print('\n----- Round', round_num, '-----\n')
            for player in self.players:
                print('\n---', player.name, '---\n')
                dice_roll = random.randint(2, 12)
                print(player.name, 'rolled a', dice_roll)
                player.move(dice_roll)
                self.land_on(player)
                if player.money <= 0:
                    player.bankrupt()
                    self.players.remove(player)
                
                if len(self.players) == 1:
                    self.players[0].win()
                    return
                    
            round_num += 1

# 创建游戏地图和物业
properties = [Property('GO', 0, None),
              Street('Mediterranean Avenue', 60, [2, 10, 30, 90, 160, 250], 'brown'),
              Chance('Advance to St. Charles Place', 'move', 11),
              Street('Baltic Avenue', 60, [4, 20, 60, 180, 320, 450], 'brown'),
              Tax('Income Tax', 200),
              Railroad('Reading Railroad', 200),
              Street('Oriental Avenue', 100, [6, 30, 90, 270, 400, 550], 'light blue'),
              Chance('Advance to Boardwalk', 'move', 39),
              Street('Vermont Avenue', 100, [6, 30, 90, 270, 400, 550], 'light blue'),
              Street('Connecticut Avenue', 120, [8, 40, 100, 300, 450, 600], 'light blue'),
              Property('Jail', None, None),
              Street('St. Charles Place', 140, [10, 50, 150, 450, 625, 750], 'pink'),
              Utility('Electric Company', 150),
              Street('States Avenue', 140, [10, 50, 150, 450, 625, 750], 'pink'),
              Street('Virginia Avenue', 160, [12, 60, 180, 500, 700, 900], 'pink'),
              Railroad('Pennsylvania Railroad', 200),
              Street('St. James Place', 180, [14, 70, 200, 550, 750, 950], 'orange'),
              Chance('Advance to Illinois Avenue', 'move', 24),
              Street('Tennessee Avenue', 180, [14, 70, 200, 550, 750, 950], 'orange'),
              Street('New York Avenue', 200, [16, 80, 220, 600, 800, 1000], 'orange'),
              Property('Free Parking', None, None),
              Street('Kentucky Avenue', 220, [18, 90, 250, 700, 875, 1050], 'red'),
              Chance('Advance to Boardwalk', 'move', 39),
              Street('Indiana Avenue', 220, [18, 90, 250, 700, 875, 1050], 'red'),
              Street('Illinois Avenue', 240, [20, 100, 300, 750, 925, 1100], 'red'),
              Railroad('B.&O. Railroad', 200),
              Street('Atlantic Avenue', 260, [22, 110, 330, 800, 975, 1150], 'yellow'),
              Street('Ventnor Avenue', 260, [22, 110, 330, 800, 975, 1150], 'yellow'),
              Utility('Water Works', 150),
              Street('Marvin Gardens', 280, [24, 120, 360, 850, 1025, 1200], 'yellow'),
              Property('Go To Jail', None, None),
              Street('Pacific Avenue', 300, [26, 130, 390, 900, 1100, 1275], 'green'),
              Street('North Carolina Avenue', 300, [26, 130, 390, 900, 1100, 1275]

以上是一个简单的大富翁游戏的代码框架和一些示例代码,希望能对您有帮助。这只是一个初步的代码,还需要根据需求进行优化和完善。

用Python带你制作小时候玩的“大富翁”(文末赠书)-LMLPHP

本期推荐

用Python带你制作小时候玩的“大富翁”(文末赠书)-LMLPHP

当当销售链接:《Web安全攻防从入门到精通 红日安全出品》(红日安全)【简介_书评_在线阅读】 - 当当图书

06-26 02:28