0% found this document useful (0 votes)
21 views23 pages

Computers Board Project

hangman program in python - can be executed on repl.it

Uploaded by

Shloka Reddy
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)
21 views23 pages

Computers Board Project

hangman program in python - can be executed on repl.it

Uploaded by

Shloka Reddy
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/ 23

Computers Board Project

2023-24
Hangman Game

Coded using Python XII Science


Index

S.No. Topic Page No.


1. Introduction to 5
Python
2. About the Project 7
(Code Explanation)
3. Software and 9
Hardware
Requirements
4. Source Code 11
5. Output Screens 18
6. Advantages and 21
Limitations
7. Bibliography 22
About the Project
Source Code
import random
import string import
sys import pygame
as pg

sw,sh = 1280, 760 sc


= (sw/2, sh/2)
screen = pg.display.set_mode((sw,sh))
pg.display.set_caption("Hangman+ by Swathi, Shloka and Sanjana")
default_font = pg.font.SysFont(None, 40)

# Assigning all the primary/secondary colors to a dictionary to use more practically colors
= {"black":(0,0,0), "darkgray":(70,70,70), "gray":(128,128,128), "lightgray":(200,200,200),
"white":(255,255,255), "red":(255,0,0),
"darkred":(128,0,0),"green":(0,255,0),"darkgreen":(0,128,0), "blue":(0,0,255),
"navy":(0,0,128), "darkblue":(0,0,128),
"yellow":(255,255,0), "gold":(255,215,0), "orange":(255,165,0),
"lilac":(229,204,255),"lightblue":(135,206,250),"teal":(0,128,128),
"cyan":(0,255,255), "purple":(150,0,150), "pink":(238,130,238), "brown":(139,69,19),
"lightbrown":(222,184,135),"lightgreen":(144,238,144),

"turquoise":(64,224,208),"beige":(245,245,220),"honeydew":(240,255,240),"lavender":(230,
230,250),"crimson":(220,20,60)}

# Loading images to a dictionary


