Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,161,441 members, 7,846,805 topics. Date: Saturday, 01 June 2024 at 12:55 AM

[SOURCE] Hangman Project - Programming - Nairaland

Nairaland Forum / Science/Technology / Programming / [SOURCE] Hangman Project (120 Views)

wizGrade School Manager is Open Source - 100% free + source code / Free C# Source Code On 30 Project work done now / Javascript Source Code For GPA Calculator (2) (3) (4)

(1) (Reply)

[SOURCE] Hangman Project by jackaustin631: 5:02pm On Oct 03, 2023
I've been programming as a hobby for a few months and wanted to share my first proper game. It's just hangman so nothing fancy and I decided to go with lives instead of adding limbs to the hangman figure, keeps it simpler.

It's python 3.4 so it won't work if your python interpreter is 2.x I've included a list of words for your convience as well. Just make sure to type the location of the words.txt for example C:\Users\Jake\Desktop/words.txt

[CODE]
import string
import random

class Hangman:

#lives: How many lives remaining.

#word: Word to be guess.

#guesses: True or false if the word is either guessed or not.

#HiddenWord: List of guessed letters and the hidden letters are marked with an underscore.

def __init__(self, word, lives):

self._lives = lives
self._hiddenWord = ['_ ' for i in word]
self._word = word
self._guesses = False

def __str__(self):

if self._hiddenWordString() == self._word:
return "Word: {0}".format(self._word)
else:
return "Word: {0}; You have {1} lives left".format(
self._hiddenWordString(), self._lives)

def livesRemaining(self):
return self._lives

#Returns the string representation of list hiddenWord.
def _hiddenWordString(self):
return "".join([ch for ch in self._hiddenWord])


#Checks if the letter exists and updates the underscore to the letter.
def updateGameStatus(self, char):
if char in self._word:colonhash:Char is the letter typed in by the user.
for i in range(len(self._word)):
if self._word == char:
self._hiddenWord = char
else:
self._lives -= 1
if self._word == self._hiddenWordString():
self._guesses = True
return self._word.count(char)


def guesses(self):
return self._guesses


def removeLineEndings(string):
return string.replace('\n' if '\n' in string else '\n', '')


#Counts how many times a letter occurs in a word. Allows for nine of the same letters.
def charToString(num):
return ['once', 'twice', 'three times', 'four times', 'five times',
'six times', 'seven times', 'eight times', 'nine times'][num - 1]


def play(word, lives):
#Main part of the game that deals with user input and output.
hm = Hangman(word, lives)
guessesLetters = []
while hm.livesRemaining() > 0 and not hm.guesses():
print(hm)
ch = input('\nEnter a letter: ').upper()
if ch in string.ascii_uppercase:
if ch in guessesLetters:
print('You have already entered the letter {0}\n'.format(ch))
else:
guessesLetters.append(ch)
charCount = hm.updateGameStatus(ch)
if charCount is 0:
print('The letter {0} does not occur in the word!'.format(ch))
else:
print('The letter {0} occurs {1} in the word!'.format(ch,#For how many times it occurs
charToString(charCount)))
if hm.guesses():
print(hm, '\nWell done - you have guessed the word correctly')
else:
print('You have no lives left - you have been hung!')
print('The word was', word)


