0% found this document useful (0 votes)
55 views19 pages

Mini Projects

The document describes creating 5 mini games in Python including Guess the Number, Rock Paper Scissors, Wordle, Connect Four, and Tic Tac Toe. It provides code snippets and explanations for how each game works and is built.

Uploaded by

sathvikag001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views19 pages

Mini Projects

The document describes creating 5 mini games in Python including Guess the Number, Rock Paper Scissors, Wordle, Connect Four, and Tic Tac Toe. It provides code snippets and explanations for how each game works and is built.

Uploaded by

sathvikag001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Mini Games

Using Python

09.04.2023

Gudapati Sree Sathvika


Guru Nanak Institution Technical Campus
Ibrahimpatnam

Overview
For my mini project I have created a python code which consists of 5 mini games which can
entertain you. I have done this using replit

Goals
1. To create a mini project consisting mini games such as:
● Guess the number
● Rock, Paper, Scissors
● Wordle
● ConnectFour
● Tic Tac Toe

Case Study
Here I am going to steps involved in creating this game
1

● Guess the number


● In this game the computer chooses a number between 1 to 100
● The user has to guess the number
Below are the Steps:
● The compiler generates a random integer between the range and
stores it in a variable for future references.
● For repetitive guessing, a while loop will be initialized. If the user
guessed a number which is greater than a randomly selected number,
the user gets an output "Try Again! You guessed too high"
● Else If the user guessed a number which is smaller than a randomly
selected number, the user gets an output "Try Again! You guessed too
small"
● And if the user guessed in a minimum number of guesses, the user
gets a"Congratulations! "Output.

Rock Paper Scissors

● In this game the user chooses a option between rock,paper and scissors
● The computer also randomly chooses a option and then the winner is decided
● The code starts by asking the user for a choice.
● The code then checks to see if the input is 1, 2, or 3.
● If it is not one of those values, the code sets the choice_name variable to
‘Rock’ if choice == 1, ‘paper’ if choice == 2, and ‘scissor’ if choice == 3.
● The next part of the code asks the user for their computer turn.
● The code uses a random number generator to choose between 1, 2, and 3.
● This value is stored in comp_choice_name.
● Next, the code loops until comp_choice equals choice.
● In each loop iteration, comp_choice will be randomly chosen from 1-3 and
stored in comp_choice_name.
● Once comp_choice equals choice, this means that the computer has
chosen rock as its turn!
2

● Finally, it prints out both choices so that everyone can see what happened
(user choice is: Rock V/s paper; Computer choice is: Rock V/s scissor).
● The code will ask the user for a choice between rock, paper and scissors.
● Once the user enters their choice, the code will randomly choose one of
those options as the computer’s turn.
● The code then prints out the chosen option and the user’s choice.

● Wordle
● In this game, there is a list of words present, out of which our interpreter will choose
1 random word. The user first has to input their names and then, will be asked to
guess any alphabet. If the random word contains that alphabet, it will be shown as
the output(with correct placement) , else the program will ask you to guess another
alphabet. The user will be given 12 turns(which can be changed accordingly) to
guess the complete word.
Step 1: Guess a Word

• Get User Information With input


Use Loops to Avoid Repetitive Code
• Check Letters With Sets

Step 2: Use a Word List


• Create a Word List Manually
o Choose a Random Word From a Word List
• Convert a Text Into a List of Words

Step 3: Organize Your Code With Functions


• Set Up Your Main Loop
• Create Supporting Functions
• Test Your Code
3

• Step 4: Style Your Game With Rich


o Get to Know the Rich Console Printer
o Keep Track of Previous Guesses and Color Them
• Wrap Up the Game in Style

● Connect Four
● It is a two-player connection board game, in which the players choose a color and
then take turns dropping colored discs into a seven-column, six-row vertically
suspended grid. The pieces fall straight down, occupying the lowest available space
within the column. The objective of the game is to be the first to form a horizontal,
vertical, or diagonal line of four of one’s own discs. Connect Four is a solved game.
1. Import the NumPy package as np. Then we will create a python function named
create_board( ).
2. We will is create another three functions

