Simple Games in Python

Published on July 30, 2021 by Mariusz Borycki

Photo by Jon Tyson on Unsplash

 

In this project I would like to describe how I made a few simple games without graphical graphical interface, focusing mainly on the code (backend).

 

You can also write games with a graphics engine in Python, and the most popular library for this purpose is Pygame. In the future I am going to write a game using the mentioned library, but there will be time for that. The games that I wrote are very simple and writing them was a form of relaxation for me.

 


GAME DESCRIPTION

In this project I will not elaborate too much, because there are no analyzes or charts to describe here, and the topic itself is quite simple.

Therefore, I will share the code and I decided to show how the games I wrote look like and how they work.

 

For this, I used the Xbox Game Bar tool to record my screen and I have uploaded the videos into the YouTube platform.

 

Game #1: "Guessing Game - User mode"

The player's task is to guess a random value, selected by the computer in a range from 1 to 10

 

Code:

import random
from time import sleep
import os

 

clear = lambda: os.system('clear')

 

def user_guess(x):
    guess_number = random.randint(1,x)
    print("The guessing number has been draw.\n ")
    time.sleep(3)
    clear() 
    zero = 0
    guess_counter = 0

    while guess_number != zero:
        zero = int(input('\nPlease guess the number: '))
        if zero < guess_number:
            print("Nooo, the Guessing Number is higher...")
            time.sleep(2)
            guess_counter += 1
            clear() 
        elif zero > guess_number:
            print(f'Nooo, the Guessing Number is lower...')
            time.sleep(2)
            guess_counter += 1
            clear()

 

    print(f"Great!!! You won :). You missed {guess_counter} times")


Video:

 

Game #2: "Guessing Game - Computer mode"

The roles are reversed in here and our task is to choose a digit in the same range (from 1 to 10) and the computer's task is to guess our value.

 

Code:

import random
from time import sleep
import os

 

clear = lambda: os.system('clear')

 

def pc_guess(min_no, max_no, name):
    '''
    In here I need to choose a number and keep it in my mind.
    PC will be guessing the number and my goal is to tell to PC
    whether the guessed number is smaller ('S'), higher ('H') or if it won ('W').

    Atributes:
    min_no - begining number
    max_no - maximum number
    name - your name
    '''

    clear()
    print(f'Hi {name}. I will try to guess what is your number.')
    sleep(3)
    clear()
    print('Please choose your number within 5 seconds\n')
    sleep(5)

 

    answer = ''
    guess_counter = 0


    while answer != 'W':
        clear()
        guess_number = random.randint(min_no,max_no)


        if (guess_number - min_no) - (guess_number - max_no) == 0:
            answer = 'W'
        else:
            print(f'\nIs the number is {guess_number}:\n')
            answer = input(f"{name}'s answer (H - higher, S - smaller, W - this is my number): ").upper()
            guess_counter += 1
            if answer == 'S':
                max_no = guess_number - 1
            elif answer == 'H':
                min_no = guess_number + 1
            elif answer == 'W':
                clear()
                print(f'Hooray!!! I won :). Your number is {guess_number}. Anyway, I messed {guess_counter} times.')
                sleep(5)
            else:
                print("I don't understand. Please type only: 'H', 'S', 'W'")


    clear()


    print(f'Thank you for your time.')

 

Video:

 

Game #3: "Rock Scissors Paper"

At the beginning of this game, you need to decide how many rounds the game should take.

The goal of the game is to choose: paper ('P'), rock ('R') or scissors ('S') and wait for the computer's move. The scoreboard is up-to-date during the game, and once the game is over, the player with the most points wins.

 

Code:

import random
import os
import time

 

clear = lambda: os.system('clear')


