A simple, 2-player number guessing game in Python 3.

[[ 🗃 ^yENdo impossible-grid ]] :: [📥 Inbox] [📤 Outbox] [🐤 Followers] [🤝 Collaborators] [🛠 Commits]

Clone

HTTPS: git clone https://vervis.peers.community/repos/yENdo

SSH: git clone USERNAME@vervis.peers.community:yENdo

Branches

Tags

master ::

impossiblegrid.py

#!/usr/bin/env python

# Copyright 2018 UltrasonicMadness
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""This is the main file which runs the Impossible Grid game. It imports the
local Grid class from grid.py, exceptions from igexceptions.py and sets the
width and height of the grid to 4.

If this file is not being imported (e.g. by PyDoc), the players are then
greeted and player 1 is asked for a number between 1 and the area of the grid.
The screen is then cleared for player 2, who has to cover player 1's number on
the grid; they are given prompts asking which rows and columns they would like
to cover until one number is left on the grid.

Player 1 wins if their number is left uncovered, otherwise player 2 wins.
"""

from grid import Grid
from igexceptions import *

WIDTH = 4
HEIGHT = 4

def gridPrompt(grid, prompt, col):
    """Prompts the player for a number between 1 and the length of the grid.
    If the number is out of range or the relevant part of the grid is already
    highlighted, an error is displayed and the user is prompted again.
    
    Parameters:
    grid: The grid to highlight.
    prompt: The prompt message shown to player 2.
    col: True if working with columns, False if working with rows.
    
    Returns:
    This function does not return any data.
    """
    
    while True:
        try:
            # Get a number from player 2
            playerNum = int(input(prompt))
            
            # Try to highlight the row or column
            if col:
                grid.highlightCol(playerNum - 1)
            else:
                grid.highlightRow(playerNum - 1)
            
            gameGrid.show()
            print("\n\n")
            break
            
        except HLOutOfRangeException:
            print("Value out of range")
            
        except DuplicateHLException:
            print("That row has already been highlighted")
        
        except ValueError:
            print("Please input a number")
        
if __name__ == "__main__":
    print("Hello and welcome to the Impossible Grid game!")
    print("Copyright (C) 2018 UltrasonicMadness")
    print()
    print("Two players are needed for this game.")

    # Keep prompting player 1 for a number in the required range until one is
    # given.
    while True:
        try:
            theNumber = int(input("Player 1, input a number between " +
                                        "1 and " + str(WIDTH * HEIGHT) +
                                        ": "))
            
            if theNumber >= 1 and theNumber <= WIDTH * HEIGHT:
                theNumber -= 1
                break
            else:
                print("Out of range, please try again.")
                
        except ValueError:
            print("A number is needed, please try again.")

    # Clear the screen by printing 1024 blank lines
    for i in range(0, 1024):
        print()

    # Create a grid and display it.
    gameGrid = Grid(theNumber, WIDTH, HEIGHT)
    gameGrid.show()

    print("Over to player 2.")
    print("Your goal is to cover the number that player 1 picked on the " +
            "above grid.\n")

    # The game itself.
    gridPrompt(gameGrid, "Choose a row to cover: ", False)
    gridPrompt(gameGrid, "Choose another row to cover: ", False)
    gridPrompt(gameGrid, "Choose a column to cover: ", True)
    gridPrompt(gameGrid, "Choose another column to cover: ", True)
    gridPrompt(gameGrid, "Choose one last row to cover: ", False)
    gridPrompt(gameGrid, "Choose one last column to cover: ", True)

    # When player 1 inevitably wins due to the game being a cheating so-and-so.
    print("Player 1's number was " + str(theNumber + 1) + ", matching " + \
            "the last remaining number on the grid.")
    print("Player 1 wins!")
    print("Thank you both for playing")

[See repo JSON]