#Selects a random word.
#User can choose which difficulty they want.
#After the game finishes it asks the user if they want to play again.
def main():
fileName = input('Enter fileName: ')
words = []
try:
f = open(fileName)
words = [removeLineEndings(line.upper()) for line in f.readlines()]#Makes words uppercase
f.close()
except IOError:
print('File does not exist!')
main()
while True:
choice = None
while choice == None:
try:
choice = int(input("""

Please select your difficulty.
[1] Easy - 10 lives
[2] Intermediate - 7 lives
[3] Hard - 5 lives
[4] Impossible - 0 lives

> """wink)
break
except ValueError:
print('\nInvalid input!')

play(random.choice(words),#Picks random word from file
(10, 7, 5, 1)[choice - 1])#10, 7, 5, 1 represent number of lives
again = input('Another game? [Y|N]: ')
if again in ('n', 'N'):
print("\nThanks for playing!"wink
exit(0)
main()
[/CODE]

Comments and criticism welcome.
Re: [SOURCE] Hangman Project by jackaustin631: 5:03pm On Oct 03, 2023
jackaustin631:
I've been programming as a hobby for a few months and wanted to share my first proper game. It's just hangman so nothing fancy and I decided to go with lives instead of adding limbs to the hangman figure, keeps it simpler.

It's python 3.4 so it won't work if your python interpreter is 2.x I've included a list of words for your convience as well. Just make sure to type the location of the words.txt for example C:\Users\Jake\Desktop/words.txt

[CODE]
import string
import random

class Hangman:

#lives: How many lives remaining.

#word: Word to be guess.

#guesses: True or false if the word is either guessed or not.

#HiddenWord: List of guessed letters and the hidden letters are marked with an underscore.

def __init__(self, word, lives):

self._lives = lives
self._hiddenWord = ['_ ' for i in word]
self._word = word
self._guesses = False

def __str__(self):

if self._hiddenWordString() == self._word:
return "Word: {0}".format(self._word)
else:
return "Word: {0}; You have {1} lives left".format(
self._hiddenWordString(), self._lives)

def livesRemaining(self):
return self._lives

#Returns the string representation of list hiddenWord.
def _hiddenWordString(self):
return "".join([ch for ch in self._hiddenWord])


#Checks if the letter exists and updates the underscore to the letter.
def updateGameStatus(self, char):
if char in self._word:colonhash:Char is the letter typed in by the user.
for i in range(len(self._word)):
if self._word == char:
self._hiddenWord = char
else:
self._lives -= 1
if self._word == self._hiddenWordString():
self._guesses = True
return self._word.count(char)


def guesses(self):
return self._guesses


def removeLineEndings(string):
return string.replace('\n' if '\n' in string else '\n', '')


#Counts how many times a letter occurs in a word. Allows for nine of the same letters.
def charToString(num):
return ['once', 'twice', 'three times', 'four times', 'five times',
'six times', 'seven times', 'eight times', 'nine times'][num - 1]


def play(word, lives):
#Main part of the game that deals with user input and output.
hm = Hangman(word, lives)
guessesLetters = []
while hm.livesRemaining() > 0 and not hm.guesses():
print(hm)
ch = input('\nEnter a letter: ').upper()
if ch in string.ascii_uppercase:
if ch in guessesLetters:
print('You have already entered the letter {0}\n'.format(ch))
else:
guessesLetters.append(ch)
charCount = hm.updateGameStatus(ch)
if charCount is 0:
print('The letter {0} does not occur in the word!'.format(ch))
else:
print('The letter {0} occurs {1} in the word!'.format(ch,#For how many times it occurs
charToString(charCount)))
if hm.guesses():
print(hm, '\nWell done - you have guessed the word correctly')
else:
print('You have no lives left - you have been hung!')
print('The word was', word)


#Selects a random word.
#User can choose which difficulty they want.
#After the game finishes it asks the user if they want to play again.
def main():
fileName = input('Enter fileName: ')
words = []
try:
f = open(fileName)
words = [removeLineEndings(line.upper()) for line in f.readlines()]#Makes words uppercase
f.close()
except IOError:
print('File does not exist!')
main()
while True:
choice = None
while choice == None:
try:
choice = int(input("""

Please select your difficulty.
[1] Easy - 10 lives
[2] Intermediate - 7 lives
[3] Hard - 5 lives
[4] Impossible - 0 lives

> """wink)
break
except ValueError:
print('\nInvalid input!')

play(random.choice(words),#Picks random word from file
(10, 7, 5, 1)[choice - 1])#10, 7, 5, 1 represent number of lives
again = input('Another game? [Y|N]: ')
if again in ('n', 'N'):
print("\nThanks for playing!"wink
exit(0)
main()
[/CODE]
for more check this out codingspell
Comments and criticism welcome.
thanks in inadvance for any help

(1) (Reply)

Performance Tester Needed, Not Software Tester / A Programmer Expert In Game Maker Studio Needed Urgently / Let Me Handle Your Data Science Assignment

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 28
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.