diff --git a/minesweeper b/minesweeper new file mode 100644 index 0000000..d942cb3 --- /dev/null +++ b/minesweeper @@ -0,0 +1,61 @@ +import random + +def initialize_board(board_size, nummines): + board = [[' ' for in range(boardsize)] for in range(board_size)] + mines = random.sample(range(board_size * board_size), num_mines) + + for mine in mines: + row = mine // board_size + col = mine % board_size + board[row][col] = '' + + return board + +def print_board(board): + board_size = len(board) + + print(" " + " ".join([str(i) for i in range(board_size)])) + print(" " + "-" (board_size * 2 + 1)) + + for i in range(board_size): + print(str(i) + "|", end="") + for j in range(board_size): + print(board[i][j] + " ", end="") + print("|") + + print(" " + "-" * (board_size * 2 + 1)) + +def count_adjacent_mines(board, row, col): + board_size = len(board) + directions = [(1, 0), (-1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)] + count = 0 + + for dr, dc in directions: + r, c = row + dr, col + dc + if 0 <= r < board_size and 0 <= c < board_size and board[r][c] == '': + count += 1 + + return count + +def play_game(board_size, num_mines): + board = initialize_board(board_size, nummines) + revealed = [[' ' for in range(boardsize)] for in range(board_size)] + game_over = False + + while not game_over: + print_board(revealed) + row = int(input("行を選択してください: ")) + col = int(input("列を選択してください: ")) + + if board[row][col] == '': + game_over = True + else: + revealed[row][col] = str(count_adjacent_mines(board, row, col)) + + print_board(board) + print("ゲームオーバー!") + +if name == "main": + board_size = 5 + num_mines = 5 + play_game(board_size, num_mines)