0% found this document useful (0 votes)
17 views17 pages

CS Ip

Uploaded by

dhanushbuddy8
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)
17 views17 pages

CS Ip

Uploaded by

dhanushbuddy8
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/ 17

INTRODUCTION

This project “Fun games made with python” mainly aims on


creating simple yet enjoyable games and learning in the process
of coding those games
This project is mainly based on the creation of simplest games like
Hangman, Hand Cricket, Toss a coin, Roll a Die, Rock Paper
Scissors, Set game.
The Descriptions of the games are as given below:
1. Rock Paper Scissors (rps)
The game begins with a prompt for the player to enter
their name, then displays "ROCK PAPER SCISSORS
SHOOT!".
The player plays against the computer, choosing between
"Rock," "Paper," and "Scissors."
The computer randomly selects its move. Each round’s
result (player win, computer win, or draw) is displayed with
relevant details.
The first to reach 5 points wins. The result is stored in a
MySQL database with the player’s name, score, and
outcome (win/lose).

2. Toss (toss)
The player enters their name and presses enter to “toss” a
coin.
The computer randomly picks between "Heads" and "Tails."
The result is displayed and stored in the database along
with the player’s name.

3. Hangman (hangman)
The game selects a random word related to Ben 10 and
displays blanks representing the word.
The player guesses letters to reveal the word within a
limited number of guesses.
The player wins if they reveal the word before running out
of guesses; otherwise, they lose.
The final outcome (win or lose), along with the word, is
recorded in the database.
4. Set Game (set_game)
The game prompts for names of two players and asks them to
choose a mode (Ben 10, Marvel, or DC).
Based on the selected mode, a set of characters is randomly
generated for each player.
Each character set is displayed in a formatted table, and a
random winner is chosen and displayed.
The game records the player names, mode, and the winner in
the database.

5. Dice Roll (dice)


The player enters their name and rolls a virtual die.
A random number from 1 to 6 is generated and displayed as
the result.
The player’s name and the rolled number are saved to the
database for future reference.

Key learning objectives of this project:

Basic Python Syntax and Logic


Writing clean and efficient Python code.
Using variables, data types, loops, and conditionals to control
game flow.

Functions and Modular Programming


Breaking down game logic into smaller, reusable functions.
Managing complexity by creating modular code that’s easy to
debug and expand.

Data Structures
Applying lists, dictionaries, and tuples to manage game states
and data.
Understanding how different data structures affect game
performance and organization.
User Input and Interactivity
Capturing and processing user input to make games interactive.
Validating input to handle unexpected behaviors and improve
user experience.

Game Loops and State Management


Implementing game loops to handle ongoing processes, like
scorekeeping and game progression.
Managing game states to control when the game is active,
paused, or over.

Randomization and Probability


Using Python’s random library to add unpredictability, such as
random enemy movements or generating different levels.
Applying probability for game dynamics, making each
playthrough unique.

Error Handling and Debugging


Identifying and fixing bugs in code to ensure games run
smoothly.
Learning how to anticipate possible user mistakes and adding
safeguards.
LANGUAGE DESCRIPTION:
PYTHON:
Python, a dynamically typed and interpreted programming
language, stands out for its simplicity, readability, and versatility.
Guido van Rossum, the creator of Python, designed it with a
focus on code clarity and ease of use. This emphasis on
readability is reflected in Python's clean and concise syntax,
making it an ideal language for both beginners and experienced
developers.

One of Python's key strengths lies in its extensive standard


library, offering a wealth of modules and packages that
facilitate various tasks. This feature not only streamlines
development but also fosters a collaborative and supportive
community. Python's popularity extends across diverse domains,
including web development, data science, artificial intelligence,
machine learning, and automation.

Python's ease of learning and rapid development capabilities


make it an accessible entry point for newcomers to
programming. However, its powerful features, such as dynamic
typing and support for multiple programming paradigms, also
cater to the needs of seasoned developers. The language's
adaptability is evident in its application in scripting, software
development, and system automation.

Moreover, Python's cross-platform compatibility ensures that


code can be executed seamlessly on different operating
systems, enhancing its portability. The language's open-source
nature encourages collaboration and continuous improvement,
with a large and active community contributing to its growth.
SQL:

