Jack the Christian Ответов: 4

Как добавить систему точек в цикл, которая продолжает отслеживать точки после перезапуска цикла?


I made a number guessing with a loop that restarts. But when the loop restarts the score system gets reset to 0 as I have set a variable to track score and on loop it is first set to 0 then using `score=score+1` I can track score but when it loops it just becomes 0 then gets set to 1?



I've tried taking the score out of the loop but it comes back with a `local variable 'score' referenced before assignment`.


<pre>
from random import *                                                

                                                                    
yesList = ("yes", "yeah", "sure", "definitely", "y", "ye", "yeah")  
                                                                   

def win():                                             
        print("Correct")                                            
        print("You have won", Pname + "!")                         
        print("I've added 1 point to your score!") 
        score = int("0")
        score= score+1                                                
        print("You've scored", score, "points!")
        restart()                                                   




Pname = input("What is your name? ")                                
print("Hello", Pname, "let's play a game.")                       


def restart():                                                     
  restart=input("Do you want to play again? ").lower()             
  if restart in yesList:                                            
    main()                                                         
  else:
    print("Game Over")
    print("You scored", score, "points!")
    exit()
    
def main():                                                       
  
  rnum = randint(1, 100)                                            
  
  num1 = int(input("Guess a number between 1 and 100: "))        
  if num1 == rnum:
        win()
      
  elif num1>rnum: 
        print("Too High")

  else: 
        print("Too Low")

      
      
  num2 = int(input("Guess again: "))
  if  num2==rnum:
          win()
      
  elif num2>rnum: 
        print("Too High")
      
  else: 
        print("Too Low")

  num3 = int(input("Guess again: "))
  if  num3==rnum:
        win()

  elif num3>rnum: 
        print("Too High")
      
  else: print("Too Low")

  num4 = int(input("Guess again: "))
  if  num4==rnum:
          win()
      
  elif num4>rnum: 
        print("Too High")
      
  else: 
        print("Too Low")
      
  num5 = int(input("Guess again: "))
  if  num5==rnum:
          win()
      
  elif num5>rnum: 
        print("Too High")
      
  else: 
        print("Too Low")
  
  
  num6 = int(input("Guess again: "))
  if  num6==rnum:
          win()
      
  elif num6>rnum: 
        print("Too High")
      
  else: 
        print("Too Low")
  
  
  num7 = int(input("Guess again: "))
  if  num7==rnum:
          win()
      
  elif num7>rnum: 
        print("Too High")
      
  else: 
        print("Too Low")
  str(print("The answer is", rnum))
  
  restart()
  
score=0
main()


Что я уже пробовал:

Traceback (most recent call last):
  File "program.py", line 115, in <module>
    main()
  File "program.py", line 40, in main
    win()
  File "program.py", line 14, in win
    score= score+1                                             
UnboundLocalError: local variable 'score' referenced before assignment

This is the error message that comes when you take the score out of the loop.

4 Ответов

Рейтинг:
1

Thomas Daniels

В дополнение к решению Ричарда:

Это происходит потому, что Python думает score это локальная переменная, но это не так. Чтобы заставить ваш текущий код работать, вам нужно сказать Python, что score является глобальной переменной. Добавьте эту строку в качестве первой строки вашего win функция:

global score

И тогда вы можете взять score = int("0") из вашего метода выигрыша.


Рейтинг:
0

Richard MacCutchan

Вы должны создать класс таким образом, чтобы переменная score была доступна всем его методам. Кроме того, вы можете передать переменную score в качестве параметра каждому из существующих методов. Видеть 4. Дополнительные инструменты потока управления : определение функций[^].


Рейтинг:
0

Patrice T

Цитата:
Как добавить систему точек в цикл, которая продолжает отслеживать точки после перезапуска цикла?

Как было замечено в предыдущих решениях:
score = int("0") # this is enough to prevent the score from working
score= score+1

