python文字游戏代码
时间: 2024-02-29 22:49:29 浏览: 101
游戏代码
当然可以!以下是一个简单的Python文字游戏代码示例:
```python
class Room:
def __init__(self, name, description):
self.name = name
self.description = description
self.exits = {}
def add_exit(self, direction, room):
self.exits[direction] = room
def get_exit(self, direction):
return self.exits.get(direction)
def get_full_description(self):
return self.name + "\n\n" + self.description
def play_game():
# 创建房间
room1 = Room("Room 1", "这是一个小房间。")
room2 = Room("Room 2", "这是另一个房间。")
room3 = Room("Room 3", "这是第三个房间。")
# 设置房间之间的连接
room1.add_exit("north", room2)
room2.add_exit("south", room1)
room2.add_exit("east", room3)
room3.add_exit("west", room2)
# 游戏循环
current_room = room1
while True:
print(current_room.get_full_description())
# 获取用户输入
command = input("输入指令:")
# 处理用户指令
if command == "quit":
print("游戏结束!")
break
elif command in current_room.exits:
current_room = current_room.get_exit(command)
else:
print("无效的指令!")
# 启动游戏
play_game()
```
这个代码示例创建了三个房间,并设置了它们之间的连接。玩家可以通过输入指令来移动到不同的房间。输入"quit"可以退出游戏。
阅读全文