Python-게임 통계 계산기

Nov 15 2020

이것은 제가 게임용으로 만든 계산기의 코드입니다. 기본적으로 계산기가하는 일은 다음 통계를 구입하는 비용을 계산하는 것입니다.

그래서 저는 인류와 근력 스탯을위한 코드를 작성했습니다. 내가보기에 각 종족에 대해 각 스탯에 대해 동일한 코드를 3 번 ​​수행해야합니다.

나는 이것과 같은 더 짧은 방법이 있기를 바랐다.

대신 human.strength나는 그것이 race.strength어디에 있기를 원합니다 race = user_race.

감사

class race:
    """The different races in the calculator"""
    def __init__(self, race, strength, agility, health, strength_cost, agility_cost, health_cost):
        self.race = race
        self.strength = strength
        self.agility = agility
        self.health = health
        self.strength_cost = strength_cost
        self.agility_cost = agility_cost
        self.health_cost = health_cost

human = race('Human', 15, 17, 18, 5, 3, 4) 
elf = race('Elf', 11, 21, 14, 4, 3, 5)
giant = race('Giant', 25, 11, 27, 4, 8, 3)

print("Human, Giant, Elf")
user_race = str(input("Enter your race:")).lower()
print("Strength, Agility, Health")
user_stat = str(input("Enter your desired stat:")).lower()
user_present_stat_value = int(input("Enter your present stat value:"))
user_desired_stat_value = int(input("Enter your desired stat value:"))

if user_race == 'human' and user_stat == 'strength':
    human_strength_present_statdif = (user_present_stat_value - human.strength) # difference of present stat with respect of base stat

    human_strength_desired_statdif = (user_desired_stat_value - human.strength) #difference of desired stat with respect of base stat
    
    human_strength_present_stat_cost = (human.strength_cost + (human_strength_present_statdif - 1) * human.strength_cost) #The cost of present stat stat 
    
    human_strength_total_present_cost = ((human_strength_present_statdif / 2) * (human.strength_cost + human_strength_present_stat_cost)) # The total cost from base stat to present stat
    
    human_strength_desired_stat_cost = (human.strength_cost + (human_strength_desired_statdif - 1) * human.strength_cost) #The cost of desired stat
    
    human_strength_total_desired_cost = ((human_strength_desired_statdif / 2) * (human.strength_cost + human_strength_desired_stat_cost)) # The total cost base stat to desired stat
    
    human_strength_net_cost = (human_strength_total_desired_cost - human_strength_total_present_cost) # The Net cost from the difference of Total desired stat and Total present stat
    
    print("Net cost: " + str(human_strength_net_cost))
```

답변

1 RootTwo Nov 16 2020 at 14:56

대화 형 계산기를 만들려는 경우에는 수업 등이 필요하지 않습니다.

먼저 인종에 따른 통계를 조회 할 수있는 간단한 테이블을 만드십시오. 사람 (당신과 같은)이 쉽게 편집하고, 변경하고, 새로운 종족이나 통계를 추가하는 등의 작업을 쉽게하십시오.

keys = "base_strength base_agility base_health strength_cost agility_cost health_cost".split()

traits = [
    #        base     base    base  strength agility health 
    #race  strength agility  health   cost     cost   cost
    "human    15       17      18      5        3      4",
    "elf      11       21      14      4        3      5",
    "giant    25       11      27      4        8      3",
]

문자열 목록 일뿐입니다. 이제 프로그램에서 쉽게 사용할 수있는 형식으로 변환하십시오. 다음과 같은 것을 사용하여 값을 조회 할 수 있도록 딕셔너리의 딕셔너리로 ​​바꿀 것 stat["elf"]["base_agility"]입니다. 코드는 다음과 같습니다.

stats = {}

for row in traits:
    row = row.strip().split()
    stats[row[0]] = dict(zip(keys, map(int, row[1:])))

이제 인간의 힘을 바꾸는 데 드는 비용을 계산하는 코드를 모든 인종이나 통계에 적용되는 일반적인 함수로 바꿀 수 있습니다.

def calc_change_cost(race, stat_name, present_value, desired_value):
    base_value = stats[race][f"base_{stat_name}"]
    stat_cost = stats[race][f"{stat_name}_cost"]

    present_statdif = present_value - base_value
    present_stat_cost = stat_cost + (present_statdif - 1) * stat_cost
    total_present_cost = (present_statdif / 2) * (stat_cost + present_stat_cost)

    desired_statdif = desired_value - base_value
    desired_stat_cost = stat_cost + (desired_statdif - 1) * stat_cost
    total_desired_cost = (desired_statdif / 2) * (stat_cost + desired_stat_cost)

    net_cost = total_desired_cost - total_present_cost

    return net_cost

total_present_cost및 을 계산하기 위해 반복되는 코드를 볼 수 total_desired_cost있습니다. 이러한 라인은 다른 기능으로 리팩토링 될 수 있습니다 (독자를위한 연습).

이제 메인 프로그램은 사용자의 입력을 수집하고 위의 함수를 호출하고 결과를 인쇄합니다.

user_race = str(input("Enter your race (Human, Giant, Elf):")).lower()
user_stat = str(input("Enter your desired stat (Strength, Agility, Health):")).lower()
present_value = int(input("Enter your present stat value:"))
desired_value = int(input("Enter your desired stat value:"))

net_cost = calc_change_cost(user_race, user_stat, present_value, desired_value)
print(f"Net cost to change {user_race} {user_stat} from {present_value} to {desired_value}: {net_cost}")