Но у вас есть еще одна проблема:
Вы зацикливаетесь без использования какого-либо оператора цикла, это означает, что вы зацикливаетесь бесконечно вызывая подпрограммы, и это плохой стиль программирования.
Хорошо, это работает на этой игрушечной программе, но ее следует избегать любой ценой в любой серьезной программе.
Вам нужно узнать, что такое петли и как их использовать.
Питон Петли Учебное Пособие | Python Для Петли | Цикл While В Python | Питон Обучения | Edureka - Ютуб[^]
Python 3 учебник по программированию - для цикла - YouTube[^]


Рейтинг:
0

Jack the Christian

Вот код, который вы можете использовать вместо этого:

#Random number and date/time is imported
import random
from datetime import datetime

currenttime = str(datetime.now())
currenttime = (
currenttime[0:19]) #Ensures that only the first 19 digits of the date and time is displayed
YES_LIST =("yes", "sure", "yeah", "ye", "yea", "y", "fine", "okay", "ok", "yep")
score = 0 #To add a point system score must equal to 0 at the start of the game
GuessesTaken2 = 0 #GuessesTaken2 calculates the total guesses out of all the games played by player so this information can be exported into the text file 

Name = input("What is your name? ") #game asks for player's name
print("Hello {}, Let's play a number guessing game. I am thinking of a number between 1 and 100.".format(Name))

#game begins
def main(): 
    
    hidden = random.randint(1,100) #random number between 1 and 100 is generated
    GuessesTaken = 0 # used to calcualte the guesses taken each game
    while GuessesTaken < 6: #loop that automatically breaks after 6 guesses

        guess = int(input("Guess which number I am thinking of: "))
        GuessesTaken = GuessesTaken + 1;
        global GuessesTaken2 #assigning GuessesTaken2 as a global function will allow the game to use it outside the loop
        GuessesTaken2 = GuessesTaken2 + 1;
        GuessesLeft = 6 - GuessesTaken; #algorithm to figure out how many guesses are left
    
        if guess > hidden and GuessesLeft==0: #when there are no guesses left and the guessed number is higher than the actual number, the loop is automatically broken
            print("Your guess is too high, you are unfortunately out of guesses!")
            print("The number I was thinking of was actually {}".format(hidden))
            restart()
        
        if guess > hidden and GuessesLeft > 0: #If the guess is too high but there are still guesses left, the game allows you to guess again
            print("Your guess is too high, you have {} guess/es left".format(GuessesLeft))
        
        if guess < hidden and GuessesLeft==0: #when there are no guesses left and the guessed number is lower than the actual number, the loop is automatically broken
            print("Your guess is too low and you are unfortunately out of guesses!")
            print("The number I was thinking of was actually {}".format(hidden))
            restart()
        
        if guess < hidden and GuessesLeft > 0: #If the guess is too low but there are still guesses left, the game allows you to guess again
            print("Your guess is too low, you have {} guess/es left".format(GuessesLeft))
        
        if guess==hidden: #When the number is guessed correctly, the player gains points
            global score #assigining score as a global function will allow the game to use it outside the loop
            score = score + 5 #score increases by  5 each time you guess the number correctly
            print("Hit!")
            print("Congratulations {} !".format(Name))
            print("It took you {} guesses to correctly guess the number correctly.".format(GuessesTaken))
            print("Your points go up by 5! You are currently on {} points.".format(score))
            restart()

def restart(): #allows the player to play again if he/she wishes
    restart=input("Would you like to play again?").lower()
    if restart in YES_LIST: # only occurs if the player's response is with the YES_LIST that was made earlier
        main() #the game restarts
    else: #
        if score==0:
            print("GAME OVER!", "Horrific, You didn't even manage to get a point.") 
        elif score>1:
            print("GAME OVER!", "Good Job, You've managed to get {} points".format(score))
      
    text_file = open(Name + " game details.txt", "w") #opens up a text file with all the game details if the player does not choose to playa again
    text_file.write("Player Name: {} \nTime and date: {} \nNumber of Guesses: {} (altogether out of all the games you played) \nScore: {}".format(Name, str(currenttime), str(GuessesTaken2), str(score)))
    text_file.close()
    exit() #exits the game if player does not choose to play again

main() #allows the game to run