2012-04-21 5 views
-1

4 가지 다른 특성에 30 포인트를 할당하여 문자 프로필을 만드는 간단한 프로그래밍 연습을 마친다. 프로그램 기능은 현재 프로필 표시, 새 프로필 만들기 또는 기존 프로필 변경입니다. 첫 번째와 두 번째 기능은 정상적으로 작동하지만 마지막에는 문제가 있습니다. 프로그램은 중첩 목록 항목 (속성 + 할당 된 점수)을 풀고 새 점수를 요청하며 이전 항목과 새 항목의 차이를 가져 와서 번호를 변경합니다. 그에 따라 풀의 사용 가능한 포인트를 계산합니다. 마지막으로 위치 0에있는 목록 (속성 + 새로 할당 된 점수)에 새 항목을 추가 한 다음 위치 1의 항목을 삭제합니다.이 항목은이 속성에 대한 이전 항목이어야합니다. 루프를 통해 목록을 완성합니다. 그러나 일단 코드를 실행하면 작동하지 않을 것입니다. 전체 코드 아래를 참조하십시오.Python 중첩 목록 - 개별 항목 바꾸기 및 바꾸기

options = ["Strength", "Health", "Wisdom", "Dexterity"] 
profile = [] 
points = 30 

choice = None 
while choice != "0": 

    print(
     """ 
    CHARACTER CREATOR PROGRAM 

    0 - Exit 
    1 - See current profile 
    2 - Build new profile 
    3 - Amend existing profile 

    """ 
     ) 

    choice = input("Please choose an option: ") 
    print() 

    if choice == "0": 
     print("Good bye.") 
    elif choice == "1": 
     for item in profile: 
      print(item) 
     input("\nPress the enter key to continue.") 
    elif choice == "2": 
     print("You can now equip your character with attributes for your adventures.") 
     print("You have",points,"points to spent.") 
     print("Now configure your character: \n") 
     #Run the point allocation loop 
     for item in options: 
      point_aloc = int(input("Please enter points for " + str(item) + ":")) 
      if point_aloc <= points: 
       entry = item, point_aloc 
       profile.append(entry) 
       points = points - point_aloc 
       print("\nYour current choice looks like this: ") 
       print(profile) 
       input("\nPress the enter key to continue.") 
      else: 
       print("Sorry, you can only allocate", points," more points!") 
       print("\nYour current choice looks like this: ") 
       print(profile) 
       input("\nPress the enter key to continue.") 
     print("\nWell done, you have configured your character as follows: ") 
     for item in profile: 
      print(item) 
     input("Press the enter key to continue.") 
    elif choice == "3": 
     print("This is your current character profile:\n") 
     for item in profile: 
      print(item) 
     print("\nYou can change the point allocation for each attribute.") 
     for item in profile: 
      point_new = int(input("Please enter new points for " + str(item) + ":")) 
      attribute, points_aloc = item 
      diff = points_aloc - point_new 
      if diff >0: 
       points += diff 
       print("Your point allocation has changed by", -diff,"points.") 
       print(diff,"points have just been added to the pool.") 
       print("The pool now contains", points,"points.") 
       entry = item, point_new 
       profile.insert(0, entry) 
       del profile[1] 
       input("Press the enter key to continue.\n") 
      elif diff <0 and points - diff >=0: 
       points += diff 
       print("Your point allocation has changed by", -diff,"points.") 
       print(-diff,"points have just been taken from the pool.") 
       print("The pool now contains", points,"points.") 
       entry = item, point_new 
       profile.insert(0, entry) 
       del profile[1] 
       input("Press the enter key to continue.\n") 
      elif diff <0 and points - diff <=0: 
       print("Sorry, but you don't have enough points in the pool!") 
       input("Press the enter key to continue.\n") 
    else: 
     print("Sorry, but this is not a valid choice!") 
     input("Press the enter key to continue.\n") 

input("\n\nPress the enter key to exit.") 

참고 : 변경 사항을 적용하려면 먼저 프로필을 만들어야합니다.

미리 도움을 청하십시오!

+5

오신 것을 환영합니다 스택 오버플로.질문을 명확히 해 주시겠습니까? 여기에는 [짧고, 독립적 인, 올바른 예] (http://sscce.org/)가 포함되어야합니다. (오류 메시지 포함!) 및 [시도한 내용] (http://mattgemmell.com/2008/12/08/what-have-you-tried/)에 대한 설명이 포함되어 있습니다. 문제를 해결할 수 있습니다. – Ben

+4

또한 예상되는 출력 및 출력을 포함해야합니다. –

답변

0

질문에 대한 의견에서 알 수 있듯이 질문을하는 것이 최선의 방법이 아닙니다. 그러나, 나는 그것이 잘못된 것을 본다. 현재 코드를 수정하는 방법을 보여줄 수는 있지만 진실은 이 가장 수정 방법은 완전히 다시 작성하는 것입니다. 그렇게 할 때 다음 전략을 채택해야합니다.

  1. 코드를 부분으로 분리하십시오. 이 경우 몇 가지 다른 기능을 만들 것을 권장합니다. 하나는 main_loop이라고 할 수 있으며 메뉴를 순환하는 논리를 포함합니다. 프로필을 업데이트하거나 표시하는 코드는 포함되어 있지 않습니다. 대신 다른 함수 (display_profile, build_profileamend_profile)를 호출합니다. 이러한 함수는 options, profilepoints과 같은 변수를 허용하고 optionspoints과 같은 값을 반환합니다. 이렇게하면 코드가 크게 단순 해지고 테스트와 디버그가 훨씬 쉬워집니다.

    def main_loop(): 
        options = ["Strength", "Health", "Wisdom", "Dexterity"] 
        profile = [] 
        points = 30 
    
        choice = None 
        while choice != "0": 
         print(menu_string) #define menu_string elsewhere 
         choice = input("Please choose an option: ") 
         print() 
    
         if choice == "0": 
          print("Good bye.") 
         elif choice == "1": 
          display_profile(profile) 
         elif choice == "2": 
          profile, points = build_profile(options, profile, points) 
         elif choice == "3": 
          profile, points = amend_profile(profile, points) 
         else: 
          print("Sorry, but this is not a valid choice!") 
          input("Press the enter key to continue.\n") 
    
        input("\n\nPress the enter key to exit.") 
    

    이 얼마나 훨씬 좋네요 참조 : 여기 main_loop의 모양에 대한 예제이다? 이제 다른 기능을 정의하면됩니다. 다음과 같은 것입니다 ...

    이 접근법의 또 다른 장점은 이제 전체 프로그램을 실행하지 않고 이러한 기능을 개별적으로 테스트 할 수 있다는 것입니다.

  2. 목록 수정에 올바른 관용구를 사용하십시오. 목록을 반복하면서 수정하는 것은 특별한주의가 필요하며 경우에 따라 (이미 반복 된 항목을 제거하거나 추가하여 목록의 길이를 변경하는 경우) 전혀 작동하지 않습니다. profile으로 시도하려는 것을 할 수있는 방법이 있지만 시작 프로그래머에게는 훨씬 더 간단하게 추천합니다. 그냥 새 목록을 만드십시오! 그런 다음 그 목록을 반환하십시오. 그래서 amend_profile 기능에, 같은 것을 할 :

    def amend_profile(profile, points): 
         # other code ... 
         new_profile = [] 
         for item in profile: 
          attribute, points_aloc = item 
          # other code ... 
          new_proflie.append(entry) 
         # other code ... 
    
         return new_profile, points 
    

    참고 또한 주요 버그 중 하나 인 곳이라고; (attribute, point_new) 대신에 이 포함 된 entry을 생성하므로 새 튜플의 내부에 item 튜플이있는 대신 attribute 문자열이 예상대로 생성됩니다.

+0

도움 주셔서 대단히 감사합니다 !! 그리고 다른 모든 의견을 주셔서 감사합니다. 이것은 나의 첫번째 지점이었다 여기에서. 앞으로 보드에 조언을 취할 것입니다 :-) – Matthias