大富翁游戏是一个比较复杂的游戏,需要涉及到很多方面的知识,包括游戏规则、玩家交互、随机事件等等。以下是一个简单的Python大富翁游戏代码示例,供您参考:
import random
class Player:
def __init__(self, name, money):
self.name = name
self.money = money
self.position = 0
def move(self, steps):
self.position += steps
if self.position >= 40:
self.position -= 40
self.money += 200
def pay_rent(self, amount):
self.money -= amount
def receive_rent(self, amount):
self.money += amount
class Property:
def __init__(self, name, price, rent):
self.name = name
self.price = price
self.rent = rent
self.owner = None
def buy(self, player):
self.owner = player
player.money -= self.price
def pay_rent(self, player):
player.pay_rent(self.rent)
self.owner.receive_rent(self.rent)
class Game:
def __init__(self, players):
self.players = players
self.properties = [
Property("起点", 0, 0),
Property("长沙", 60, 2),
Property("公交车", 0, 0),
Property("深圳", 100, 4),
Property("机会", 0, 0),
Property("北京", 200, 6),
Property("上海", 150, 8),
Property("医院", 0, 0),
Property("广州", 180, 10),
Property("机会", 0, 0),
Property("深圳", 100, 4),
Property("长沙", 60, 2),
Property("公交车", 0, 0),
Property("北京", 200, 6),
Property("上海", 150, 8),
Property("机会", 0, 0),
Property("广州", 180, 10),
Property("长沙", 60, 2),
Property("公交车", 0, 0),
Property("深圳", 100, 4),
Property("机会", 0, 0),
Property("北京", 200, 6),
Property("上海", 150, 8),
Property("医院", 0, 0),
Property("广州", 180, 10),
Property("机会", 0, 0),
Property("长沙", 60, 2),
Property("公交车", 0, 0),
Property("深圳", 100, 4),
Property("北京", 200, 6),
Property("上海", 150, 8),
Property("机会", 0, 0),
Property("广州", 180, 10),
Property("终点", 0, 0)
]
self.current_player = 0
def next_player(self):
self.current_player += 1
if self.current_player >= len(self.players):
self.current_player = 0
def play(self):
while True:
player = self.players[self.current_player]
print("轮到玩家 %s" % player.name)
steps = random.randint(1, 6)
print("玩家 %s 掷骰子,前进 %d 步" % (player.name, steps))
player.move(steps)
property = self.properties[player.position]
if property.price > 0:
if property.owner is None:
print("玩家 %s 到达 %s,可以购买该地产,价格为 %d" % (player.name, property.name, property.price))
choice = input("是否购买?(y/n)")
if choice == "y":
property.buy(player)
print("玩家 %s 购买了 %s" % (player.name, property.name))
else:
print("玩家 %s 放弃购买 %s" % (player.name, property.name))
elif property.owner != player:
print("玩家 %s 到达 %s,需要支付 %d 的租金给 %s" % (player.name, property.name, property.rent, property.owner.name))
property.pay_rent(player)
elif property.name == "机会":
print("玩家 %s 到达 机会,获得一次机会" % player.name)
elif property.name == "医院":
print("玩家 %s 到达 医院,需要休息一回合" % player.name)
elif property.name == "公交车":
print("玩家 %s 到达 公交车,可以免费前往任意一处地产" % player.name)
elif property.name == "起点":
print("玩家 %s 到达 起点,获得 200 元奖励" % player.name)
player.money += 200
elif property.name == "终点":
print("玩家 %s 到达 终点,游戏结束" % player.name)
break
self.next_player()
players = [
Player("玩家1", 1000),
Player("玩家2", 1000),
Player("玩家3", 1000),
Player("玩家4", 1000)
]
game = Game(players)
game.play()
运行效果