gpt-4o-2024-08-06· OpenAI
WildChat-4.8M (AI2)
Make a minesweeper game.
- User
Make a minesweeper game.
- Assistant
Make a minesweeper game.
Creating a basic Minesweeper game involves setting up a grid with hidden mines and allowing the player to uncover cells to find and mark mines. Here, I'll outline a simple text-based version you can run in Python. For a graphical version, you'd typically use a library like Pygame, but for now, let's keep it simple:
import random
def initialize_board(size, num_mines):
# Create a size x size board initialized with 0s
board = [[0 for _ in range(size)] for _ in range(size)]
# Place mines randomly on the board
mines_placed = 0
while mines_placed < num_mines:
row = random.randint(0, size-1)
col = random.randint(0, size-1)
if board[row][col] != 'M':
board[row][col] = 'M'
mines_placed += 1
# Update the surrounding squares' numbers
for i in range(max(0, row-1), min(size, row+2)):
for j in range(max(0, col-1), min(size, col+2)):
if board[i][j] != 'M':
board[i][j] += 1
return board
def print_board(board, revealed):
size = len(board)
print(" " + " ".join(str(i) for i in range(size)))
for row in range(size):
print(str(row) + " " + " ".join(
str(board[row][col]) if revealed[row][col] else "." for col in range(size)
))
def check_victory(revealed, board, num_mines):
size = len(board)
revealed_cells = sum(sum(row) for row in revealed)
return revealed_cells == size * size - num_mines
def play_minesweeper(size=5, num_mines=5):
board = initialize_board(size, num_mines)
revealed = [[False for _ in range(size)] for _ in range(size)]
flagged = [[False for _ in range(size)] for _ in range(size)]
while True:
print_board(board, revealed)
try:
move = input("Enter your move: (format: r c action [0:uncover, 1:flag]): ")
r, c, action = map(int, move.split())
if action == 0: # Uncover
if board[r][c] == 'M':
print("Boom! You hit a mine. Game Over!")
break
revealed[r][c] = True
elif action == 1: # Flag
flagged[r][c] = True
if check_victory(revealed, board, num_mines):
print("Congratulations! You've found all the mines!")
break
except (ValueError, IndexError):
print("Invalid move! Please enter in the format 'r c action'.")
play_minesweeper(size=5, num_mines=5)
row col action, where row and col are zero-indexed, and action is either 0 to uncover or 1 to flag a cell.This code provides a basic playable Minesweeper game in the console. For an extended challenge, try adding features like recursive clearing of zero-adjacent cells or a timer function.
Not yet included in a published release.