Python扫雷小游戏
时间: 2023-11-05 20:53:05 浏览: 97
好的,我可以为您提供一个Python扫雷小游戏的代码示例。下面是一个简单的实现:
```python
import random
# 游戏设置
ROW = 10
COL = 10
BOMBS = 10
# 空白格子的标记
BLANK = 0
# 炸弹格子的标记
BOMB = -1
# 游戏状态
PLAYING = 0
WON = 1
LOST = 2
# 打印棋盘
def print_board(board):
print(" ", end="")
for i in range(1, COL + 1):
print(i, end="")
print()
for i in range(ROW):
print(chr(ord('A') + i), end="")
for j in range(COL):
if board[i][j] == BLANK:
print(" ", end="")
elif board[i][j] == BOMB:
print("X", end="")
else:
print(board[i][j], end="")
print()
# 初始化游戏棋盘
def init_board():
board = [[BLANK] * COL for i in range(ROW)]
bombs = []
# 随机生成炸弹的位置
while len(bombs) < BOMBS:
row = random.randint(0, ROW - 1)
col = random.randint(0, COL - 1)
if (row, col) not in bombs:
bombs.append((row, col))
board[row][col] = BOMB
# 计算每个格子周围炸弹的数量
for i in range(ROW):
for j in range(COL):
if board[i][j] != BOMB:
count = 0
for row in range(max(0, i - 1), min(ROW, i + 2)):
for col in range(max(0, j - 1), min(COL, j + 2)):
if board[row][col] == BOMB:
count += 1
board[i][j] = count
return board
# 点开格子
def click(board, row, col):
if board[row][col] == BOMB:
return LOST
board[row][col] = BLANK
# 点开周围的格子
if board[row][col] == 0:
for r in range(max(0, row - 1), min(ROW, row + 2)):
for c in range(max(0, col - 1), min(COL, col + 2)):
if board[r][c] != BOMB and board[r][c] != BLANK:
click(board, r, c)
# 检查游戏是否胜利
for i in range(ROW):
for j in range(COL):
if board[i][j] != BOMB and board[i][j] != BLANK:
return PLAYING
return WON
# 主函数
def main():
board = init_board()
status = PLAYING
while status == PLAYING:
print_board(board)
move = input("请输入坐标(如 A1):")
col = ord(move[0]) - ord('A')
row = int(move[1:]) - 1
status = click(board, row, col)
print_board(board)
if status == WON:
print("你赢了!")
else:
print("你输了!")
if __name__ == "__main__":
main()
```
运行程序后,您可以输入坐标来点开相应的格子,直到游戏结束。希望这个示例能够帮助您开始编写自己的扫雷游戏。
阅读全文