Copy of Niruban

Download as pdf or txt
Download as pdf or txt
You are on page 1of 55

Gaming has always been a popular way to combine entertainment

with learning. With the rise of programming, developing simple


games has become an engaging method to understand core
concepts of computer science, such as logic building, problem-
solving, and modular programming.

This project, titled "GAME LIBRARY," is a Python-based game


library developed as part of the Class 12th Computer Science
curriculum. It contains three classic and interactive games:

1. Hangman: A word-guessing game where players attempt to


uncover a hidden word by guessing its letters.
2. Rock Paper Scissors: A simple two-player game where the
user competes with the computer, aiming to predict and
counter the computer's choice.
3. Word Building: A multiplayer word game that tests the
players' vocabulary and quick thinking by creating words
based on the last letter of the previous word
4. .

The primary objective of this project is to design a fun and


engaging application while applying and showcasing
programming concepts such as functions, loops, conditionals, and
library integration.

The games are designed to be simple yet interactive, encouraging


users to engage in strategic thinking and develop problem-solving
skills. This project also demonstrates the practical application of
Python’s libraries, such as random and nltk, to create real-world
solutions.

By the end of this project, the goal is to provide a functional,


modular, and user-friendly game library that highlights the
developer's understanding of software development principles.
PAGE NO.
S.NO TOPIC
1 INTRODUCTION

2 SYSTEM
REQUIRMENTS
3 MODULES USED

4 BUILD-IN
FUNCTIONS
5 USER DEFINED
FUNCTION
6 SOURCE CODE

7 OUTPUT

8 EXPLANATION

9 CONCLUSION

10 BIBLIOGRAPHY
I, J NIRUBAN RAAJ of class XII A, express my
gratitude to my school authorities for allowing me
to undertake the project titled “GAME LIBRARY”.
I naturally could not have done justice to my
delicate assignment had I not been privileged to
get the animate guidance from MRS. RAMYA,
Computer Science Teacher. I also express sincere
thanks to my family who extended helping hand in
completing this project
This is to certify that J. NIRUBAN RAAJ, a
student of class XII-A of PM SHRI KENDIYA
VIDYALAYA, Ashok Nagar, Chennai, has
successfully completed the Computer Science
investigatory project work under the guidance
of MRS. RAMYA on the topic “Game Library” as
prescribed by the Central Board of Secondary
Education for AISSCE for the academic year
2024-25

Roll no : Date:

Signature of external Signature of


examiners The Teacher
1. Hardware Requirements
 Processor: Intel Core i3 or equivalent (minimum), Core i5 or
higher recommended.
 RAM: 4GB (minimum), 8GB or higher recommended for
smooth performance.
 Storage:
o 500MB of free disk space for project files and
dependencies.
o Additional space for Python installation if not already
installed.
 Display: Monitor with a resolution of 1024x768 or higher.
 Peripherals: Keyboard and mouse for input.
2. Software Requirements
 Operating System:
o Windows 10 or higher (64-bit preferred).
o Linux (Ubuntu 18.04 or higher).
o macOS 10.15 (Catalina) or higher.
 Programming Environment:
o Python 3.7 or higher.
 Required Libraries:
o random (built-in).
o nltk: Used for word validation in the Word Building
game.
 Text Editor/IDE:
o VS Code, PyCharm, or any Python-compatible IDE.
o Notepad++ or Sublime Text for editing .txt files used in
the project.
3. Python Libraries Installation
 The following command must be executed to install the
required external library:

 After installation, download the word corpus using the


following Python command:

4. Execution Environment
 Command-Line Interface (CLI): The games are designed
to run in a terminal or command prompt.
 Dependencies: Ensure Python and all required libraries are
properly installed before execution.
5. Network Requirements
 Internet connectivity is required for the initial setup of nltk (to
download the word dataset).
1. random
 Purpose:
The random module is used to generate random choices
and numbers, which add unpredictability to the games.
 Usage in Project:
o Selecting random words for the Hangman game.
o Randomizing the computer's choice in Rock Paper
Scissors.
2. nltk (Natural Language Toolkit)
 Purpose:
The nltk library is a powerful tool for natural language
processing. It provides access to a large collection of words
and helps validate user inputs.
 Usage in Project:
o Checking if the entered word in the Word Building game
exists in the English language dictionary.
o Downloading the words corpus to use in word
validation.
What is a Built-in Function?
A built-in function is a function that is included in
Python's standard library and is readily available for use
without requiring an import or definition. These
functions are integral to Python and allow developers to
perform common tasks such as mathematical
operations, data manipulation, and input/output
handling efficiently.
List of Built-in Functions Used in This Project
1. print()
 Purpose: Outputs text or data to the console.
 Usage in Project:
