python写的扫雷游戏代码
原创
52cxy
02-13 18:16
阅读数:2931
import random
def print_board(board):
for row in board:
print(" ".join([str(cell) for cell in row]))
def generate_board(size, bombs):
board = [[0 for x in range(size)] for y in range(size)]
for i in range(bombs):
bomb_placed = False
while not bomb_placed:
x = random.randint(0, size - 1)
y = random.randint(0, size - 1)
if board[x][y] != "X":
board[x][y] = "X"
bomb_placed = True
for i in range(size):
for j in range(size):
if board[i][j] != "X":
count = 0
if i > 0 and board[i - 1][j] == "X":
count += 1
if i < size - 1 and board[i + 1][j] == "X":
count += 1
if j > 0 and board[i][j - 1] == "X":
count += 1
if j < size - 1 and board[i][j + 1] == "X":
count += 1
if i > 0 and j > 0 and board[i - 1][j - 1] == "X":
count += 1
if i > 0 and j < size - 1 and board[i - 1][j + 1] == "X":
count += 1
if i < size - 1 and j > 0 and board[i + 1][j - 1] == "X":
count += 1
if i < size - 1 and j < size - 1 and board[i + 1][j + 1] == "X":
count += 1
board[i][j] = count
return board
def play_game(size, bombs):
board = generate_board(size, bombs)
print_board(board)
if __name__ == '__main__':
play_game(5, 5)共0条评论