請寫出一個踩地雷的程式
- User
請寫出一個踩地雷的程式
Assistant
當然!以下是一個簡單的踩地雷遊戲的Python程式。這個程式將在一個固定大小的棋盤上生成地雷,並允許玩家選擇位置來揭開格子。
pythonimport random class Minesweeper: def __init__(self, width=10, height=10, mines=10): self.width = width self.height = height self.mines = mines self.board = [[' ' for _ in range(width)] for _ in range(height)] self.revealed = [[False for _ in range(width)] for _ in range(height)] self.game_over = False self.place_mines() def place_mines(self): mine_positions = random.sample(range(self.width * self.height), self.mines) for pos in mine_positions: x, y = divmod(pos, self.width) self.board[x][y] = 'X' def count_adjacent_mines(self, x, y): count = 0 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 < self.height and 0 <= ny < self.width and self.board[nx][ny] == 'X': count += 1 return count def reveal(self, x, y): if self.revealed[x][y]: return self.revealed[x][y] = True if self.board[x][y] == 'X': self.game_over = True return count = self.count_adjacent_mines(x, y) if count > 0: self.board[x][y] = str(count) else: self.board[x][y] = ' ' 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 < self.height and 0 <= ny < self.width: self.reveal(nx, ny) def display(self): for x in range(self.height): for y in range(self.width): if self.revealed[x][y]: print(self.board[x][y], end=' ') else: print('?', end=' ') print() def play(self): while not self.game_over: self.display() x = int(input(f"Enter x coordinate (0-{self.height-1}): ")) y = int(input(f"Enter y coordinate (0-{self.width-1}): ")) self.reveal(x, y) if self.game_over: self.display() print("Game Over! You hit a mine.") if __name__ == "__main__": game = Minesweeper() game.play()
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.