o1-preview-2024-09-12· OpenAI
WildChat-4.8M (AI2)
make a complete working minesweeper game using pygame
- User
make a complete working minesweeper game using pygame
- Assistant
make a complete working minesweeper game using pygame
Sure! Below is a complete Minesweeper game implemented using Pygame. This code creates a Minesweeper game with a 16x16 grid and 40 mines, which are the classic settings. You can left-click to reveal cells and right-click to flag or unflag suspected mines.
import pygame
import sys
import random
# Initialize Pygame
pygame.init()
# Game constants
WIDTH = 20 # Width of each cell
HEIGHT = 20 # Height of each cell
MARGIN = 2 # Margin between cells
GRID_SIZE = 16 # Number of cells in a row/column
NUM_MINES = 40 # Total number of mines
WINDOW_SIZE = ((WIDTH + MARGIN) * GRID_SIZE + MARGIN, (HEIGHT + MARGIN) * GRID_SIZE + MARGIN + 40)
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GRAY = (189, 189, 189)
DARK_GRAY = (120, 120, 120)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
# Create screen
screen = pygame.display.set_mode(WINDOW_SIZE)
pygame.display.set_caption("Minesweeper")
# Fonts
font_small = pygame.font.SysFont(None, 20)
font_large = pygame.font.SysFont(None, 36)
# Game states
STATE_PLAYING = "playing"
STATE_GAME_OVER = "game over"
STATE_WIN = "win"
def create_board(size, num_mines):
board = []
# Initialize board with empty cells
for row in range(size):
board.append([])
for col in range(size):
cell = {
'mine': False,
'revealed': False,
'flagged': False,
'adjacent_mines': 0
}
board[row].append(cell)
# Place mines randomly
mines_placed = 0
while mines_placed < num_mines:
row = random.randint(0, size - 1)
col = random.randint(0, size - 1)
if not board[row][col]['mine']:
board[row][col]['mine'] = True
mines_placed += 1
# Calculate adjacent mines for each cell
for row in range(size):
for col in range(size):
if not board[row][col]['mine']:
count = 0
for r in range(max(0, row - 1), min(size, row + 2)):
for c in range(max(0, col - 1), min(size, col + 2)):
if board[r][c]['mine']:
count += 1
board[row][col]['adjacent_mines'] = count
return board
def draw_board(screen, board, game_state):
# Draw each cell on the board
for row in range(GRID_SIZE):
for col in range(GRID_SIZE):
cell = board[row][col]
x = (MARGIN + WIDTH) * col + MARGIN
y = (MARGIN + HEIGHT) * row + MARGIN
rect = pygame.Rect(x, y, WIDTH, HEIGHT)
if cell['revealed']:
pygame.draw.rect(screen, GRAY, rect)
if cell['mine']:
# Draw mine
pygame.draw.circle(screen, BLACK, rect.center, WIDTH // 2 - 2)
elif cell['adjacent_mines'] > 0:
# Draw number of adjacent mines
text = font_small.render(str(cell['adjacent_mines']), True, BLUE)
text_rect = text.get_rect(center=rect.center)
screen.blit(text, text_rect)
else:
pygame.draw.rect(screen, DARK_GRAY, rect)
if cell['flagged']:
# Draw flag
pygame.draw.polygon(screen, RED, [
(x + WIDTH // 2, y + 5),
(x + 5, y + HEIGHT - 5),
(x + WIDTH - 5, y + HEIGHT - 5)
])
# Display game over or win message
if game_state == STATE_GAME_OVER:
text = font_large.render("Game Over!", True, RED)
screen.blit(text, ((WINDOW_SIZE[0] - text.get_width()) // 2, WINDOW_SIZE[1] - 35))
elif game_state == STATE_WIN:
text = font_large.render("You Win!", True, GREEN)
screen.blit(text, ((WINDOW_SIZE[0] - text.get_width()) // 2, WINDOW_SIZE[1] - 35))
def reveal_cell(board, row, col):
# Recursive function to reveal cells
if board[row][col]['revealed'] or board[row][col]['flagged']:
return
board[row][col]['revealed'] = True
if board[row][col]['mine']:
return
if board[row][col]['adjacent_mines'] == 0:
for r in range(max(0, row - 1), min(GRID_SIZE, row + 2)):
for c in range(max(0, col - 1), min(GRID_SIZE, col + 2)):
if not (r == row and c == col):
reveal_cell(board, r, c)
def check_win(board):
# Check if all non-mine cells are revealed
for row in board:
for cell in row:
if not cell['mine'] and not cell['revealed']:
return False
return True
def main():
board = create_board(GRID_SIZE, NUM_MINES)
clock = pygame.time.Clock()
game_state = STATE_PLAYING
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if game_state == STATE_PLAYING:
if event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
col = pos[0] // (WIDTH + MARGIN)
row = pos[1] // (HEIGHT + MARGIN)
if 0 <= row < GRID_SIZE and 0 <= col < GRID_SIZE:
if event.button == 1: # Left click
if not board[row][col]['flagged']:
board[row][col]['revealed'] = True
if board[row][col]['mine']:
game_state = STATE_GAME_OVER
else:
reveal_cell(board, row, col)
if check_win(board):
game_state = STATE_WIN
elif event.button == 3: # Right click
if not board[row][col]['revealed']:
board[row][col]['flagged'] = not board[row][col]['flagged']
# Draw the board
screen.fill(BLACK)
draw_board(screen, board, game_state)
pygame.display.flip()
clock.tick(60)
# If game over or win, wait a bit and then exit
if game_state in [STATE_GAME_OVER, STATE_WIN]:
pygame.time.wait(2000)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Instructions to run the game:
Ensure you have Python 3 installed on your system.
Install Pygame if you haven't already:
pip install pygame
Save the above code into a file named, for example, minesweeper.py.
Run the game:
python minesweeper.py
Controls:
Gameplay Notes:
Enjoy playing Minesweeper!
Not yet included in a published release.