Using classes in a python program and incrementing points - python

I need to create a final project for a Beginning Python class and I decided to create a riddle program and want to simplify the following code, but am unsure how to do it. I would like to use a class to do this, but I'm having trouble figuring out how to change my main program to use the information from Class The program runs fine without using Class, but I have to use it for the final project. I am unsure how to do this, I've tried a few things like doing a points system (5 points increment for each win) and thought it would be nice to make the riddles/answers etc. into a class. The problem I'm having is how to code the self instances in the program itself. I know to import the class, but I'm struggling with how/what to change in the program without screwing everything up.. I've looked all over Stack Overflow and a variety of other internet resources, and believe I have a decent understanding of classes, importing and inheritance, but I can't seem to find any examples similar to what I'm trying to do.. Any help is greatly appreciated.
import riddle_class
banner = "~Riddle Me This~"
print(banner)
print('')
print('Instructions: You have 10 chances to answer each of the following 5 riddles.\
You will receive 5 points for each riddle you answer – up to 25 points.')
points = {'win': 0}
riddle_one = 'What\'s round, but not always around. It is light sometimes and is dark sometimes. Everyone wants to walk all over me. What am I?'
riddle_two = 'What has roots as nobody sees, Is taller than trees, Up, up it goes, And yet never grows?'
riddle_three = 'Voiceless it cries, Wingless flutters, Toothless bites, Mouthless mutters. What am I?'
riddle_four = 'Tear one off and scratch my head; what was once red is black instead.'
riddle_five = 'We\'re five little items of an everyday sort; you\'ll find us all in a tennis court'
riddle_one_answer = 'moon'
riddle_two_answer = 'mountain'
riddle_three_answer = 'wind'
riddle_four_answer = 'match'
riddle_five_answer = 'vowels'
hidden_one = '-' * len(riddle_one_answer)
hidden_two = '-' * len(riddle_two_answer)
hidden_three = '-' * len(riddle_three_answer)
hidden_four = '-' * len(riddle_four_answer)
hidden_five = '-' * len(riddle_five_answer)
guess_one = 0
guess_two = 0
guess_three = 0
guess_four = 0
guess_five = 0
points = 0
score = {'win':0}
print('')
#Riddle One
print('~Riddle Number One!~')
print(riddle_one)
print('')
while guess_one < 11:
print(hidden_one)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_one)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_one_answer.count(user_input)
# Replace the appropriate position(s) in hidden_word with the actual character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_one_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_one = hidden_one[:position] + user_input + hidden_one[position+1:] # Rebuild the hidden word string
if not '-' in hidden_one:
print('')
print('Nice Job!', end=' ')
results = 'win'
break
guess_one += 1
else:
print('Loser!', end=' ')
print('The word was %s' % riddle_one_answer,'\.')
print('______________________________________')
print('')
#Riddle Two
print('')
print('~Riddle Number Two!~')
print(riddle_two)
print('')
while guess_two < 11:
print(hidden_two)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_two)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_two_answer.count(user_input)
# Replace the hidden_word with the character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_two_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_two = hidden_two[:position] + user_input + hidden_two[position+1:] # Rebuild the hidden word string
if not '-' in hidden_two:
print('')
print('WINNER!', end=' ')
results = 'win'
break
guess_two += 1
else:
print('Loser!', end=' ')
print('The word was: %s' % riddle_two_answer,'\.')
print('______________________________________')
print('')
#Riddle Three
print('')
print('~Riddle Number Three!~')
print(riddle_three)
print('')
while guess_three < 11:
print(hidden_three)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_three)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_three_answer.count(user_input)
# Replace the appropriate position(s) in hidden_word with the actual character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_three_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_three = hidden_three[:position] + user_input + hidden_three[position+1:] # Rebuild the hidden word string
if not '-' in hidden_three:
print('')
print('WINNER!', end=' ')
results = 'win'
break
guess_three += 1
else:
print('Loser!', end=' ')
print('The word was %s' % riddle_three_answer,'/.')
print('______________________________________')
print('')
#Riddle Four
print('')
print('~Riddle Number Four!~')
print(riddle_four)
print('')
while guess_four < 11:
print(hidden_four)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_four)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_four_answer.count(user_input)
# Replace the appropriate position(s) in hidden_word with the actual character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_four_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_four = hidden_four[:position] + user_input + hidden_four[position+1:] # Rebuild the hidden word string
if not '-' in hidden_four:
print('')
print('WINNER!', end=' ')
results = 'win'
break
guess_four += 1
else:
print('Loser!', end=' ')
print('The word was %s' % riddle_four_answer,'/.')
print('______________________________________')
print('')
#Riddle Five
print('')
print('~Riddle Number Five!~')
print(riddle_five)
print('')
while guess_five < 11:
print(hidden_five)
user_input = input('Enter one letter at a time (guess #%d): ' % guess_five)
if len(user_input) != 1:
continue
# Count the number of times the character occurs in the word
num_occurrences = riddle_five_answer.count(user_input)
# Replace the appropriate position(s) in hidden_word with the actual character.
position = -1
for occurrence in range(num_occurrences):
position = riddle_five_answer.find(user_input, position+1) # Find the position of the next occurrence
hidden_five = hidden_five[:position] + user_input + hidden_five[position+1:] # Rebuild the hidden word string
if not '-' in hidden_five:
print('')
print('WINNER!', end=' ')
results = 'win'
break
guess_five += 1
else:
print('Loser!', end=' ')
print('The word was %s' % riddle_five_answer,'/.')
print('______________________________________')
print('')
if results == 'win':
score['win'] += 1
total_wins = (score['win'])
points += 5 * total_wins
print('Total points: %d' % points) *#This is only recognizing 1 'win'*
Class
class riddle_me:
def __init__(self, turns, guess):
self.turns = 5
guess = 0
score = {'wins': 0}
def __init__(self):
guess_one = 0
guess_two = 0
guess_three = 0
guess_four = 0
guess_five = 0
UPDATE
Thank you all for your help and questions. Even the questions got me thinking more about my project. I still haven't completed the program yet, but I know it could work. I just need to practice more. I've been studying nonstop, but for some reason I'm struggling to learn this language no matter how many tutorials I search.