def rock_scissors_paper():
    rsp_list = ['r','s','p']
    clear()
    print("Welcome in the Rock Scissors Paper game.\n")

 

    while True:
        try:
            rounds_number = int(input("Please make a choice, how many times do you wanna play?: "))
        except:    
            clear()
            print("That was no valid number. Try again...")
            time.sleep(3)
            clear()
        else:
            break

    result_player = 0
    result_pc = 0
    print(f"Ok then, we will play {rounds_number} rounds.\nCurrent result is: Player: {result_player} | {result_pc} Computer")

 

    def game_result(player,computer):
        # r > s, s > p, p > r; if True then player won
        if player in rsp_list:
            if (player == 'r' and computer == 's') or (player == 's' and computer == 'p') or (player == 'p' and computer == 'r'):
                return 'player'
            elif (player == 's' and computer == 'r') or (player == 'p' and computer == 's') or (player == 'r' and computer == 'p'):
                return 'computer'
            else:
                return 'tie'
        else:    
            return 'Wrong char'

 

    round_ = 1   

    
    while round_ <= rounds_number:
        clear()
        print(f"Result: Player - {result_player} | {result_pc} - Computer. Round {round_} of {rounds_number} \n")

        player_choice = input(f"Play: 'r' for rock, 's' for scissors, 'p' for paper: ").lower()
        computer_choice = random.choice(rsp_list)
        result = game_result(player_choice,computer_choice)

 

        if result == 'player':
            print(f'Player has got a point. {player_choice} > {computer_choice}')
            result_player += 1
            round_ += 1
            time.sleep(3)
        elif result == 'computer':
            print(f'Computer has got a point. {player_choice} < {computer_choice}')
            result_pc += 1
            round_ += 1
            time.sleep(3)
        elif result == 'tie':
            print(f'Tie. {player_choice} = {computer_choice}')
            round_ += 1
            time.sleep(3)
        else:
            clear()
            print("That was no valid character. Try again to use only those: 'r','s','p'")
            time.sleep(3)
            clear()

 

    clear()


    print(f"The final result: Player - {result_player} | {result_pc} - Computer\n")

 

Video:

 

Game #4: "Hangman"

In this game, our task is to guess the word drawn by the computer from a list of nearly 2,500 English words.

In the game we choose the letters that we think are part of the given word. We can make 5 mistakes, and after using this limit, we lose the game. Of course, once we guess the hidden password before we exceed the limit, we win the game.

 

Code:

from words import hangman_words
import random
import string
import os
from time import sleep

 

clear = lambda: os.system('clear')

 

def choose_a_word(hangman_words):
    word = random.choice(hangman_words)
    while '-' in word or ' ' in word: # we do not need spaces or dashes in our word
        word = random.choice(hangman_words)
    return word.upper()

 

def hangman_game(lives_number):
    '''
    Argument: lives = amount of lives you wanna have
    '''

    underline = ("\n-----------------------\n")
    clear()
    print("Welcome in the Hangman Game!" + underline)
    print('We are searching a word for you. Please wait a second...')
    lives = lives_number
    alphabet = set(string.ascii_uppercase)
    chosen_word = choose_a_word(hangman_words)
    word_letters = set(chosen_word)
    used_letters = set()
    missed_letters = list()
    sleep(5)

 

    while len(word_letters) > 0 and lives >= 1:
        clear()
        guessed_letters = [letter if letter in used_letters else "_" for letter in chosen_word]
        print(f"Remaining life: {lives}")
        print(f"Used letters: {missed_letters}")
        print("\nCurrent word: "," ".join(guessed_letters))
        user_letter = input("\nWrite a letter: ").upper()

 

        if user_letter in word_letters and user_letter in alphabet:
            clear()
            print(f"{underline}You guessed the letter: '{user_letter}'{underline}")
            sleep(3)
            word_letters.remove(user_letter)
            used_letters.add(user_letter)
        else:
            clear()
            print(f"{underline}Sorry try to guess another letter{underline}")
            sleep(3)
            missed_letters.append(user_letter)
            lives -= 1

 

    if lives == 0:
        clear()
        print(f"\n{underline}Sorry but you're dead. The chosen word was: '{chosen_word}'{underline}")
        sleep(3)
    else:
        clear()
        print(f"\n{underline}Congratulation! You guessed the chosen word was: '{chosen_word}'{underline}")
        sleep(3)

 

 

Video:

 

Game #5: "Tic Tac Toe"

This is the last game in this project and it is a strategy game for two players, X and O, who take turns marking the spaces in a 3×3 grid.

The player who succeeds in placing three of their marks in a diagonal, horizontal, or vertical row is the winner. 

 

Code:

import os
from time import sleep

 

# Variables
X = 'X'
O = 'O'
WINNER = None
PLAY_ON = True
X_O = str()
PLAYER_NAME = str()
FIRST_PLAYER = str()
FIG = str()

 

# Board
board = [' ' for _ in range(9)]
def print_board():
    for row in [board[i*3:(i+1)*3] for i in range(3)]:
        print('| ' + ' | '.join(row) + ' |')
    print('')

 

def print_board_nums():
    print('Please find below the numbers you can choose:\n')

    rows = [[str(i+1) for i in range(j*3, (j+1)*3)] for j in range(3)]
    for row in rows:
        print('| ' + ' | '.join(row) + ' |')
    print('\n\n')

 

def clear_console():
    clear = lambda: os.system('clear')
    clear()

 

def separator():
    print("--------------------------------")

 

def introduction():
    print('Hello, this is the Tic Tac Toe game.\nPlease choose who  will be the first player:'
    ' you or your opponent?\n')

 

def whats_your_name():
    player_1 = input('Hello PLAYER 1. What is your name? ')
    player_2 = input('Hello PLAYER 2. What is your name? ')
    return player_1, player_2

 

