minesweeper.py

Created by tari-patrik-lfgeb

Created on October 16, 2023

1.41 KB


import random

def create_board(rows, cols, mines):
    board = [[0] * cols for _ in range(rows)]
    mine_positions = []

    while mines:
        r = random.randint(0, rows - 1)
        c = random.randint(0, cols - 1)

        if board[r][c] == 0:
            board[r][c] = "*"
            mine_positions.append((r, c))
            mines -= 1

    for r in range(rows):
        for c in range(cols):
            if board[r][c] == "*":
                continue

            total_mines = 0

            for dr in [-1, 0, 1]:
                for dc in [-1, 0, 1]:
                    rr, cc = r + dr, c + dc

                    if 0 <= rr < rows and 0 <= cc < cols and board[rr][cc] == "*":
                        total_mines += 1

            board[r][c] = str(total_mines)

    return board, mine_positions

def print_board(board):
    for row in board:
        print(" ".join(row))
    print()

def play_game():
    rows, cols, mines = 5, 5, 3
    board, mine_positions = create_board(rows, cols, mines)
    game_over = False

    while not game_over:
        print_board(board)

        row = int(input("Enter row (0-indexed): "))
        col = int(input("Enter column (0-indexed): "))

        if (row, col) in mine_positions:
            print("Game Over! You hit a mine!")
            game_over = True
        else:
            print("Safe! Keep going!")

# To start the game, we'll call play_game()
play_game()

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.