I'm assuming you understand what a class is, right? So your question really is, "how should I use classes in this program?"
Usually the best way to figure out what classes (and objects) you need in a program is to sit down and write out a description of what your program is trying to do, and then pick out words from that. For example:
This riddle game will ask the user a series of questions, and each time compare the user's guess with the correct answer. When the user guesses correctly, the user's points will increase. If the user does not guess correctly after 10 guesses, we will move to the next question. After all the questions have been asked, the game will display the user's points.
OK, so this is still pretty straightforward. I've highlighted some of the words that occur more than once. Each of these words represents an idea that might be usefully made into a class: the game itself, each question, the user's guess.
Some of these things don't need to be their own objects, but can be properties of other objects. For example, notice how we kept referring to "the user's points". Clearly the points number is an attribute of the user object. And the correct answer to a question should be an attribute of that question.
OK, so now we have some "things" we're going to use in our program, and some idea of what we want to know about each of them:
User:
has points (a number)
Question:
has question text (a string)
has correct answer (a string)
Guess:
has the text of the guess, what the user entered (a string)
is either right or wrong (a boolean)
Game:
has 5 questions
OK, these are starting to look like classes! We can translate these into classes pretty directly:
class User:
def __init__(self):
self.points = 0 # user starts out with zero points
class Question:
def __init__(self, question_text, correct_answer):
self.question_text = question_text
self.correct_answer = correct_answer
class Guess:
def __init__(self, text, is_correct):
self.text = text
self.is_correct = is_correct
class Game:
def __init__(self, questions):
self.questions = questions
Now we have some objects, but we can't do anything useful with them. Now we need to decide what methods to add. There's more than one right way to do this (and a lot of subtle tradeoffs, depending on which things you care more or less about).
Let's start, though, by identifying things we want to be able to do:
ask a Question, that is, print out its question_text
read in a Guess from the user
determine whether a Guess matches a Question's correct_answer text
add points to a User
find the next Question in a Game, or determine when there are no more questions
Each of these things we want to do should be a method! Now you're breaking down your program into smaller and smaller pieces. Keep doing it until it becomes obvious what each piece should do -- and then translate each piece into code. That's it!
Some of these things could potentially live in multiple places. Some things to think about:
Should reading in a Guess from the user be a method on Guess or on User? Either one is OK. Or it could even be a separate function (not a method of a class).
Where should the function that determines whether a Guess is correct or not live? Right now I have it as an attribute of the Guess class, but maybe it should be a method on Guess like is_correct_answer_to(question) that takes the question and returns True or False.
Where should we keep track of the number of guesses so far for a particular question? It could either be on the Question object, or on the User object. Or it could just be a local variable in a function like ask_question(question) which could live either on Question or maybe on Game, or maybe not as a member of a class.
These are the decisions you need to make. But hopefully this will help you get started!