o Display instructions, game menus, feedback
(e.g., "You win!" or "Game Over"), and game
progress.
2. input()
 Purpose: Accepts user input as a string.
 Usage in Project:
o Collects player choices, guesses, and game
inputs like the number of players or rounds.
3. len()
 Purpose: Returns the number of items in an object
(e.g., length of a string or list).
 Usage in Project:
o Checks the length of a word in the Word
Building game to ensure it meets the minimum
requirement.
4. list()
 Purpose: Converts an iterable into a list.
 Usage in Project:
o Converts strings (e.g., the randomly chosen
word in Hangman) into lists of characters for
easier manipulation.
5. open()
 Purpose: Opens a file and returns a file object.
 Usage in Project:
o Opens words.txt to read a list of words for
Hangman.
o Writes temporary data to Worddata.txt in the
Word Building game.
6. read()
 Purpose: Reads the content of a file as a single
string.
 Usage in Project:
o Loads the words from words.txt into a variable
for Hangman.
7. splitlines()
 Purpose: Splits a string into a list at each newline
character.
 Usage in Project:
o Splits the content of words.txt into individual
words for Hangman.
8. append()
 Purpose: Adds an item to the end of a list.
 Usage in Project:
o Appends valid words to a list in the Word
Building game.
9. lower()
 Purpose: Converts a string to lowercase.
 Usage in Project:
o Normalizes user inputs to ensure case-
insensitive comparisons.
10. upper()
 Purpose: Converts a string to uppercase.
 Usage in Project:
o Formats output for better readability, such as
displaying choices in Rock Paper Scissors.
11. pop()
 Purpose: Removes an item from a list by its index
and returns it.
 Usage in Project:
o Eliminates a player from the Word Building
game if they make an invalid move.
12. quit()
 Purpose: Exits the Python program.
 Usage in Project:
o Ends the game when the player decides not to
continue.
13. int()
 Purpose: Converts a string or float into an integer.
 Usage in Project:
o Validates and processes numeric inputs like the
number of players in Word Building.
14. float()
 Purpose: Converts a string or integer into a float.
 Usage in Project:
o Accepts fractional input for the number of
rounds in Word Building.
15. range()
 Purpose: Generates a sequence of numbers.
 Usage in Project:
o Iterates through a sequence in loops, such as
assigning names to players.
16. set()
 Purpose: Creates an unordered collection of unique
elements.
 Usage in Project:
o Checks for unique letters or validates words in
the Word Building game.
What is a User-Defined Function?
A user-defined function is a block of code written by the
programmer to perform a specific task. Unlike built-in
functions provided by Python, user-defined functions
are created to simplify repetitive tasks, improve code
reusability, and organize the program structure. These
functions are defined using the def keyword, followed
by a function name and optional parameters.
List of User-Defined Functions in This Project
1. hangman()
 Purpose:
Implements the Hangman game logic.
 Explanation:
o Manages the game flow by displaying hangman
graphics, tracking guesses, and checking if the
guessed letters match the chosen word.
o Provides feedback on correct and incorrect
guesses and determines whether the player
has won or lost.
2. make_a_guess() (Called within hangman())
 Purpose:
Handles the logic for processing a player's letter
guess.
 Explanation:
o Checks if the guessed letter exists in the chosen
word.
o Updates the game state (e.g., reveals the
guessed letter in the word or increments the
mistake count).
3. Rock_Paper_scissor()
 Purpose:
Implements the Rock Paper Scissors game.
 Explanation:
o Accepts user input, generates a random choice
for the computer, and compares the two to
determine the winner.
o Tracks and displays the number of wins, losses,
and draws.
4. word_building()
 Purpose:
Manages the Word Building game logic.
 Explanation:
o Handles player input, validates words using the
nltk library, and ensures each word starts with
the last letter of the previous word.
o Tracks scores based on word length and
difficulty.
5. get_player_count() (Called within word_building())
 Purpose:
Collects and validates the number of players for the
Word Building game.
 Explanation:
o Ensures the player count is between 2 and 6,
with appropriate error handling for invalid
inputs.
6. get_player_names() (Called within word_building())
 Purpose:
Collects and stores player names for the Word
Building game.
 Explanation:
o Loops through the number of players and
accepts their names as input.
7. is_valid_word(previous_word, current_word) (Called
within word_building())
 Purpose:
Validates if the current word starts with the last
letter of the previous word.
 Explanation:
o Returns True if the condition is satisfied;
otherwise, returns False.
8. is_word_in_dictionary(word) (Called within
word_building())
 Purpose:
