How to restart a simple coin tossing game

前端 未结 4 1579
面向向阳花
面向向阳花 2021-01-16 16:43

I am using python 2.6.6

I am simply trying to restart the program based on user input from the very beginning. thanks

import random
import time
print         


        
相关标签:
4条回答
  • 2021-01-16 17:30

    I recommend:

    1. Factoring your code into functions; it makes it a lot more readable
    2. Using helpful variable names
    3. Not consuming your constants (after the first time through your code, how do you know how many guesses to start with?)

    .

    import random
    import time
    
    GUESSES = 5
    
    def playGame():
        remaining = GUESSES
        correct = 0
    
        while remaining>0:
            hiddenValue = random.choice(('heads','tails'))
            person = raw_input('Heads or Tails?').lower()
    
            if person in ('q','quit','e','exit','bye'):
                print('Quitter!')
                break
            elif hiddenValue=='heads' and person in ('h','head','heads'):
                print('Correct!')
                correct += 1
            elif hiddenValue=='tails' and person in ('t','tail','tails'):
                print('Correct!')
                correct += 1
            else:
                print('Nope, sorry...')
                remaining -= 1
    
        print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
    
    def main():
        print("You may press q to quit at any time")
        print("You have {0} chances".format(GUESSES))
    
        while True:
            playGame()
            again = raw_input('Play again? (Y/n)').lower()
            if again in ('n','no','q','quit','e','exit','bye'):
                break
    
    0 讨论(0)
  • 2021-01-16 17:30

    You need to use random.seed to initialize the random number generator. If you call it with the same value each time, the values from random.choice will repeat themselves.

    0 讨论(0)
  • 2021-01-16 17:38

    After you enter 'y', guess == 0 will never be True.

    0 讨论(0)
  • 2021-01-16 17:39

    Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.

    Not based on your question, but how to use continue:

    while True: 
            choice = raw_input('What do you want? ')
            if choice == 'restart':
                    continue
            else:
                    break
    
    print 'Break!' 
    

    Also:

    choice = 'restart';
    
    while choice == 'restart': 
            choice = raw_input('What do you want? ')
    
    print 'Break!' 
    

    Output :

    What do you want? restart
    What do you want? break
    Break!
    
    0 讨论(0)
提交回复
热议问题