帮我写WUMPUS代码
时间: 2024-12-20 07:09:26 浏览: 18
Wumpus World是一个经典的文本冒险游戏,玩家在一个洞穴地图中寻找金子并避免遇到恐怖的瓦普斯(一种会发射毒气和刺人的怪物)。以下是一个简单的Wumpus World的Python代码版本,这个版本基于命令行交互:
```python
import random
class Cave:
def __init__(self, width, height):
self.width = width
self.height = height
self.map = [[' ' for _ in range(width)] for _ in range(height)]
self.wumpus = {'x': None, 'y': None}
self.gold = {'x': None, 'y': None}
def place_wumpus(self):
x, y = random.randint(0, self.width - 1), random.randint(0, self.height - 1)
while [x, y] == self.gold['x'], [x, y] == self.wumpus['x'] or self.map[y][x] != ' ':
x, y = random.randint(0, self.width - 1), random.randint(0, self.height - 1)
self.wumpus['x'], self.wumpus['y'] = x, y
self.map[y][x] = 'W'
def place_gold(self):
self.gold['x'], self.gold['y'] = random.randint(0, self.width - 1), random.randint(0, self.height - 1)
while self.map[self.gold['y']][self.gold['x']] != ' ':
self.gold['x'], self.gold['y'] = random.randint(0, self.width - 1), random.randint(0, self.height - 1)
self.map[self.gold['y']][self.gold['x']] = 'G'
def move_player(self, direction):
if direction == 'u':
player_y = max(0, self.player['y'] - 1)
elif direction == 'd':
player_y = min(self.height - 1, self.player['y'] + 1)
elif direction == 'l':
player_x = max(0, self.player['x'] - 1)
elif direction == 'r':
player_x = min(self.width - 1, self.player['x'] + 1)
if self.map[player_y][player_x] != 'P' and (self.wumpus['x'], self.wumpus['y']) != (player_x, player_y):
self.player['y'], self.player['x'] = player_y, player_x
return True
else:
print("Invalid move.")
return False
# 示例游戏
cave = Cave(5, 5)
cave.place_wumpus()
cave.place_gold()
cave.player = {'x': 0, 'y': 0} # 初始化玩家位置
while True:
print("You are at ({}, {}).".format(cave.player['x'], cave.player['y']))
direction = input("Enter a direction (u/d/l/r): ")
if cave.move_player(direction):
if cave.map[cave.player['y']][cave.player['x']] == 'G':
print("You found gold!")
break
elif cave.map[cave.player['y']][cave.player['x']] == 'W':
print("A wumpus shot you!")
break
```
阅读全文