用Python编程语言写一个扫雷小游戏
以下是一个使用Python编写的基本扫雷游戏的示例代码:
import random
# 游戏板类
class Board:
def __init__(self, size, num_bombs):
self.size = size
self.num_bombs = num_bombs
self.board = [[' ' for _ in range(size)] for _ in range(size)]
self.bombs = []
# 随机放置炸弹
def place_bombs(self):
bombs_placed = 0
while bombs_placed < self.num_bombs:
row = random.randint(0, self.size-1)
col = random.randint(0, self.size-1)
if self.board[row][col] == ' ':
self.board[row][col] = '*'
self.bombs.append((row, col))
bombs_placed += 1
# 计算每个方格周围的炸弹数量
def compute_numbers(self):
for row in range(self.size):
for col in range(self.size):
if self.board[row][col] == ' ':
count = 0
for dr in [-1, 0, 1]:
for dc in [-1, 0, 1]:
nr = row + dr
nc = col + dc
if nr >= 0 and nc >= 0 and nr < self.size and nc < self.size and self.board[nr][nc] == '*':
count += 1
if count > 0:
self.board[row][col] = str(count)
# 显示游戏板
def display(self, show_bombs=False):
print(" " + " ".join(str(i) for i in range(self.size)))
print(" +" + "---+" * self.size)
for row in range(self.size):
print(str(row) + " | " + " | ".join(self.board[row]) + " |")
print(" +" + "---+" * self.size)
if show_bombs:
print("Bombs: ", self.bombs)
# 游戏类
class Game:
def __init__(self, size, num_bombs):
self.board = Board(size, num_bombs)
# 开始游戏
def start(self):
self.board.place_bombs()
self.board.compute_numbers()
self.board.display()
while True:
row = int(input("Enter row: "))
col = int(input("Enter column: "))
if row < 0 or row >= self.board.size or col < 0 or col >= self.board.size:
print("Invalid move! Try again.")
continue
if (row, col) in self.board.bombs:
print("Game over! You hit a bomb.")
self.board.display(show_bombs=True)
break
elif self.board.board[row][col] != ' ':
print("Invalid move! Try again.")
continue
else:
self.reveal(row, col)
self.board.display()
# 揭示方格
def reveal(self, row, col):
if row < 0 or row >= self.board.size or col < 0 or col >= self.board.size or self.board.board[row][col] != ' ':
return
count = 0
for dr in [-1, 0, 1]:
for dc in [-1, 0, 1]:
nr = row + dr
nc = col + dc
if nr >= 0 and nc >= 0 and nr < self.board.size and nc < self.board.size and self.board.board[nr][nc] != ' ':
count += 1
self.board.board[row][col] = str(count)
if count == 0:
for dr in [-1, 0, 1]:
for dc in [-1, 0, 1]:
self.reveal(row + dr, col + dc)
# 创建游戏对象并开始游戏
game = Game(8, 10)
game.start()
这是一个简单的文本界面扫雷游戏,游戏板大小为8x8,总共有10个炸弹。玩家通过输入行列号来选择方格,如果选择到炸弹,游戏结束;如果选择到数字方格,数字表示周围的炸弹数量。玩家需要揭示所有非炸弹方格来获胜
原文地址: https://www.cveoy.top/t/topic/iShr 著作权归作者所有。请勿转载和采集!