● Tic Tac Toe


● Tic tac toe Python is a two-player game played on the 3X3 grid between two
players. Each player chooses between X and O and the first player starts to draw
the X on the space on the grid followed alternatively by the other until a player
successfully marks a streak on the grid else if all spaces are filled the game is
set to draw.The major topics that must be refreshed before creating and building the tic
tac toe Python project are as follows:

● Basic concepts of Python


● User define functions in Python
● Loops in Python (for loop, if else, if elif else)
● try-exception block in Python
● while loop of Python

Winning Rules a
s follows:

Rock vs paper-> paper wins


4

Main Program
from gtn import guess_the_number

from rps import rock_paper_scissors

from wordle import Wordle

from connect_four import ConnectFour

from tictactoe import TicTacToe

while True:

txt = """Mini Games!!!

- Guess The Number (1)

- Rock, Paper, Scissors (2)

- Wordle (3)

- ConnectFour (4)

- Tic Tac Toe (5)

Select a game (press a number or 'q' to quit): """

value = input(txt)

if value == "1":

guess_the_number(100)

elif value == "2":

rock_paper_scissors()

elif value == "3":

game = Wordle()

game.play()

elif value == "4":

game = ConnectFour()

game.play()

elif value == "5":

game = TicTacToe()

game.play()

elif value == "q":

break
5

Now we make sub files in which we write the code of


each game.
First we make a file named gtn.py for guess the
number game
import random

def guess_the_number(x):

print("Let's play Guess The Number")

random_number = random.randint(0, x)

num_guesses = 0

while True:

guess = int(input(f"Guess a number between 0 and {x}: "))

num_guesses += 1

if guess == random_number:

print(f"Congrats, the number is {random_number}")

break

elif guess < random_number:

print("Too low!")

else:

print("Too high!")

Now we make a file named rps.py for rock paper


scissors game
import random

def rock_paper_scissors():

print("Let's play Rock Paper Scissors")

r = "rock"
6

p = "paper"

s = "scissors"

all_choices = [r,p,s]

user = input(f"Enter a choice ({r}, {p}, {s}): ")

if user not in all_choices:

print("Invalid choice")

return

computer = random.choice(all_choices)

print(f"User chose {user}, computer chose {computer}")

# r>s, p>r, s>p

if user == computer:

print("Tie")

elif (user == r and computer == s) or (user == p and computer == r)


or (user == s and computer == p):

print("You won!")

else:

print("You lost")

Now we make a file named wordle.py for the game


wordle
import random

from rich import print