I think there are two possible places to put a class into your code. One is urgently needed, the other not so much (but it could come in handy if you want to add new features to the program).
The obvious place to use a class is to encapsulate all the data and logic related to a single riddle. Each instance of the class would have attributes for the question, the answer, and perhaps other things that would be modified as the player tries to solve the riddle (the masked solution shown to the player and a list of the guesses so far, perhaps).
Something like this:
class Riddle(object):
def __init__(self, question, answer):
self.question = question
self.answer = answer
self.guesses = []
self.update_mask()
def update_mask(self):
self.masked_answer = "".join(c if c in self.guesses else "-"
for c in self.answer)
def guess(self, letter):
# perhaps do some sanity checking here, for invalid or duplicated letters
self.guesses.append(letter)
self.update_mask()
# return number of letters just matched, number yet to be guessed
return self.answer.count(letter), self.masked_answer.count("-")
The other place you might use a class is to encapsulate the game logic (e.g. how many guesses the user gets to make, how they score points) and state (e.g. the player's score and the list of Riddles to ask). This would let you adapt your program in various ways, like letting the player play again after they complete the first run.
However, I don't think that using a class for this is nearly as important as it was for the riddles. Most of the benefits would simply come from gathering the game logic into functions, rather than repeating it over and over. Make an ask_riddle function to handle a single riddle and return the score the player earned and your code will get a whole lot cleaner. If you want to make it a method of the Game class, and update the instance with the score instead, that works too. Python doesn't require you to write object oriented code (though it does make it easy to do so), so you don't need to wedge classes in where they're not needed.

Related

Inconsistent Python outcomes

So I'm having this problem in which my code is inconsistently failing at random times, this has been answered before:(Python 3.7.3 Inconsistent code for song guessing code, stops working at random times now I have had to add a leaderboard to this song guessing game I am doing. I randomly choose a number of which is used to find the artist and song. If right, it will remove the song and artist to prevent dupes and carry on. Here is the code:
loop = 10
attempts = 0
ArtCount = len(artist)
for x in range (ArtCount):
print(ArtCount)
randNum = int(random.randint(0, ArtCount - 1))
randArt = artist[randNum]
ArtInd = artist.index(randArt)# catches element position
songSel = songs[randNum]
print (randNum)
print ("The artist is " + randArt)
time.sleep(0.5)
songie = songSel
print( "The songs first letter be " + songSel[0])
time.sleep(0.5)
print("")
question = input("What song do you believe it to be? ")
if question == (songSel):
songs.remove(songSel)
artist.remove(randArt)
print ("Correct")
print ("Next Question")
if attempts ==0:
points = points + 5
print("+5 Points")
print("")
if question != (songSel):
loop = loop + 1
attempts = attempts + 1
print("")
print("Wrong,", attempts, "questions wrong, careful!")
print("")
time.sleep(0.5)
if attempts == 5:
break
print("GAME OVER")
Pardon my mess, I'm just starting off in making large code, will clean up when finished. I've had the additional problem of having the count controlled loop as 10 (the amount of questions) then having to go pas the loop when you get a question wrong, I've tried having it loop by the amount of songs in the list and I've also tried making a variable that +1 when you get it wrong so you have space to answer but that doesn't work either. After implementing the leaderboard it now doesn't remove any songs (I was messing with the indentation to make the leaderboard print every time.) The error I randomly get is;
randArt = artist[randNum]
IndexError: list index out of range
I'm never sure why this is the code that is the problem, I'm not even sure if it's necessary.
Please, don't use
randNum = int(random.randint(0, ArtCount - 1))
You may easily get a random artist by using:
randArt = random.choice(artist)
The problem is your code had modify the artist array length when you remove item on true answer. You need to get the right artist count after you change.
for x in range (ArtCount):
print(ArtCount)
count = len(artist) # get the new length here
randNum = int(random.randint(0, count - 1)) # use the new length here instead of your old ArtCount

Why does this code produce the error 'int is not subscriptable'?

I have converted the variable to a string, however Python still does not recognise this and says the integer is not subscriptable.
I've already tried viewing other questions with the same 'integer is not subscriptable' problem but none which answer my question specifically.
I have explicity converted the variable to a string the line before the error occurs.
import random
num = random.randint(1000, 9999)
tot_correct = 0
tot_tries = 0
while tot_correct != 4:
tot_correct = 0
tot_tries += 1
guess = input("Guess the number: ")
guess = str(guess)
#check 1st number
if guess[0] == num[0]:
tot_correct += 1
#check 2nd number
if guess[1] == num[1]:
tot_correct += 1
#check 3rd number
if guess[2] == num[2]:
tot_correct += 1
#check 4th number
if guess[3] == num[3]:
tot_correct += 1
print("You got " + tot_correct + " numbers right.")
print("You have guessed the number correctly! It took you " + tot_tries + " tries.")
I expected the string to become a string array, (but it still does not, and returns the same error) and then identify whether or not the individual number matches the one already
Your code isn't doing what you think it is. Right now you are inputting a number, converting it to a string and comparing the first character of that guess string to the first index of the number num[0] which isnt indexable.
edit:
Your code is doing a number of things wrong actually. One huge problem you have is you are setting tot_correct = 0 inside of your while loop which means it'll run forever and never finish.
But stepping back I think you are making this problem too complicated. Let's talk about the pseudocode for what I believe you are trying to do.
num_guessed = 0
number_to_guess = 4
total_guesses = 0
while num_guessed < number_to_guess:
# each pass we reset their guess to 0 and get a new random number
guess = 0
# get a new random number here
while guess != random:
# have a user guess the number here
total_guesses += 1 # we can increment their total guesses here too
# it would be a good idea to tell them if their guess is higher or lower
# when they guess it right it will end the loop
num_guessed += 1
# down here we can tell them game over or whatever you want
The code should at least give you an idea of how to approach the problem without solving it for you.
I respectfully disagree with the previous comment. It will be possible for the loop to end. I understand why you are setting tot_correct to 0 at the start of each loop. Because tot_correct is incremented up to 4 times, it is possible for tot_correct == 4 to be true.
Edit: The poster is trying to count the correct number of digits provided. So if the number to guess is '1234' and the user inputs '1564', the poster wants the code to return '2' to indicate that the '1' and '4' were correct numbers. It's like the game mastermind, where a player has to guess the correct colors and orientation of the colors. However, this code will not inform the user if a correct number is added in an incorrect position, just if the correct number is in the correct position.
However, he is correct that your error lies in your access of num[<index>]. numis an integer so you cannot index into it, hence 'integer is not subscriptable.' num needs to be a string in order to index the characters.
Edit: guess was already a string without the call to str() because the return from input() is a string
Some things to consider: Do you want your user to know they need a 4 digit number? What if there are whitespaces added? Currently your code does not remove whitespace. If you are looking for '6543' as the magic number and I enter ' 6543' your solution would not recognize my answer as correct.

Can't determine why program terminates early

I was working on this assignment for the EdX MIT Python course and decided I wanted the output to display differently. Based on my code, I thought that the task program would end when guesses = 0. However, I'm either getting "IndexError: list assignment index out of range" or the program ends at guess 2. This appears to depend on the length of the secretWord. Can anyone point me in the right direction?
def hangman(secretWord):
'''
secretWord: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secretWord contains.
* Ask the user to supply one guess (i.e. letter) per round.
* The user should receive feedback immediately after each guess
about whether their guess appears in the computers word.
* After each round, you should also display to the user the
partially guessed word so far, as well as letters that the
user has not yet guessed.
Follows the other limitations detailed in the problem write-up.
'''
trackedguess = []
letcount = ()
letterlist = []
guess = ''
for i in range(0, (len(secretWord)-1)):
trackedguess.append('_')
letcount = len(secretWord)
guessesleft = 8
for i in range(0, 7):
if ''.join(trackedguess) == secretWord:
print('You win!')
break
if guessesleft < 1:
print('You have 0 guesses remaining.')
break
print(trackedguess)
print("You have ", guessesleft, " guesses remaining.")
guess = input('Please guess a letter and press return: ')
if guess in letterlist:
print("You've already guessed that. Try again.")
else:
guessesleft -= 1
letterlist.append(guess)
for i in range(0, len(secretWord)):
if secretWord[i] in letterlist:
coordinate = i
trackedguess[coordinate] = secretWord[i]
hangman(chooseWord(wordlist))
A few things stick out to me:
range uses an exclusive end. That means range(0, (len(secretWord)-1) will iterate one time less than the length of secretWord. You want the lengths to match. More straightforward, less error-prone approaches would be just: trackedGuess = ['_'] * len(secretWord) or trackedGuess = list('_' * len(secretWord)).
You should verify your assumptions. For example, the above case could have been caught easily if you did assert(len(trackedGuess) == len(secretWord)).
for i in range(0, 7) suffers from the same problem as your earlier usage of range(). If you want to iterate 8 (guessesleft) times, then you should use range(0, 8). However, you're also decrementing guessesleft inside the loop and exiting when it reaches 0. Do one or the other, but not both. As your code currently is, if someone enters a guess that they've already made, it will count one iteration against them (which I'm not sure is what you want).
It's a very good attempt, but there are some things that are wrong. I'm going to try to walk through them one by one.
Instead of a for loop, I'd suggest using a while guessesleft>0. In the current implementation the for loop will run for 8 times regardless of whether or not there are any guesses left (for example, try providing the same letter as a guess every time). With the while, however, you gain much more control over the loop.
The trackedguess generation is flawed. It will always miss the last letter of the secretword (this is also the reason you were getting the IndexError) Try for i in range(len(secretWord)) instead. You'll also find it much more concise and readable.
I also took the liberty of moving the win or lose condition down in the loop. Previously, if you won on the last guess, you'd still lose (because the win check condition happened before the input and after that the loop ended); also, the guess wasn't printed if you won (because the loop would break before the print statement).
Revised code below:
def hangman(secretWord):
'''
secretWord: string, the secret word to guess.
Starts up an interactive game of Hangman.
* At the start of the game, let the user know how many
letters the secretWord contains.
* Ask the user to supply one guess (i.e. letter) per round.
* The user should receive feedback immediately after each guess
about whether their guess appears in the computers word.
* After each round, you should also display to the user the
partially guessed word so far, as well as letters that the
user has not yet guessed.
Follows the other limitations detailed in the problem write-up.
'''
trackedguess = []
letterlist = []
for i in range(len(secretWord)):
trackedguess.append('_')
guessesleft = 8
while guessesleft > 0:
print(trackedguess)
print("You have ", guessesleft, " guesses remaining.")
guess = input('Please guess a letter and press return: ')
if guess in letterlist:
print("You've already guessed that. Try again.")
else:
guessesleft -= 1
letterlist.append(guess)
for i in range(0, len(secretWord)):
if secretWord[i] in letterlist:
coordinate = i
trackedguess[coordinate] = secretWord[i]
if ''.join(trackedguess) == secretWord:
print(trackedguess)
print('You win!')
break
if guessesleft < 1:
print('You have 0 guesses remaining.')
break
hangman('test')
Hope that helps.

Storing a dictionary generated in the loop and reusing it in a different loop assuming it exists

My task is to produce a word game.
The code is rather simple and is defined as follows( ignore the undefined helper function, which will not appear for the sake of brevity):
def playGame(wordList):
"""
Allow the user to play an arbitrary number of hands.
1) Asks the user to input 'n' or 'r' or 'e'.
* If the user inputs 'n', let the user play a new (random) hand.
* If the user inputs 'r', let the user play the last hand again.
* If the user inputs 'e', exit the game.
* If the user inputs anything else, tell them their input was invalid.
2) When done playing the hand, repeat from step 1
"""
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
n=7
previous_hand={}
hand=dealHand(n)
while choice!= False:
previous_hand=hand.copy()
if choice=='n':
playHand(hand, wordList, n)
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
elif choice=='r':
if len(previous_hand)==0:
print 'You have not played a hand yet. Please play a new hand first!'
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
else:
playHand(previous_hand, wordList,n)
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
elif choice=='e':
break
else:
print 'Invalid command.'
choice=str(raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: '))
Everything seems to be working fine except that 'r' bit. The main trick of this game is that a player can choose to replay a previous hand by inputting 'r'. Say player started a game, played one hand and then want to repeat exactly same hand (all the letters dealt are the same as previously dealt), and the game allows him/her to do so if a player input 'r'.
Something like this:
Enter n to deal a new hand, r to replay the last hand, or e to end game: n
Current Hand: p z u t t t o
Enter word, or a "." to indicate that you are finished: tot
"tot" earned 9 points. Total: 9 points
Current Hand: p z u t
Enter word, or a "." to indicate that you are finished: .
Goodbye! Total score: 9 points.
Enter n to deal a new hand, r to replay the last hand, or e to end game: r
Current Hand: p z u t t t o
Enter word, or a "." to indicate that you are finished: top
"top" earned 15 points. Total: 15 points
However, my code is not working properly on that bit. Everything else is working fine except that. I do not understand how to make a copy of the initial hand, story and then reuse it if player choose 'r'.
This is from a looong time ago but should work for your M.I.T pset:
def playGame(wordList):
hand = None
legalIn = ['r','e','n']
while True:
user = raw_input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ")
if user not in legalIn:
print "Invalid word."
continue
#if user inputs r but there have been no hands played yet
elif user == 'r' and hand is None:
print "You have not played a hand yet. Please play a new hand first!"
elif user == 'n':
hand = dealHand(n)
playHand(hand,wordList,n)
elif user == 'e': # exit game if player inputs e.
break
else:
playHand(hand,wordList, n)
def playHand(hand, wordList, n):
# Keep track of the total score
totalScore = 0
c = calculateHandlen(hand)
# As long as there are still letters left in the hand:
while True:
if c == 0:
print "Run out of letters. Total score: {} points.".format(totalScore)
break
# Game is over if ran out of letters), so tell user the total score
# Display the hand
displayHand(hand)
# Ask user for input
word = raw_input("Enter word, or a '.' to indicate that you are finished: ") # Ask user for input
word = word.lower()
# If the input is a single period:
if word == '.':
# End the game (break out of the loop)
print "Goodbye! Total score: {} points.".format(totalScore)
break
# Otherwise (the input is not a single period):
# If the word is not valid:
elif not isValidWord(word,hand,wordList):
# Reject invalid word (print a message followed by a blank line)
print "Invalid word, please try again."
print
# Otherwise (the word is valid):
else:
hand = updateHand(hand,word)
# Tell the user how many points the word earned, and the updated total score, in one line followed by a blank line
getWordScore(word,n)
totalScore += getWordScore(word,n)
print "{} earned {} points.: {}.".format(word,getWordScore(word,n),totalScore)
# Update the hand
c = calculateHandlen(hand)
Here's how I'd do it. There's only a single variable, hand, which is only modified if we're playing a new hand. If we're replaying the previous hand, we just leave it be (unless it's None, in that case we reject the input):
hand = None
while True:
choice = raw_input('Enter n to deal a new hand, r to replay the last hand, or e to end game: ')
if choice == "n": # deal a new hand
hand = dealHand(n)
elif choice == "r": # reuse the old hand, if there was one
if hand is None:
print 'You have not played a hand yet. Please play a new hand first!'
continue
elif choice == "e": # exit
break
else: # any other input
print 'Invalid command.'
continue
playHand(hand) # actually play here

Checking through a variable to see if it doesn't contains anymore strings

def main():
#word = input("Word to guess for player 2:")
word = ['h','e','l','l','o']
word2 = "hello"
#make a list of _ the same length as the word
display =[]
for i in range (0,len(word)):
display.append("_")
chances = int(input("Number of chances to guess word:"))
if len(word)== 11:
print ("Your word is too long. It has to be 10 charecters or less")
else:
word = word
if chances < len(word):
answer = input("Your word is {0} letters long , are you sure you don't want more chances? Yes or no?". format (len(word)))
if answer == "no":
chances= int(input("Number of chances:"))
else:
chances = chances
("Ok then lets continue with the game")
print ("Player 2, you have {0} chances to guess the word.". format (chances))
won = False
underscore = False
while chances > 0 and won == False and underscore == False:
guess = input("Enter your guess: ")
gC=False
for i in range (0,len(word)):
if guess == word[i]:
gC=True
display[i]=guess
if not gC:
chances = chances - 1
display2 = ""
for i in display:
display2 = display2 + i + " "
For some reason the code doesn't work when I state my while loop as the game continues to go on until the user runs out of guess'. Does anybody have any suggestions as to how I can fix this?
You never set won to True when the user wins the game by guessing all the letters.
This is not an answer to your original question, instead more of a code-review, but maybe you'll find it useful.
word = list('hello') # replaces manual splitting of string into letters
display = [ '_' ] * len(word) # replaces build-up using for-loop
chances = input("Number ... ") # already returns int if the user enters an int
# but will evaluate any valid python expression the
# user enters; this is a security risk as what
# ever is done this way will be done using your
# permissions
chances = int(raw_input("Number ...")) # probably what you wanted
...
else:
word = word # does nothing. remove this line and the "else:" above
chances -= 1 # replaces 'chances = chances - 1' and does the same
display2 = ' '.join(display) # replaces the for-loop to build display2
Furthermore I suggest to use better names. Variables like display2 or gC aren't very helpful in this context. In professional programming you always have to keep in mind that you are writing your code (also or even mainly) for the next developer who has to maintain it. So make it readable and understandable. Choose names like displayString or guessedCorrectly instead.

Categories

Resources