python猫和老鼠游戏制作大全集
时间: 2023-07-26 18:10:50 浏览: 60
猫和老鼠游戏是一种经典的童年游戏,也是一个很好的编程练习项目。下面是一个简单的Python猫和老鼠游戏的实现步骤:
1. 导入必要的模块
```python
import random
import os
import time
```
2. 定义游戏地图
```python
MAP_WIDTH = 40
MAP_HEIGHT = 20
map_data = []
for y in range(MAP_HEIGHT):
row = []
for x in range(MAP_WIDTH):
if x == 0 or x == MAP_WIDTH-1 or y == 0 or y == MAP_HEIGHT-1:
row.append('#')
else:
row.append(' ')
map_data.append(row)
```
3. 定义猫和老鼠的初始位置
```python
cat_x = random.randint(1, MAP_WIDTH-2)
cat_y = random.randint(1, MAP_HEIGHT-2)
mouse_x = random.randint(1, MAP_WIDTH-2)
mouse_y = random.randint(1, MAP_HEIGHT-2)
```
4. 游戏主循环
```python
while True:
# 清屏
os.system('cls' if os.name == 'nt' else 'clear')
# 更新地图
map_data[cat_y][cat_x] = 'C'
map_data[mouse_y][mouse_x] = 'M'
# 输出地图
for row in map_data:
print(''.join(row))
# 判断胜负
if cat_x == mouse_x and cat_y == mouse_y:
print('猫抓到了老鼠!')
break
# 猫的移动
if cat_x < mouse_x:
cat_x += 1
elif cat_x > mouse_x:
cat_x -= 1
if cat_y < mouse_y:
cat_y += 1
elif cat_y > mouse_y:
cat_y -= 1
# 老鼠的移动
mouse_dx = random.randint(-1, 1)
mouse_dy = random.randint(-1, 1)
if 0 < mouse_x + mouse_dx < MAP_WIDTH-1:
mouse_x += mouse_dx
if 0 < mouse_y + mouse_dy < MAP_HEIGHT-1:
mouse_y += mouse_dy
# 暂停一会儿
time.sleep(0.1)
```
这样就完成了一个简单的Python猫和老鼠游戏。你可以在此基础上进行更多的扩展,比如添加障碍物、增加多只老鼠等等。