Checks if a word exists in the English dictionary
using the nltk library.
 Explanation:
o Uses the word list from nltk to verify word
validity.
9. calculate_score(word) (Called within word_building())
 Purpose:
Calculates a player's score based on the length and
complexity of the word.
 Explanation:
o Assigns points based on word length, with
additional points for using difficult letters like
'Q', 'Z', 'J', and 'X'.
10. play_game(no_rounds) (Called within
word_building())
 Purpose:
Handles the game rounds, player turns, and scoring
for the Word Building game.
 Explanation:
o Ensures the flow of the game, validates each
word, and calculates scores.
o Determines and displays the winner at the end
of the game.
Advantages of Using User-Defined Functions in
This Project
1. Code Reusability: Functions like make_a_guess()
and play_game() can be reused in different parts of
the project.
2. Improved Readability: Breaking the project into
smaller functions makes it easier to understand.
3. Modularity: Each function handles a specific task,
which simplifies debugging and testing.
4. Efficiency: Reduces redundancy by encapsulating
frequently used logic within functions.
#---------------------------------------GAME LIBRARY-------------------------------
----------------
import random as r
#----------------------------------Hangman-------------------------------------------
----------
def hangman():
print('\n \n------------------------------ Hangman -----------------------------
-')
print("\n"," ***Only one players can play this game***")
print("\n"," -Let's Start the game-","\n")
global chances
global chosen_word
global guess
global act
global blank_list
def make_a_guess():
global chances
global chosen_word
global guess
global act
global blank_list
x,y = 0,0
y=0
correct_guess = False
for i in chosen_word:
if guess.lower() == chosen_word[x]:
act[x] = guess.lower()
blank_list[y] = guess.lower()
correct_guess = True
x += 1
y += 2
if correct_guess == False:
print(f"There is no {guess}, sorry.")
chances +=1
x,y = 0,0
#---------------------------------------------------------------------------------------
-------
#GRAFICS FOR THE GAME
hangman_grafics = ['''
+---+
| |
|
|
|
|
=========''', '''
+---+
| |
O |
|
|
|
=========''', '''
+---+
| |
O |
| |
|
|
=========''','''
+---+
| |
O |
/| |
|
|
=========''','''
+---+
| |
O |
/|\ |
|
|
=========''', '''
+---+
| |
O |
/|\ |
/ |
|
=========''', '''
+---+
| |
O |
/|\ |
/\ |
|
=========''']
#---------------------------------------------------------------------------------------
-------
fo=open("words.txt","r")
word_list = fo.read().splitlines()
the_word = r.choice(word_list)
chosen_word = list(the_word)
blank = ""
for i in chosen_word:
blank += "_"
act=list(blank)
blank=" ".join(blank)
blank_list = list(blank)
chances = 0
#---------------------------------------------------------------------------------------
-------
print(hangman_grafics[chances])
guess = input(f"Welcome to hangman\n{blank}\nMake a guess? ")
make_a_guess()
print(hangman_grafics[chances])
print(''.join(blank_list))
make_a_guess()
while chances < 6:
if chosen_word == act:
print("YOU WIN!")
break
guess = input("Make another guess? ")
make_a_guess()
print(hangman_grafics[chances])
print(''.join(blank_list))
if chances == 6:
print("GAME OVER")
print(f"The Word is {the_word}")
fo.close()
#------------------------------------------------------------------------------------------
----

#------------------------------------------------------------------------------------------
----
#-----------------------------------Rock Paper Scissors-----------------------------
-----------
def Rock_Paper_scissor():
print('\n \n--------------------------- Rock Paper Scissors -------------------
--------')
print("\n"," ***Only one players can play this game***")
print("\n"," -Let's Start the game-","\n")
print('''
**************************************
* NOTE *
* *
* Rock vs Paper -> Paper Wins *
* Paper vs Scissors -> Scissors Wins *
*Rock vs Scissors -> Rock Wins *
**************************************''')

options = ["rock", "paper", "scissors"]


print()

draws,wins,loses=0,0,0

c="yes"
while c=="yes":
uchoice = input("Choose Rock, Paper, or Scissors: ")
uchoice = uchoice.lower()
cchoice = r.choice(options)
cchoice = cchoice.lower()
print()
print("You chose: ", uchoice.upper())
print("Computer chose: ", cchoice.upper())
print()
if uchoice == cchoice:
print("It's a DRAW!")
draws+=1
elif uchoice == "rock" and cchoice == "scissors":
print("ROCK beats SCISSORS")
print("You win!")
wins+=1
elif uchoice == "paper" and cchoice == "rock":
print("PAPER beats ROCK")
print("You win!")
wins+=1
elif uchoice == "scissors" and cchoice == "paper":
print("SCISSORS beats PAPER")
print("You win!")
wins+=1
else:
print(f"{cchoice.upper()} beats {uchoice.upper()}")
print("Computer wins!")
loses+=1
print()
print(f"Win = {wins} Lose = {loses} Draw = {draws}")
print()
c=input(" Want to play another match?? ( yes or no ) : ")
c=c.lower()
print()
if c != 'yes':
print("Game over!!")
#------------------------------------------------------------------------------------------
-------------------------------------------
def word_building():
import nltk
from nltk.corpus import words
global l
l=[]
nltk.download('words')
fo = open("Worddata.txt","w+")
#------------------------------------------------------------------------------------------
-------------------------------------------
def get_player_count():
while True:
try:
count = int(input("Enter number of players (2-6): "))
if count < 2:
print("\n","***Atleast two playes should be there to play
this game***","\n")
decision=input("If you want to continue to the game
'press c' else just 'press enter' : ")
decision = decision.lower()
print()
if decision == "c":
count = int(input("Enter number of players (2-6): "))
if 2 <= count <= 6:
return count
else:
print("\nEnter a value between 2 to 6\n")
else:
quit()
if count > 6:
print("\n","***Only 6 players can play this
game***","\n")
decision=input("If you want to continue to the game
'press c' else just 'press enter' : ")
decision = decision.lower()
print()
if decision == "c":
count = int(input("Enter number of players (2-6): "))
if 2 <= count <= 6:
return count
else:
print("\nEnter a value between 2 to 6\n")
else:
quit()
except ValueError:
print("Invalid input. Please enter a number.")
return count
def get_player_names(count):
players = []
print()
for i in range(count):
name = input(f"Enter name for Player {i + 1}: ")
players.append(name)
return players

def is_valid_word(previous_word, current_word):


return current_word[0].lower() == previous_word[-1].lower()

def is_word_in_dictionary(word):
word_list = set(words.words())
return word in word_list

def calculate_score(word):
length = len(word)
score = 0
if length <= 3:
score = 1
elif length <= 5:
score = 2
else:
score = 3
difficult_letters = set('qzjx')
for letter in word:
if letter in difficult_letters:
score += 1
return score

def play_game(no_rounds):
global l
letter_limit=int(input("What is the minimum value of letters in
the word: "))

player_count = get_player_count()
players = get_player_names(player_count)

scores = {player: 0 for player in players}


current_word = input(f"\n{players[0]} enter the first word:
").lower()
if len(current_word) < letter_limit :
print(f"The word should have atleast {letter_limit} letters,
Please start again with a valid word.")
current_word = input(f"{players[0]} enter the first word:
").lower()

l.append(current_word)

if not is_word_in_dictionary(current_word):
print("The first word is not valid. Please start again with a
valid word.")
return

player_turn = 1
rounds = 1/len(players)
while rounds < no_rounds:
if int(rounds) == rounds :
print(f"Round {int(rounds)}")
next_word = input(f"{players[player_turn]} enter a word
starting with '{current_word[-1]}': ").lower()
if len(next_word) < letter_limit :
print(f"The word should have atleast {letter_limit} letters,
Please try again.\n")
next_word = input(f"{players[player_turn]} enter a word
starting with '{current_word[-1]}': ").lower()

l.append(next_word)

if not is_word_in_dictionary(next_word):
print(f"Invalid word '{next_word}' by {players[player_turn]}.
Please try again.\n")
continue

if is_valid_word(current_word, next_word):
print(f"Valid word by {players[player_turn]}!\n")
if rounds >= 1:
points = calculate_score(next_word)
scores[players[player_turn]] += points
print(f"Scores: {scores}\n")
rounds= rounds + (1/len(players))
current_word = next_word
player_turn = (player_turn + 1) % len(players)
else:
print(f"Invalid word by {players[player_turn]},
{players[player_turn]} Eliminated\n")
players.pop(player_turn)
maximum=0
max_player=""
for player, score in scores.items():
print(f"{player}: {score}")

l=[]
# Final scores display
print("\nFinal Scores:")
for player, score in scores.items():
if score > maximum:
maximum = score
max_player = player
print(f"\nThe Winner of the game is {max_player}\n \n")
#------------------------------------------------------------------------------------------
-------------------------------------------
print('--------------------------- Word Building ---------------------------')
print("\n"," ***Minimum 2 players***","\n","
***Maximum 6 players***","\n")
#------------------------------------------------------------------------------------------
-------------------------------------------
print("\n"," -Let's Start the game-","\n")
no_rounds = float(input("Enter number of rounds : "))
play_game(no_rounds)
fo.close()
#------------------------------------------------------------------------------------------
-------------------------------------------
#------------------------------------------------------------------------------------------
-------------------------------------------
print('--------------------------- Welcome to GAME LIBRARY ------------------
---------')
print("""
DEVELOPED BY:
NIRUBAN RAAJ
NIKHILESH
JEEVA""")
print('''
Games Available:

1) Hangman [Code : A]
2) Rock Papper Scissors [Code : B]
3) Word Building [Code : C]

***For Selecting the above games press the corresponding


code***''')

while True:
game_selection = input("Enter the code : ").lower()

if game_selection == "a":
hangman()
if game_selection == "b":
Rock_Paper_scissor()

if game_selection =="c":
word_building()

print('''
Games Available:

1) Hangman [Code : A]
2) Rock Papper Scissors [Code : B]
3) Word Building [Code : C]

***For Selecting the above games press the corresponding


code***''')

ask=input("Want to play any other game press 'y' if yes else just
press enter")

if ask == "y":
continue
else:
print("Thanks for using our application!!")
break
1.IMPORTING LIBRARIES:

PURPOSE:
These libraries are essential for implementing randomness
and word validation:
 random: Used for generating random choices in games
like Hangman and Rock Paper Scissors.
 nltk: Provides a word corpus for validating player inputs
in the Word Building game.

2. Hangman Game:
Function: hangman()

 Purpose: Implements the Hangman game where


players guess a hidden word.
 Core Features:
o Word Selection:

Randomly selects a word from a predefined list in


words.txt.
o Player Input and Validation:

Accepts guesses and checks if they are correct using


make_a_guess().

 Hangman Graphics: Visual feedback for wrong


guesses using ASCII art.
 Game Logic: Tracks the player's progress and
determines a win or loss after 6 incorrect guesses.
3. ROCK PAPER SCISSORS GAME:
Function: Rock_Paper_scissor()

 Purpose: Implements the classic Rock Paper


Scissors game.
 Core Features:
o Game Rules:

Displays the rules to the player.


o Random Computer Choice:

Randomly selects the computer's move.


o Result Calculation:

Compares the user’s choice with the computer’s and


declares the winner.
4. WORD BUILDING GAME:
Function: word_building()

 Purpose: A multiplayer game where players


construct words based on the last letter of the
previous word.
 Core Features:
o Player Setup:

Collects the number of players and their names.


o Word Validation:

Ensures words follow the game's rules and exist in


the dictionary.
o Score Calculation:

Assigns scores based on word length and


complexity.
5. UTILITY FUNCTIONS:
 make_a_guess():

Updates the Hangman game state based on the player's


input.
 get_player_count():

Validates and collects the number of players for the


Word Building game.
 get_player_names():

Accepts and stores the names of the players.


 is_valid_word():

Checks if a word starts with the last letter of the previous


word.
 is_word_in_dictionary():

Confirms if a word exists in the English dictionary using


nltk.
 calculate_score():

Determines points based on word length and complexity.


6. MAIN MENU:

 Purpose: Provides a menu to let users choose


between the three games.
 Functionality:
o Executes the corresponding function based on
user input:

7. EXIT CONDITION:

 Purpose: Allows users to play another game or exit


the application
Conclusion
The "GAME LIBRARY" project serves as a
comprehensive demonstration of programming
concepts and their application in real-world scenarios.
By developing a library of three engaging games—
Hangman, Rock Paper Scissors, and Word Building—this
project highlights the importance of logical thinking,
problem-solving, and modular programming.
Throughout the development process, various Python
concepts such as user-defined functions, file handling,
control structures, and external libraries like nltk were
utilized. The integration of these concepts into a
cohesive and interactive application showcases the
practical potential of programming.
This project not only provided an opportunity to
strengthen programming skills but also emphasized the
value of user-centric design, error handling, and
gameplay mechanics. It fostered creativity and
reinforced the importance of writing efficient, reusable,
and well-documented code.
Moving forward, the project has room for
enhancements, such as incorporating a graphical user
interface (GUI), adding more games to the library, and
enabling multiplayer features over a network. These
improvements would further enrich the learning
experience and expand the project's scope.
Overall, the "GAME LIBRARY" project has been a
fulfilling journey that blended learning and creativity,
and it stands as a testament to the power of
programming in creating enjoyable and functional
applications.
 NCERT CBSE COMPUTER SCIENCE
TEXTBOOK
 COMPUTER SCIENCE WITH PYTHON CLASS
XII – BY SUMITHA ARORA

You might also like