Python, a dynamically typed and interpreted programming


language, stands out for its simplicity, readability, and
versatility. Guido van Rossum, the creator of Python, designed
it with a focus on code clarity and ease of use. This emphasis
on readability is reflected in Python's clean and concise syntax,
making it an ideal language for both beginners and
experienced developers.

One of Python's key strengths lies in its extensive standard


library, offering a wealth of modules and packages that
facilitate various tasks. This feature not only streamlines
development but also fosters a collaborative and supportive
community. Python's popularity extends across diverse domains,
including web development, data science, artificial
intelligence, machine learning, and automation.

Python's ease of learning and rapid development capabilities


make it an accessible entry point for newcomers to
programming. However, its powerful features, such as dynamic
typing and support for multiple programming paradigms, also
cater to the needs of seasoned developers. The language's
adaptability is evident in its application in scripting, software
development, and system automation.

Moreover, Python's cross-platform compatibility ensures that


code can be executed seamlessly on different operating
systems, enhancing its portability. The language's open-source
nature encourages collaboration and continuous improvement,
with a large and active community contributing to its growth.
GAME LOGICS- BREAKDOWN:
Here’s a breakdown of the code structure and implementation list:
Imports and Database Connection
Modules Imported:
mysql.connector: Used to connect to and interact with a
MySQL database.
random: For generating random choices in games.
Database Connection:
Each game connects to the MySQL database using
mysql.connector.connect() within the function where it is
used.
Parameters: host, user, password, and database are provided
to establish a connection.
After operations, conn.commit() saves changes, and
conn.close() closes the connection.
Game 1: Rock Paper Scissors (rps())
Player Setup: Prompts the player for their name and stores it.
Gameplay Logic:
A loop allows continuous rounds of Rock, Paper, Scissors until
either the player or computer reaches 5 points.
The player’s choice is taken, and the computer makes a
random choice.
Based on the comparison of player and computer choices,
points are awarded.
Score Recording:
After a player or computer wins 5 rounds, the outcome
and score are stored in the database under rps_scores.
Game 2: Toss (toss())
Player Setup: Prompts the player for their name.
Gameplay Logic:
A virtual coin toss randomly returns either "Heads" or "Tails."
Result Recording:
The toss result is stored in the database in the toss_results
table, along with the player’s name.
Game 3: Hangman (hangman())
Player Setup: Prompts the player for their name.
Gameplay Logic:
Randomly selects a word and presents it as blanks.
The player guesses letters, and correct guesses fill in the
blanks.
The player can ask for a hint if they have 2 or fewer lives
remaining.
The game ends when the player completes the word or
exhausts their guesses.
Outcome Recording:
The result (win or lose) and the word are stored in the
hangman_scores table.
Game 4: Set Game (set_game())
Player Setup: Prompts for the names of two players and a game
mode (Ben 10, Marvel, or DC).
Gameplay Logic:
Based on the mode, the game selects a set of characters for
each player from predefined lists.
Character lists for each player are displayed in columns.
A random winner between the two players is chosen and
displayed.
Winner Recording:
Player names, chosen mode, and the winner’s name are saved
in the set_scores table.
Game 5: Dice Roll (dice())
Player Setup: Prompts the player for their name.
Gameplay Logic:
A virtual dice roll randomly generates a number between 1 and
6.
Result Recording:
The roll result is saved in the database in the dice_rolls table,
along with the player’s name.
Running Each Game
At the bottom of the code, function calls (like rps(), toss(), etc.) are
given to be selected based on the user’s choice.
SOURCE CODE:
CREATION OF DATABASE:

import mysql.connector

# Setup connection to MySQL


conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password"
)
cursor = conn.cursor()

# Create database and tables


cursor.execute("CREATE DATABASE IF NOT EXISTS game_scores")
cursor.execute("USE game_scores")

# Table for RPS scores