def print_number(PLAYER_NAME, X_O):
    separator()
    print(f"{PLAYER_NAME} ({X_O}): - it is your turn:")
    separator()
    position = input('\nChoose a possition [1-9]: ')
    return position

 

def choose_player(p1, p2):
    answers = ["Y","N"]
    answer = str()

    while answer not in answers:
        clear_console()
        print('Thank you for typing the names...')
        sleep(3)
        clear_console()

        answer = input(f'{p1} do you want to begin the game? (y/n). Type "n" if {p2} should be the first player: ')
        answer =  answer.upper()


        if answer in answers:
            if answer == "Y":
                FIG = 'X'
                FIRST_PLAYER = p1
                print(f'Okey then, {p1} will begin the game\n')
                sleep(2)
            else:
                FIG = 'O'
                FIRST_PLAYER = p2
                print(f'Okey then, {p2} will be the first player\n')
                sleep(2)
        else:
            print(f'Please choose correct character. "{answer}" is not valid\n')
    return FIG, FIRST_PLAYER 

 

def check_winner():

    rows = check_rows()
    cols = check_columns()
    diags = check_diagonals()
    tie = check_tie()

 

    if rows == None:
        if cols == None:
            if diags == None:
                if tie == None:
                    return None
                else:
                    won = tie
            else:
                won = diags
        else:
            won = cols
    else:
        won = rows

 

    return won 

 

def check_columns():
    global PLAY_ON    

    col1 = board[0] == board[3] == board[6] != " "
    col2 = board[1] == board[4] == board[7] != " "
    col3 = board[2] == board[5] == board[8] != " "

 

    if col1 or col2 or col3:
        PLAY_ON = False
    if col1:
        return board[0]
    elif col2:
        return board[1]
    elif col3:
        return board[2]
    else:
        return None

 

def check_diagonals():
    global PLAY_ON

    dia1 = board[0] == board[4] == board[8] != " "
    dia2 = board[2] == board[4] == board[6] != " "

    if dia1 or dia2:
        PLAY_ON = False
    if dia1:
        return board[0]
    elif dia2:
        return board[2]
    else:
        return None

 

def check_rows():
    global PLAY_ON

    row1 = board[0] == board[1] == board[2] != " "
    row2 = board[3] == board[4] == board[5] != " "
    row3 = board[6] == board[7] == board[8] != " "

 

    if row1 or row2 or row3:
        PLAY_ON = False
    if row1:
        return board[0]
    elif row2:
        return board[3]
    elif row3:
        return board[6]
    else:
        return None

 

def check_tie():
    global PLAY_ON  

    a = 0


    for row in range(9):
        if board[row] == " ":
            a += 1
        else:
            a = a
    if a == 0:
        PLAY_ON = False
        return True
    else:
        return None

 

def flip_player(fig, p_name, p1, p2):
    if fig == 'X':
        fig = 'O'
    else:
        fig = 'X'

    if p_name == p1:
        p_name = p2
    else:
        p_name = p1
    return fig, p_name

 

def tic_tac_toe_game():
    clear_console()
    introduction()
    player_1, player_2 = whats_your_name()
    FIG, FIRST_PLAYER = choose_player(player_1, player_2)

    X_O = "X" if FIG == "X" else "O"
    PLAYER_NAME = player_1 if FIRST_PLAYER == player_1 else player_2

    clear_console()
    print_board_nums()


    while PLAY_ON:
        position = print_number(PLAYER_NAME, X_O)

        valid = False


        while not valid:
            while position not in ['1','2','3','4','5','6','7','8','9']:
                position = print_number(PLAYER_NAME, X_O)

            pos = int(position) - 1
            if board[pos] == " ":
                valid = True
            else:
                separator()
                print("You can't go there. Go again.")
                separator()
                sleep(2)
                position = print_number(PLAYER_NAME, X_O)    

        position = int(position) - 1
        print(f'\nCurrent Board: {board[position]}')
        board[position] = X_O
        clear_console()
        print_board_nums()
        print_board()
        winner  = check_winner()
        X_O, PLAYER_NAME = flip_player(X_O, PLAYER_NAME, player_1, player_2)

 

    if winner == "X" or winner == "O":
        print(f"The winner is: {FIRST_PLAYER} ('{winner}')\n")
    elif winner == True:
        print("Tie\n")

 

Video:

 


IN CONCLUSION

If you have any questions or free conclusions regarding this article, feel free to leave a comment.

However, if you have ideas for further projects or if you have any other questions, please do not hesitate to contact me.

 

All scripts and their descriptions can be found in my repository on the GitHub platform, where I cordially invite you.

 

Comments:

0 comments

There is no comment yet.

Add new comment: