2016-08-23 4 views
-1

지금까지 나는 문제의 도형 영역을 추측해야하는 짧은 게임을 만들었습니다. 지금까지 삼각형 만 작동하고 정답은 테스트를위한 B입니다.파이썬에서 점수 저장

사용자의 진행 상황을 텍스트 파일에 저장하여 저장하려하지만 점수를 업데이트하는 함수를 호출하면 점수가 제거되도록 파일을 덮어 씁니다. 어떻게하면이 문제를 해결할 수 있으며, 사용자가 레벨에서 레벨로 이동할 수 있기를 원하기 때문에 다른 방법으로이 작업을 수행 할 수 없으면 어떻게해야합니까?

내 코드 :

User_Points = '0' 

def LoginScreen(): 
    print("Welcome to Area Trainer") 
    print("Please enter the username for your account") 
    global user_name 
    user_name = str(input()) 
    save = open(user_name + '.txt', 'w') 
    save.write(str(User_Points)) 


    PasswordCheck= True 
    while PasswordCheck: 
     user_password = input("Type in your password: ") 
     if len(user_password) < 8: 
      print("Your password must be 8 characters long") 
     elif not any(i.isdigit() for i in user_password): 
      print("You need a number in your password") 
     elif not any(i.isupper() for i in user_password): 
      print("You need a capital letter in your password") 
     elif not any(i.islower() for i in user_password): 
      print("You need a lowercase letter in your password") 
     else: 
      PasswordCheck = False 


def MenuTriangle(): 
    global User_Points 
    User_Points = '' 
    print('''Here is a triangle with a height of 12 cm and a width of 29 cm 
    /\  |    *Not to scale. 
/\ | 
/ \ | 12 cm 
/ \ | 
<-------> 
    29 cm 
    You must find out the area and select the correct answer from these options''') 
    print('''A) 175 
     B) 174 
     C) 2000 
     D) 199 

      ''') 
    user_input = input().upper() 

    if user_input == "A": 
      print("I'm sorry this is incorrect, but you still have a chance to get 1 point!") 
      MenuTriangle2() 

    elif user_input == "C": 
      print("I'm sorry this is incorrect, but you still have a chance to get 1 point!") 
      MenuTriangle2() 

    elif user_input == "D": 
      print("I'm sorry this is incorrect, but you still have a chance to get 1 point!") 
      MenuTriangle2() 

    elif user_input == "B": 
      print("Congratulations! You got it right; someone's a smart cookie. Here have two points!") 
      reading = open(user_name + '.txt') 
      score = reading.read() 
      score = score + '2' 
      print("Your score is", score) 
      save = open(user_name + '.txt', 'a') 
      save.write(str(score)) 
      MenuStart() 

def MenuStart(): 

    print("Welcome to the mathematical area game!") 
    print("In this game you will be required to calculate the area of multiple shapes.") 
    print("To do this you must know how to calculate the area of different shapes with increasing difficulty.") 
    print('''Please select a shape you want to play, 
    A) Triangle 
    B) Square 
    C) Circle''') 
    user_input = input().upper() 

    if user_input == "A": 
     print("You have chosen to calculate the area of a triangle!") 
     MenuTriangle() 

    elif user_input == "B": 
     print("You have chosen to calculate the area of a square!") 
     MenuSquare() 

    elif user_input == "C": 
     print("You have chosen the calculate the area of a circle!") 
     MenuCircle() 

    else: 
     print("Oops! I didn't understand that >:") 
     MenuStart() 


LoginScreen() 
MenuStart() 
+3

전체 게임을 게시 한 이유가 무엇인가요? 우리는 점수가 파일에 쓰여지는 부분 만보기 만하면됩니다. ** ** ** ** 완전한 예제를 게시하십시오. https://stackoverflow.com/help/mcve –

+0

발생하는 문제점에 대해 명확하지 않습니다. 파일을 열어 읽고 읽고 추가하는 것 같습니다. 그런데 파일을 여는 데 도움이되는 'with'문이 있음을 알 수 있습니다 (http://effbot.org/zone/python-with-statement.htm). –

+0

그 대답이 맞는지 ('B'), 인쇄와 함수 호출이 필요한지 확인하지 않으면 코드가 약간 단축 될 것입니다. – depperm

답변

1

파일을 닫습니다 결코 때문에 절약 아닙니다. 이것이 대부분의 사람들이 with open(filename, 'w+')이 모범 사례라고 동의하는 이유입니다.

내가 또한 정수를 추가하는 것이 아니라 함께 문자열을 추가하려고 MenuTriangle()의 끝에서 발견 LoginScreen()

def LoginScreen(): 
    print("Welcome to Area Trainer") 
    print("Please enter the username for your account") 
    global user_name 
    user_name = str(input()) 
    with open(user_name + '.txt', 'w') as f: 
     f.write(str(User_Points)) 

    # Remaining code below here... 

을 위해 아래의 형식을 사용하십시오. 점수를 높이기 전에 파일에서 읽은 문자열을 정수로 변환하고 싶을 것입니다. 또한 필요한 파일을 여는 모드를 제공하지 않습니다. 'r'으로 기본 설정되어 있지만 명시 적으로하는 것이 좋습니다.

def MenuTriangle(): 

    # if: ... 
    # elif: ... 
    # elif: ... 

    elif user_input == "B": 
     print("Congratulations! You got it right, someone's a smart cookie. Here have two points!") 

     with open(user_name + '.txt', 'r') as f: 
      score = f.read() 
      new_score = int(score) + 2 
      print("Your score is {}".format(new_score)) 

     with open(user_name + '.txt', 'w+') as w: # Wouldn't you want to overwrite this rather than continue appending numbers? 
      w.write(str(new_score)) 

     MenuStart() # Call this outside of your with statements so that the file closes 
+0

정말 고마워요! 이것은 완벽하게 작동했습니다! 나는 네가 지금 한 짓을 본다. :디 – BushellsMaster

2

여기

score = reading.read() 
score = score + '2' 

하고 있다는 것을 추가가 type str 그래서 당신이 024 같은 값을 점점 계속하다, 첫째 int에 파일의 값을 변경합니다.

score = int(score) + '2' 

또한 w+ 모드

save = open(user_name + '.txt', 'w+') 

에서 파일을 열거 나 다른 사람에 의해 추천 된 것으로 with를 사용합니다.