import pygame import random # Initialize pygame pygame.init() # Define colors white = (255, 255, 255) black = (0, 0, 0) gray = (169, 169, 169) blue = (0, 0, 255) red = (255, 0, 0) light_gray = (211, 211, 211) # Set up the display cell_size = 30 grid_size = 10 num_mines = 15 width = height = grid_size * cell_size dis = pygame.display.set_mode((width, height)) pygame.display.set_caption('Minesweeper') # Font for text font = pygame.font.SysFont(None, 24) def draw_grid(): for x in range(0, width, cell_size): pygame.draw.line(dis, black, (x, 0), (x, height)) for y in range(0, height, cell_size): pygame.draw.line(dis, black, (0, y), (width, y)) def draw_cell(x, y, content, revealed=False): if revealed: pygame.draw.rect(dis, white, [x * cell_size, y * cell_size, cell_size, cell_size]) pygame.draw.rect(dis, black, [x * cell_size, y * cell_size, cell_size, cell_size], 1) if content == -1: pygame.draw.circle(dis, red, (x * cell_size + cell_size // 2, y * cell_size + cell_size // 2), cell_size // 3) elif content > 0: text = font.render(str(content), True, black) dis.blit(text, (x * cell_size + cell_size // 4, y * cell_size + cell_size // 4)) else: pygame.draw.rect(dis, gray, [x * cell_size, y * cell_size, cell_size, cell_size]) pygame.draw.rect(dis, black, [x * cell_size, y * cell_size, cell_size, cell_size], 1) def get_neighbors(x, y): neighbors = [] for dx in [-1, 0, 1]: for dy in [-1, 0, 1]: if dx == 0 and dy == 0: continue nx, ny = x + dx, y + dy if 0 <= nx < grid_size and 0 <= ny < grid_size: neighbors.append((nx, ny)) return neighbors def initialize_grid(): grid = [[0] * grid_size for _ in range(grid_size)] mines = set() while len(mines) < num_mines: x, y = random.randint(0, grid_size - 1), random.randint(0, grid_size - 1) if (x, y) not in mines: mines.add((x, y)) grid[x][y] = -1 for nx, ny in get_neighbors(x, y): if grid[nx][ny] != -1: grid[nx][ny] += 1 return grid def reveal_cells(grid, x, y, revealed): if revealed[x][y] or x < 0 or x >= grid_size or y < 0 or y >= grid_size: return revealed[x][y] = True if grid[x][y] == 0: for nx, ny in get_neighbors(x, y): reveal_cells(grid, nx, ny, revealed) def gameLoop(): grid = initialize_grid() revealed = [[False] * grid_size for _ in range(grid_size)] game_over = False while not game_over: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.MOUSEBUTTONDOWN: if event.button == 1: # Left click x, y = event.pos x //= cell_size y //= cell_size if grid[x][y] == -1: game_over = True print("Game Over! You hit a mine.") else: reveal_cells(grid, x, y, revealed) dis.fill(light_gray) draw_grid() for x in range(grid_size): for y in range(grid_size): draw_cell(x, y, grid[x][y], revealed[x][y]) pygame.display.update() gameLoop()