写一段代码实现扫雷小游戏
时间: 2023-11-21 18:45:51 浏览: 76
扫雷小游戏 微信小游戏源代码
5星 · 资源好评率100%
好的,下面是一个简单的 Python 扫雷小游戏实现代码:
```python
import random
# 初始化游戏面板
def init_board(mine_count, width, height):
board = [[0 for x in range(width)] for y in range(height)]
mines = random.sample(range(width * height), mine_count)
for mine in mines:
x = mine % width
y = mine // width
board[y][x] = "*"
for dx in range(-1, 2):
for dy in range(-1, 2):
if (dx != 0 or dy != 0) and 0 <= x+dx < width and 0 <= y+dy < height and board[y+dy][x+dx] != "*":
board[y+dy][x+dx] += 1
return board
# 显示游戏面板
def show_board(board):
height = len(board)
width = len(board[0])
print(" " + "-" * (2*width+1))
for y in range(height):
print("|", end="")
for x in range(width):
print(" " + str(board[y][x]), end="")
print(" |")
print(" " + "-" * (2*width+1))
# 游戏结束
def game_over(board, x, y):
show_board(board)
print("Game Over!")
return True
# 空白扩散
def expand(board, x, y):
height = len(board)
width = len(board[0])
if board[y][x] == 0:
board[y][x] = "."
for dx in range(-1, 2):
for dy in range(-1, 2):
if (dx != 0 or dy != 0) and 0 <= x+dx < width and 0 <= y+dy < height and board[y+dy][x+dx] != "*":
expand(board, x+dx, y+dy)
# 游戏主循环
def main_loop(mine_count, width, height):
board = init_board(mine_count, width, height)
show_board(board)
while True:
x, y = map(int, input("Enter the coordinate (x y): ").split())
if board[y][x] == "*":
if game_over(board, x, y):
break
else:
expand(board, x, y)
show_board(board)
if all(all(cell in (".", "*") for cell in row) for row in board):
print("You win!")
break
# 运行游戏循环
main_loop(10, 10, 10)
```
这段代码实现了一个 10x10 的扫雷小游戏,初次运行时会生成 10 个地雷并显示游戏面板,随后循环进行以下操作:
1. 等待玩家输入要翻开的格子坐标(x,y);
2. 如果该格子是地雷,游戏结束并显示游戏面板;
3. 如果该格子不是地雷,则扩散连通区域,并显示游戏面板;
4. 如果所有不是地雷的格子都被扩散,则游戏胜利并退出循环。
这只是一个简单的实现,可能还有一些 bug 没有完全解决,欢迎指出。
阅读全文