words = (

"awake",

"blush",

"focal",
7

"evade",

"serve",

"model",

"karma",

"grade",

"quiet",

class Wordle:

def __init__(self):

self.word = random.choice(words)

self.num_guesses = 0

self.guess_dict = {

0: [" "]*5,

1: [" "]*5,

2: [" "]*5,

3: [" "]*5,

4: [" "]*5,

5: [" "]*5,

def draw_board(self):

for guess in self.guess_dict.values():

print(" | ".join(guess))

print("================")

def get_user_input(self):

user_guess = input("enter a 5 letter word: ")

while len(user_guess) != 5:

user_guess = input("not valid, enter a 5 letter word: ")

user_guess = user_guess.lower()
8

for idx, char in enumerate(user_guess):

if char in self.word:

if char == self.word[idx]:

char = f"[green]{char}[/]"

else:

char = f"[yellow]{char}[/]"

self.guess_dict[self.num_guesses][idx] = char

self.num_guesses += 1

return user_guess

def play(self):

while True:

self.draw_board()

user_guess = self.get_user_input()

if user_guess == self.word:

self.draw_board()

print(f"You won! The word was {self.word}")

break

if self.num_guesses > 5:

self.draw_board()

print(f"You lost! The word was {self.word}")

break

Now we make a file named connect_four.py for the


game Connect four

class ConnectFour:
9

def __init__(self, height=6, width=7):

self.height = height

self.width = width

self.board = [[" "]*width for row in range(height)]

def draw_board(self):

print([str(i+1) for i in range(self.width)], end="\n\n")

for row in self.board:

print(row)

def get_column(self, index):

return [row[index] for row in self.board]

def get_row(self, index):

return self.board[index]

def get_diagonals(self):

diagonals = []

for i in range(self.height + self.width - 1):

diag1, diag2 = [], []

for j in range(max(i - self.height + 1, 0), min(i + 1,


self.height)):

diag1.append(self.board[self.height - i + j - 1][j])

diag2.append(self.board[i - j][j])

diagonals.append(diag1)

diagonals.append(diag2)

return diagonals

def insert_token(self, team, col):

if " " not in self.get_column(col):


10

return False

row = self.height -1

while self.board[row][col] != " ":

row -= 1

self.board[row][col] = team

return True

def check_win(self):

four_in_row = (["0", "0", "0", "0"], ["1", "1", "1", "1"])

# check rows

for row in range(self.height):

for col in range(self.width-3):

if self.get_row(row)[col:col+4] in four_in_row:

return True

# check cols

for col in range(self.width):

for row in range(self.height-3):

if self.get_column(col)[row:row+4] in four_in_row:

return True

# check diagonals

for diag in self.get_diagonals():

for idx, _ in enumerate(diag):

if diag[idx:idx+4] in four_in_row:

return True

return False

def play(self):

team = "0"
11

while True:

self.draw_board()

col = int(input(f"Team {team} choose column: ")) - 1

ok = self.insert_token(team, col)

while not ok:

print("column is full!")

col = int(input(f"Team {team} choose column: ")) - 1

ok = self.insert_token(team, col)

if self.check_win():

self.draw_board()

print(f"Team {team} wins!")

break

team = "1" if team == "0" else "0"

Now we make a file named tictactoe.py for the game


tic tac toe
import random

player, computer = "X", "O"

winners = ((0,1,2),(3,4,5),(6,7,8),(0,3,6),

(1,4,7),(2,5,8),(0,4,8),(2,4,6))

class TicTacToe:

def __init__(self):

self.board = [" "]*9

def print_board(self):
12

for i, val in enumerate(self.board):

end = " | "

if i == 2 or i == 5:

end = "\n-----------\n"

elif i == 8:

end = "\n"

print(val, end=end)

def can_move(self, move):

if move in range(1, 10) and self.board[move-1] == " ":

return True

return False

def can_win(self, player):

win = True

for tup in winners:

win = True

for idx in tup:

if self.board[idx] != player:

win = False

break

if win == True:

break

return win

def make_move(self, player, move):

# moved, win

if self.can_move(move):

self.board[move-1] = player

win = self.can_win(player)

return (True, win)

return (False, False)


13

def computer_move(self):

for move in (5, 1, 3, 7, 9, 2, 4, 6, 8):

if self.can_move(move):

return self.make_move(computer, move)

return self.make_move(computer, -1)

def play(self):

print("Order is:\n1 2 3\n4 5 6\n7 8 9")

print(f"player is {player}, computer is {computer}")

result = "Tie"

while True:

if self.board.count(player) + self.board.count(computer) ==
9:

break

self.print_board()

move = int(input("make your move [1-9]: "))

moved, won = self.make_move(player, move)

if not moved:

print("invalid move! try again!")

continue

if won:

result = "You win!"

break

_, won = self.computer_move()

if won:

result = "You lose!"


14

break

self.print_board()

print(result)

OUTPUT/RESULT
15
16
17

scissor-> Rock wins


18

paper vs scissor-> scissor

You might also like