cursor.execute("""
CREATE TABLE IF NOT EXISTS rps_scores (
id INT AUTO_INCREMENT PRIMARY KEY,
player_name VARCHAR(50),
score INT,
outcome VARCHAR(10),
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")

# Table for Toss results


cursor.execute("""
CREATE TABLE IF NOT EXISTS toss_results (
id INT AUTO_INCREMENT PRIMARY KEY,
player_name VARCHAR(50),
result VARCHAR(5),
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Table for Hangman scores
cursor.execute("""
CREATE TABLE IF NOT EXISTS hangman_scores (
id INT AUTO_INCREMENT PRIMARY KEY,
player_name VARCHAR(50),
word VARCHAR(50),
outcome VARCHAR(10),
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
# Table for Set game scores
cursor.execute("""
CREATE TABLE IF NOT EXISTS set_scores (
id INT AUTO_INCREMENT PRIMARY KEY,
player1 VARCHAR(50),
player2 VARCHAR(50),
mode VARCHAR(20),
winner VARCHAR(50),
timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
""")
conn.commit()
conn.close()

THE GAME CODE:


import mysql.connector
import random

# Function for Rock-Paper-Scissors Game


def rps():
# Establish database connection
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="game_scores"
)
cursor = conn.cursor()
# Welcome message and player input
player_name = input("Enter your name: ")
print("\n\t\t\t ROCK PAPER SCISSORS SHOOT!")
GAME_LIST = ["ROCK", "SCISSORS", "PAPER"]
computer_score = 0
player_score = 0
# Game loop until either player or computer reaches 5 points
while computer_score < 5 and player_score < 5:
user_choice = input("Enter your choice (Rock, Paper, or Scissors):
").upper()
computer_choice = random.choice(GAME_LIST)
# Ensure the player's choice is valid
if user_choice in GAME_LIST:
if (user_choice == "ROCK" and computer_choice == "SCISSORS") or \
(user_choice == "SCISSORS" and computer_choice == "PAPER") or \
(user_choice == "PAPER" and computer_choice == "ROCK"):
player_score += 1
print(f"Computer chose {computer_choice}. You get a point.")
elif user_choice == computer_choice:
print(f"Computer chose {computer_choice}. It’s a draw; No points.")
else:
computer_score += 1
print(f"Computer chose {computer_choice}. Computer gets a point.")
else:
print("Invalid choice. Please select Rock, Paper, or Scissors.")
# Determine outcome and record it in the database
outcome = "WIN" if player_score == 5 else "LOSE"
cursor.execute("INSERT INTO rps_scores (player_name, score, outcome)
VALUES (%s, %s, %s)",
(player_name, player_score if player_score == 5 else computer_score,
outcome))
conn.commit()
conn.close()
print(f"{'YOU WIN!' if player_score == 5 else 'You lose'}")
# Function for Toss Game
def toss():
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="game_scores"
)
cursor = conn.cursor()
player_name = input("Enter your name: ")
input("Press Enter to toss the coin!")
result = "Heads" if random.randint(0, 1) == 0 else "Tails"
print(f"The coin toss result is: {result}")
cursor.execute("INSERT INTO toss_results (player_name, result)
VALUES (%s, %s)", (player_name, result))
conn.commit()
conn.close()
# Function for Hangman Game
def hangman():
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="game_scores"
)
cursor = conn.cursor()
player_name = input("Enter your name: ")
words = ["rath", "fastrack", "atomix", "lodestar", "ghostfreak"]
hints = {
"rath": "Orangy beast with wolverine claws.",
"fastrack": "Exhibits super speed.",
"atomix": "Looks good and related to chemicals.",
"lodestar": "Controls magnetic fields.",
"ghostfreak": "Can pass through walls."
}
word = random.choice(words)
print("\t\t\tWelcome to HANGMAN (Ben 10 version)!")
word_length = len(word)
display_word = "_" * word_length
guesses = []
lives = 5
player_wins = False
# Game loop for Hangman
while lives > 0:
print(f"The word is: {display_word}")
print(f"Remaining lives: {lives}")
# Offer a hint if lives are low
if lives <= 2:
if input("Would you like a hint? (y/n): ").lower() == "y":
print(f"Hint: {hints[word]}")
guess = input("Guess a letter: ").lower()
if guess in guesses:
print("You have already guessed that letter! Try again.")
elif guess in word:
print("Correct guess!")
display_word = "".join([letter if letter == guess else display_word[i]
for i, letter in enumerate(word)])
guesses.append(guess)
if "_" not in display_word:
player_wins = True
break
else:
print("Incorrect guess.")
lives -= 1
# Record outcome in database
outcome = "WIN" if player_wins else "LOSE"
cursor.execute("INSERT INTO hangman_scores (player_name,
word, outcome) VALUES (%s, %s, %s)", (player_name, word,
outcome))
conn.commit()
conn.close()
print("Congratulations, you won!" if player_wins else "Sorry, you
lost!")
print(f"The correct word was: {word}")
# Function for Set Game
def set_game():
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="game_scores"
)
cursor = conn.cursor()
player1 = input("Enter first player name: ")
player2 = input("Enter second player name: ")
mode = input("Enter mode (Ben10, Marvel, DC): ").lower()

# Select character sets based on mode


if mode == "ben10":
character_sets = [
["Grey Matter", "Humangasaur", "Waybig", "Chromastone"],
["Diamondhead", "Swampfire", "Fourarms", "Rath"],
["Bigchill", "Heatblast", "Cannon Bolt", "Brainstorm"],
["Echo Echo", "Stingfly", "XLR8", "Ghostfreak"]
]
elif mode == "marvel":
character_sets = [
["Iron Man", "Hulk", "Thor", "Strange"],
["Ghost Rider", "Spider-Man", "Doom", "Deadpool"],
["Venom", "Knull", "Dormammu", "Galactus"],
['Arishem','Black Panther','wolverine','Carnage']
]
elif mode == "dc":
character_sets = [
["Darkseid", "Flash", "Reverse Flash", "Superman"],
["Batman", "Wonder Woman", "Joker", "Spectre"],
["Lucifer", "Michael", "Fate", "Manhattan"],
["Martian Manhunter","Aquaman","Greatest Darkness",'Ellaine']
]
else:
print("Invalid mode chosen")
return
random.shuffle(character_sets)
player1_set = [random.choice(characters) for characters in
character_sets]
player2_set = [random.choice(characters) for characters in
character_sets]
winner = random.choice([player1, player2])
cursor.execute("INSERT INTO set_scores (player1, player2, mode,
winner) VALUES (%s, %s, %s, %s)", (player1, player2, mode, winner))
conn.commit()
conn.close()
print(f"{player1}\t\t{player2}")
for p1_char, p2_char in zip(player1_set, player2_set):
print(f"{p1_char:<20} {p2_char:<20}")
print(f"The winner is {winner}!")
# Function for Dice Game
def dice():
conn = mysql.connector.connect(
host="localhost",
user="your_username",
password="your_password",
database="game_scores"
)
cursor = conn.cursor()
player_name = input("Enter your name: ")
dice_result = random.randint(1, 6)
print(f"The dice rolled a {dice_result}.")
cursor.execute("INSERT INTO dice_rolls (player_name, result)
VALUES (%s, %s)", (player_name, dice_result))
conn.commit()
conn.close()
# Game menu
print("Choose a game to play:")
print("1. Rock Paper Scissors")
print("2. Toss a Coin")
print("3. Dice Roll")
print("4. Hangman")
print("5. Set Game")
try:
choice = int(input("Enter your choice: "))
if choice == 1:
rps()
elif choice == 2:
toss()
elif choice == 3:
dice()
elif choice == 4:
hangman()
elif choice == 5:
set_game()
else:
print("Invalid choice! Please select a valid option.")
except ValueError:
print("Please enter a number between 1 and 5.")
SYSTEM REQUIREMENTS:

HARDWARE REQUIRED:
Windows 7 +
Mac OS X 10.11 or higher,64-bit
Linux: RHEL 6/7,64-BIT(almost all libraries also work
in urban)
4 GB+ RAM
5 GB+ free space
Printer for printing

SOFTWARE REQUIRED:
Operating system
Python 3.10 +
SQL 5.0+
MS Word, for preparing documentation
BIBLIOGRAPHY:

Computer science with python – class XII By; Sumita Arora


slideshare.net
canva.com
python4csip.com
en.wikipedia.org
en.wikipedia.org

You might also like