images = {"logo":pg.image.load("imgs/logo.png"),0:pg.image.load("imgs/empty.png"),
1:pg.image.load("imgs/v1.png"), 2:pg.image.load("imgs/v2.png"),

3:pg.image.load("imgs/v3.png"),4:pg.image.load("imgs/v4.png"),5:pg.image.load("imgs/v5.p
ng"),6:pg.image.load("imgs/v6.png")}
alphabet = list(string.ascii_uppercase)

class Button(object):
def __init__(self, color, pos, width, height, letter, active = False, type = 1, size = 40):
self.type = type
self.active = active
self.clicked = False
self.rollOver = False
self.size = size
self.font = pg.font.SysFont(None, self.size)
self.color = color
self.letter = letter
self.pos = pos
self.width = width
self.height = height
self.subsurface = pg.Surface((self.width, self.height))
self.subsurface.fill(self.color)
self.text = self.font.render(self.letter, True, colors["white"])

def Draw(self, surface):


if self.type == 1:
if self.rollOver:
self.subsurface.set_alpha(200)
else:
self.subsurface.set_alpha(255)
if not self.clicked:
surface.blit(self.subsurface, self.pos)
self.subsurface.blit(self.text,(self.width/4,self.height/5))
if self.type == 2:
if self.active:
self.subsurface.set_alpha(255)
else:
self.subsurface.set_alpha(100)
surface.blit(self.subsurface, self.pos)
self.subsurface.blit(self.text, (self.width / 4, self.height / 5))
notesArea = pg.Surface((sw,700))
notesArea.fill(colors["beige"])

buttonArea = pg.Surface((sw, 100))


buttonArea.fill(colors["lavender"])

letters = []
j=0
for number, letter in enumerate(alphabet):
if number > 12:
number = number - 13
j=1
letters.append(Button(colors["gray"], (70+number*90,140+j*60), 50, 50, letter))

chbuttons = []
chbuttons.append(Button(colors["gray"], (30, 400), 90,40, "SPORTS", False, 2, 30))
chbuttons.append(Button(colors["gray"], (120, 400), 90,40, "CITIES", True, 2, 30))

errorCount = 0

#SPORTS
sports = open("wordsEN.txt","r")

# CITIES
cities = open("wordsTR.txt","r")

choice = 1 #1 == Sports, 2 == Cities, DEFAULT IS Sports


currentchoice = sports if choice == 1 else cities
word_list= currentLanguage.read().splitlines()
currentWord = random.randrange(0, len(word_list))
word= word_list[currentWord]

guessed = []

lw = 40
ls = 10
needRestart = False
winCount = 0
pointCount = 0
spaceCount = 0
for letter in word_list[currentWord]:
if letter == " ":
spaceCount += 1
sports_content = sports.read()
cities_content = cities.read()
print(len(sports_content))
print(len(cities_content))

while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
if event.type==pg.MOUSEMOTION:
for button in letters:
currentRect = button.subsurface.get_rect(topleft = (button.pos[0], button.pos[1]))
if currentRect.collidepoint(pg.mouse.get_pos()):
button.rollOver = True
else:
button.rollOver = False
if event.type == pg.MOUSEBUTTONDOWN:
if event.button == 1:
for button in letters:
if button.rollOver is True and button.clicked is False:
button.clicked = True
guessed.append(button.letter)
noError = False
for letter in currentchoice[currentWord]:
if button.letter == letter:
noError = True
if errorCount < 6 and not noError:
errorCount += 1
for button in chbuttons:
currentRectLang = button.subsurface.get_rect(topleft = (button.pos[0],
button.pos[1]))

if currentRectLang.collidepoint(pg.mouse.get_pos()):
button.active = True
if button.letter == "English":
currentchoice = cities
else:
currentchoice = sports
currentIndex = chbuttons.index(button)
for subbutton in chbuttons
if chbuttons.index(subbutton) =currentIndex:
pass
else:
subbutton.active = False
needRestart = True

screen.fill(colors["white"])
screen.blit(notesArea, (0,0))
screen.blit(buttonArea, (0, 700))

screen.blit(images["logo"], (sc[0]-images["logo"].get_rect().width/2, 10)) # LOGO


screen.blit(images[errorCount], (sc[0]-images[errorCount].get_rect().width/2,
sc[1]images[errorCount].get_rect().height/2+70))

for letter in letters:


letter.Draw(screen)

for langbut in chbuttons:


langbut.Draw(screen)
stats_font = pg.font.SysFont(None, 25, False, True) # A FONT FOR THE STATS
winCountText = stats_font.render("TOTAL WINS : " + str(winCount), True, colors["black"])
pointCountText = stats_font.render("TOTAL POINTS : " + str(pointCount), True,
colors["black"])
screen.blit(winCountText, (30, 300))
screen.blit(pointCountText, (30, 330))

totalShown = 0 # TOTAL LETTERS SHOWN AT THE BOTTOM PART


if not needRestart:
for i,letter in enumerate(word_list[currentWord]):
text = default_font.render(letter, True,colors["black"])
posX = (1280 - len(currentchoice[currentWord]) * (lw + ls))/2 + i * (lw + ls)
posY = 740
if letter != " ":
pg.draw.rect(screen, colors["black"], (posX, posY, lw, 3))
else:
pg.draw.rect(screen, colors["lavender"], (posX, posY, lw,3))
if letter in guessed:
totalShown += 1
screen.blit(text, (posX+lw/3, posY-30))

pg.display.update

final_font = pg.font.SysFont(None, 80)


lose_text = final_font.render("YOU LOSE", True, colors["darkred"])
win_text = final_font.render("YOU GUESSED IT", True, colors["darkgreen"])
if errorCount >= 6 or needRestart:
if not needRestart:
screen.blit(lose_text, (500,380))
pg.display.update()
pg.time.wait(1000)
guessed.clear()
pointCount = 0

errorCount = 0

winCount = 0

for letter in letters:

letter.clicked = False

currentWord = random.randrange(0, len(word_list))


spaceCount = 0
for letter in currentchoice[currentWord]:
if letter == " ":
spaceCount += 1
needRestart = False

pg.time.wait(1000)
if totalShown == len(currentchoice[currentWord]) - spaceCount: # IF IT'S A WIN CONDITION
screen.blit(win_text, (380, 380))

pg.display.update()

pg.time.wait(1000)

guessed.clear()

pointCount += 600 + winCount*10 - errorCount * 100 # POINTS SYSTEM, GAIN FEWER


POINTS IF YOU HAD MORE ERRORS
errorCount = 0

winCount+=1

for letter in letters:


letter.clicked = False
currentWord = random.randrange(0, len(word_list))

spaceCount = 0

for letter in word_list[currentWord]:

if letter == " ":


spaceCount += 1
pg.time.wait(1000)
TEXT FILES
Gameplay (Output)

• This is the initial layout when the game starts.

The game offers two options, which can be chosen by


the user:
• If the clicked letter is present in the word, it appears
on the dashed line at the bottom of the screen.

• If the clicked letter is not present in the word, the


body of the hangman starts to form.
• The game ends on either guessing the entire word
correctly or on the complete formation of the
hangman.

Game Win
Screen

Game Lose
Screen

The game keeps a record of the user’s wins and total


points in one gameplay.
Advantages and Limitations
Advantages:
1. Interactive UI: The program has a graphical user interface
built using Pygame, making it visually appealing and
interactive.
2. Customizable Design: The game's design elements like
buttons, colors, and images are customizable, allowing for
easy adjustments or enhancements.
3. Multiple Categories: It includes two categories (sports and
cities) for word guessing, offering variety and allowing for
expansion with additional categories.
4. Scalability: The structure of the code is modular, making it
relatively straightforward to add more words or categories
without significant modification.
5. Point System: Incorporation of a point system adds a
competitive aspect, providing a scoring mechanism for users,
enhancing engagement.
Limitations:
1. Error Handling: The program lacks comprehensive error
handling. If unexpected user actions occur or if files are
missing (like images), the program might crash or behave
unexpectedly.
2. Limited Word Bank: The word bank is fixed within the code.
Adding more words or categories would require manual
intervention within the code rather than dynamic addition or
modification through an interface.
3. UI Responsiveness: The UI may not adapt to different screen
sizes or resolutions, potentially causing layout issues on
certain displays.
4. File Paths: The program relies on specific file paths for
images. If these paths change or the images are moved, it
could lead to loading errors.
Bibliography

1. www.wikipedia.com
2. www.freecodecamp.com
3. www.devdocs.io
4. www.youtube.com

You might also like