python大富翁游戏实现代码
时间: 2023-07-23 22:40:54 浏览: 249
大富翁的代码
下面是一个简单的 Python 大富翁游戏实现代码,仅供参考:
```python
import random
# 定义玩家类
class Player:
def __init__(self, name):
self.name = name
self.money = 1000
self.position = 0
def __str__(self):
return f"{self.name} 当前资产为 {self.money}"
# 玩家掷骰子
def roll_dice(self):
input(f"{self.name} 按回车键掷骰子:")
point = random.randint(1, 6)
print(f"{self.name} 掷得了 {point} 点")
self.position += point
if self.position >= 20:
self.position -= 20
self.money += 200
print(f"{self.name} 经过起点,获得了 200 元")
# 定义地图类
class Map:
def __init__(self):
self.places = [
"起点", "长沙", "广州", "深圳", "厦门",
"天津", "上海", "南京", "杭州", "成都",
"重庆", "武汉", "郑州", "济南", "西安",
"太原", "沈阳", "哈尔滨", "青岛", "大连"
]
def __getitem__(self, index):
return self.places[index]
# 定义游戏类
class Game:
def __init__(self, player_names):
self.players = [Player(name) for name in player_names]
self.map = Map()
# 打印游戏状态
def print_status(self):
for player in self.players:
print(player)
print("")
# 判断游戏是否结束
def is_game_over(self):
return any(player.money <= 0 for player in self.players)
# 进行一轮游戏
def play_round(self):
for player in self.players:
player.roll_dice()
place = self.map[player.position]
print(f"{player.name} 来到了 {place}")
if place == "起点":
continue
elif place == "长沙":
player.money -= 100
print(f"{player.name} 花费 100 元在长沙住了一晚")
elif place == "广州":
player.money -= 200
print(f"{player.name} 花费 200 元在广州住了一晚")
elif place == "深圳":
player.money -= 300
print(f"{player.name} 花费 300 元在深圳住了一晚")
elif place == "厦门":
player.money -= 400
print(f"{player.name} 花费 400 元在厦门住了一晚")
else:
money = random.randint(-200, 200)
player.money += money
if money >= 0:
print(f"{player.name} 在 {place} 赚了 {money} 元")
else:
print(f"{player.name} 在 {place} 亏了 {-money} 元")
# 开始游戏
def start(self):
print("游戏开始!")
while not self.is_game_over():
self.print_status()
self.play_round()
print("游戏结束!")
# 测试游戏
game = Game(["小明", "小红"])
game.start()
```
注意:这是一个简单的实现,游戏规则可以根据需求进行修改和扩展。
阅读全文