Przyporządkowywanie zmiennej nadrzędnej do zmiennej podrzędnej

0

Nie wiem do końca jak temat nazwać. Generalnie mój problem jest taki. Piszę gierkę tekstową dla zabawy:
W skrócie wygląda to tak.
Na początku mamy input powitalny z 3 możliwymi opcjami:
a, b, c.
Po wybraniu b pokazuje się 5 opcji
po wybraniu dowolnej liczba opcji się zmniejsza. Nie mniej finalną opcja jest opcja wyjściowa.
Czyli w pierwszym kroku wybieramy b, potem a, znowu a aż w końcu wybranie a automatycznie jest równe opcji c z pierwszego wyboru.

if beginning == "a":
    marketX = input("Welcome on the market of Xarthas, what you plan to do? \n [a] Go to horse merchant,\n "
                    "[b] Go to armor merchant,\n[c]Go to wine merchant,\n [d]Go to weapon merchant "
                    "\n[e] Go to wheat merchant \n[f] Try to sell your goods")
    if marketX == "a":
        print("Greetings, are you looking for new steed?")
    elif marketX == "b":
        print("Greetings, I see that you are not warrior, please let me show you my best crafts")
    elif marketX == "c":
        print("Here, take a look at the finest wines in Xarthas")
    elif marketX == "d":
        print("Welcome in the finest armory of this city")
    elif marketX == "e":
        print("Welcome in Jacobsen & Sons")
    elif marketX == "f":
        print("You set up your stool and wait for buyer of your stuff")
elif beginning == "b":
    tavernX = input("Welcome in Hanging Bear. You can: \n [a] buy a beer for 5 talars. \n "
                    "[b] buy food for you for 15 talars .\n "
                    "[c] rent a room for 1 gulden. \n [d] buy food for your horses for 2 guldens. \n [e] leave tavern.")

    if tavernX == "a":
        totalMoney = totalMoney - beerPriceX
        tavernXa = input("You feel happier, yet your pocket is lighter. You have " + str(totalMoney) + " total"
                         " Do you wish to do anything else? You can:\n [a] buy food for you for 15 talars. \n "
                         "[b] rent a room for 1 gulden. \n [c] buy food for your horses for 2 guldens. \n "
                         "[d] leave tavern.")
        if tavernXa == "a":
            totalMoney = totalMoney - foodPriceX
            tavernXaA = input(" You feel healthier, but your money bag contains only " + str(totalMoney) + " now. "
                              "You can either:\n [a]rent a room for 1 gulden. \n "
                              "[b] buy food for your horses for 2 guldens."
                              "\n [c] leave tavern. ")
            if tavernXaA == "a":
                totalMoney = totalMoney - rentPriceX
                tavernXaAa = input("Yaawn, that was good night Now you posses only a mere " + str(totalMoney) + ""
                                   " guldens. You can: \n [a] feed your horses for 2 guldens.\n [b] leave the tavern.")
                if tavernXaAa == "a":
                    totalMoney = totalMoney - horseFoodX
                    tavernXaAaA = input("Now you have " + str(totalMoney) + " guldens and your horses are well feed. "
                                        "Having none activities here, you decided to leave tavern. Now you can :\n"
                                        "[a] go to market \n[b] leave the city")
                    if tavernXaAaA == "a":
                        tavernXaAaA = marketX
                    else:
                        tavernXaAaA = outskirtsX

           elif beginning == "c":
    outskirtsX = input("You are at outskirts of the city")
       

Jak najszybciej/najprościej zrobić by zmienna lokalna tavernXaAaA zwracała input ze zmiennej outskirtsX? Co robię źle?

0

Najpierw robisz override zmiennej tavernXaAaA przypisując do niej to, co siedzi w outskirtsX, a potem do outskirtsX wrzucasz coś nowego - czyli input użytkownika. Trochę tak, jakbyś w C napisał:

int a = 10;
int b = 20;
b = a;
a = 30;
printf("%d", b);

I oczekiwał, że zobaczysz 30 :)

0

Musisz mieć jakiś ogólny handler, który 'skanuje' obecny status i wykonuje przypisane akcje. Mozesz zaimplementować to za pomocą pętli while. Jest to nie jako state machine (wygooglaj koncepcję). Np.:

while True:
    if beginning == "a":
        marketX = input("Welcome on the market of Xarthas, what you plan to do? \n [a] Go to horse merchant,\n "
                        "[b] Go to armor merchant,\n[c]Go to wine merchant,\n [d]Go to weapon merchant "
                        "\n[e] Go to wheat merchant \n[f] Try to sell your goods")
        if marketX == "a":
            print("Greetings, are you looking for new steed?")
        elif marketX == "b":
            print("Greetings, I see that you are not warrior, please let me show you my best crafts")
        elif marketX == "c":
            print("Here, take a look at the finest wines in Xarthas")
        elif marketX == "d":
            print("Welcome in the finest armory of this city")
        elif marketX == "e":
            print("Welcome in Jacobsen & Sons")
        elif marketX == "f":
            print("You set up your stool and wait for buyer of your stuff")
    elif beginning == "b":
        tavernX = input("Welcome in Hanging Bear. You can: \n [a] buy a beer for 5 talars. \n "
                        "[b] buy food for you for 15 talars .\n "
                        "[c] rent a room for 1 gulden. \n [d] buy food for your horses for 2 guldens. \n [e] leave tavern.")

        if tavernX == "a":
            totalMoney = totalMoney - beerPriceX
            tavernXa = input("You feel happier, yet your pocket is lighter. You have " + str(totalMoney) + " total"
                             " Do you wish to do anything else? You can:\n [a] buy food for you for 15 talars. \n "
                             "[b] rent a room for 1 gulden. \n [c] buy food for your horses for 2 guldens. \n "
                             "[d] leave tavern.")
            if tavernXa == "a":
                totalMoney = totalMoney - foodPriceX
                tavernXaA = input(" You feel healthier, but your money bag contains only " + str(totalMoney) + " now. "
                                  "You can either:\n [a]rent a room for 1 gulden. \n "
                                  "[b] buy food for your horses for 2 guldens."
                                  "\n [c] leave tavern. ")
                if tavernXaA == "a":
                    totalMoney = totalMoney - rentPriceX
                    tavernXaAa = input("Yaawn, that was good night Now you posses only a mere " + str(totalMoney) + ""
                                       " guldens. You can: \n [a] feed your horses for 2 guldens.\n [b] leave the tavern.")
                    if tavernXaAa == "a":
                        totalMoney = totalMoney - horseFoodX
                        beginning = input("Now you have " + str(totalMoney) + " guldens and your horses are well feed. "
                                            "Having none activities here, you decided to leave tavern. Now you can :\n"
                                            "[a] go to market \n[b] leave the city")
                        
    elif beginning == "c":
        outskirtsX = input("You are at outskirts of the city")
0

Zrobiłem to tak:

beerPriceX = float(0.05)
foodPriceX = float(0.15)
rentPriceX = float(1.00)
horseFoodX = float(2.00)
print("Hello")
name = input("Please, insert your name ")
beginning = input("Hello " + name + ", after long time spent on foreign university, your uncle sent "
                  "you a letter with horrible news"
                  "\ndue to recent disease your father and mother deceased. What is worse, after their death, "
                  "your home was caught by fire \nAll what remained is pair of old horses, "
                  "old cart  and 50 feet of linen cloth for sale and 40 guldens and 30 talars."
                  "\nFinally you reclaimed what you possess. What will you do?"
                  " You are next to your old home and you feel saddened. "
                  "You can:\n[a] Go to market,\n[b] Go to tavern, "
                  "\n[c]Leave the city.""Choose your option by choosing letters ")
while beginning:

    if beginning == "a":
        marketX = input("Welcome on the market of Xarthas, what you plan to do? \n [a] Go to horse merchant,\n"
                        "[b] Go to armor merchant,\n[c]Go to wine merchant,\n [d]Go to weapon merchant "
                        "\n[e] Go to wheat merchant \n[f] Try to sell your goods")
        if marketX == "a":
            print("Greetings, are you looking for new steed?")
        elif marketX == "b":
            print("Greetings, I see that you are not warrior, please let me show you my best crafts")
        elif marketX == "c":
            print("Here, take a look at the finest wines in Xarthas")
        elif marketX == "d":
            print("Welcome in the finest armory of this city")
        elif marketX == "e":
            print("Welcome in Jacobsen & Sons")
        elif marketX == "f":
            print("You set up your stool and wait for buyer of your stuff")
    elif beginning == "b":
        tavernX = input("Welcome in Hanging Bear. You can: \n [a] buy a beer for 5 talars. \n "
                        "[b] buy food for you for 15 talars .\n "
                        "[c] rent a room for 1 gulden. \n [d] buy food for your horses for 2 guldens. \n "
                        "[e] leave tavern.")

        if tavernX == "a":
            totalMoney = totalMoney - beerPriceX
            tavernXa = input("You feel happier, yet your pocket is lighter. You have " + str(totalMoney) + " total"
                             " Do you wish to do anything else? You can:\n [a] buy food for you for 15 talars. \n "
                             "[b] rent a room for 1 gulden. \n [c] buy food for your horses for 2 guldens. \n "
                             "[d] leave tavern.")
            if tavernXa == "a":
                totalMoney = totalMoney - foodPriceX
                tavernXaA = input(" You feel healthier, but your money bag contains only " + str(totalMoney) + " now. "
                                  "You can either:\n [a]rent a room for 1 gulden. \n "
                                  "[b] buy food for your horses for 2 guldens."
                                  "\n [c] leave tavern. ")
                if tavernXaA == "a":
                    totalMoney = totalMoney - rentPriceX
                    tavernXaAa = input("Yaawn, that was good night Now you posses only a mere " + str(totalMoney) + ""
                                       " guldens. You can: \n [a] feed your horses for 2 guldens.\n [b] leave the "
                                       "tavern.")
                    if tavernXaAa == "a":
                        totalMoney = totalMoney - horseFoodX
                        tavernXaAaA = input("Now you have " + str(totalMoney) + " guldens and your horses "
                                            "are well feed."
                                            "Having none activities here, you decided to leave tavern. Now you can :\n"
                                            "[a] go to market \n[b] leave the city")
                        if tavernXaAaA == "a":
                            tavernXaAaA = (beginning == "a")
                        else:
                            tavernXaAaA = (beginning == "c")
            elif tavernXa == "b":
                totalMoney = totalMoney - rentPriceX
                tavernXaA = input("Yaawn, that was good night Now you posses only a mere " + str(totalMoney) +
                                  " guldens. Now you can:"
                                  "\n [a] buy food for your horses for 2 guldens \n [b] leave the tavern")
            elif tavernXa == "c":
                totalMoney = totalMoney - horseFoodX
                print("Now you have only " + str(totalMoney) + " guldens, but at least your horses are well feed")
            else:
                print("You left tavern, What do you plan to do?")

        if tavernX == "b":
            totalMoney = totalMoney - foodPriceX
            print("Your stomach is full and you are ready for upcoming events. You have " + str(totalMoney) + " left")
        elif tavernX == "c":
            totalMoney = totalMoney - rentPriceX
            print("You got some rest. But your pocket contains now " + str(totalMoney) + " coins")
        elif tavernX == "d":
            totalMoney = totalMoney - horseFoodX
            print("Your horses are well feed now and healthier. You have now " + str(totalMoney))
    elif beginning == "c":
        outskirtsX = input("You are at outskirts of the city")
    else:
        beginning = input("Choose your option by choosing letters ")


Niby wraca mi na początek ale jedynie na początek "tavernX"
Chciałbym by wracało do wyboru nadrzędnego

0

Możesz zacząć refaktoring od drobnych zmian. Np. przenieść tfragmenty kodu do funkcji. Stworzę też bardzo prostą klasę State która będzie przechowywać obecne miejsce i stan $:

Przykład:

class State:
    def __init__(self):
        # look into decimal class for better money related numbers calcs
        self.money = float(40.30)
        self.place = None
        self.inventory = {
        'old horse': 2,
        'old cart': 1,
        'linen cloth': 50
        }

state = State
beerPriceX = float(0.05)
foodPriceX = float(0.15)
rentPriceX = float(1.00)
horseFoodX = float(2.00)
print("Hello")
name = input("Please, insert your name ")
state.place = input("Hello " + name + ", after long time spent on foreign university, your uncle sent "
                  "you a letter with horrible news"
                  "\ndue to recent disease your father and mother deceased. What is worse, after their death, "
                  "your home was caught by fire \nAll what remained is pair of old horses, "
                  "old cart  and 50 feet of linen cloth for sale and 40 guldens and 30 talars."
                  "\nFinally you reclaimed what you possess. What will you do?"
                  " You are next to your old home and you feel saddened. "
                  "You can:\n[a] Go to market,\n[b] Go to tavern, "
                  "\n[c]Leave the city.""Choose your option by choosing letters ")

def market(state):
    marketX = input("Welcome on the market of Xarthas, what you plan to do? \n [a] Go to horse merchant,\n"
                    "[b] Go to armor merchant,\n[c]Go to wine merchant,\n [d]Go to weapon merchant "
                    "\n[e] Go to wheat merchant \n[f] Try to sell your goods")
    if marketX == "a":
        print("Greetings, are you looking for new steed?")
    elif marketX == "b":
        print("Greetings, I see that you are not warrior, please let me show you my best crafts")
    elif marketX == "c":
        print("Here, take a look at the finest wines in Xarthas")
    elif marketX == "d":
        print("Welcome in the finest armory of this city")
    elif marketX == "e":
        print("Welcome in Jacobsen & Sons")
    elif marketX == "f":
        print("You set up your stool and wait for buyer of your stuff")
   return state

def buy_food(price, state):
    state.money -= price
    print("Your stomach is full and you are ready for upcoming events. You have " + str(state.money) + " left")
    return state
    
def buy_beer(price, state):
    state.money -= price
    print("You feel happier, yet your pocket is lighter. You have " + str(state.money) + " total")
    return state
    
def rent_room(price, state):
    state.money -= price
    print("Yaawn, that was good night Now you posses only a mere " + str(state.money) + " guldens")
                       
def buy_horse_food(price, state):
    state.money -= price
    print("Now you have " + str(state.money) + " guldens and your horses are well feed.")
     
def tavern(state)
    tavernX=''
    while tavernX!='e':
        tavernX = input("Welcome in Hanging Bear. You can: \n [a] buy a beer for 5 talars. \n "
                        "[b] buy food for you for 15 talars .\n "
                        "[c] rent a room for 1 gulden. \n [d] buy food for your horses for 2 guldens. \n "
                        "[e] leave tavern.")
        if tavernX=='a':
            state = buy_beer(beerPriceX, state)
        elif tavernX=='b':
            state = buy_food(beerPriceX, state)
        elif tavernX=='c':
            state = rent_room(beerPriceX, state)
        elif tavernX=='d'
            state = buy_horse_food(beerPriceX, state)

while state:
    if state.place == "a":
        state = market(state)
    elif state.place == "b":
        state = tavern(state)
    elif state.place == "c":
        print("You are at outskirts of the city")
    else:
        state.place = input("Choose your option by choosing letters ")

Nie testowałem tego kodu po prostu napisałem w poście więc mogą być literówki lub drobne błędy.

1

W sumie to w ogóle jeśli fabuła tej gry jest taka "drzewiasta", to może logicznie byłoby machnąć sobie w kodzie jakieś drzewo/graf lokacji / zdarzeń powiązanych na zasadzie przyczyna (akcja) -> skutek (nowy stan/lokacja/konwersacja/whatever) z nowymi opcjami czy coś zamiast jakichś turbo-ifo-pętli :P Może łatwiej byłoby Ci żonglować stanami w czymś takim :)

1

Powiedzmy że machniesz sobie taki building block - w dużym uproszczeniu:

class Node:
  def __init__(self, description=None):
    self.description = description or 'Unknown location'
    self._visited = False
    self._children = {}
  
  def add_child(self, child, key):
    if key in self._children .keys():
      raise KeyError('Key "{}" is already taken'.format(key))
    self._children [key] = child
  
  def get_child(self, key):
    return self._children.get(str)
  
  @property
  def options(self):
    return list(self._children.keys())
  
  def visit(self):
    self._visited = True

No i cyk, masz coś w stylu drzewka które możesz poskładać do kupy. Od biedy dałbyś radę chodzić po tym i/lub poskładać to w jakiś graf:

>>> question = Node('The Drunken Merchant tells you a really bad joke. How do you respond?')
>>> a = Node('"Hahaha" - you try to sound as believably as possible. The Drunken Merchant is so drunk he wouldn\'t notice, but better safe than sorry. You get your bargain.')
>>> b = Node('"He.. he..." - you force yourself to laugh. The Drunken Merchant is too drunk to notice and gives you a bargain.')
>>> c = Node('"That wasn\'t funny at all!" - you fuss at the merchant. "Get lost, loser!" - the Drunken Merchant responded and stumbled away.')
>>> question.add_child(a, 'A) Laugh')
>>> question.add_child(b, 'B) Laugh half-heartedly')
>>> question.add_child(c, 'C) Tell the merchant his joke was bad')
>>> question.options
['A) Laugh', 'B) Laugh half-heartedly', 'C) Tell the merchant his joke was bad']
>>>

Choć być może lepiej byłoby ich nie składać do kupy w jedną wielką strukturę, tylko trzymać te węzły osobno i w każdym tylko np. identyfikatory dzieci, albo w ogóle zrobić osobną macierz połączeń między takimi elementami fabuły, a stan gry trzymać obok, albo dorzucić do węzła info kto jest rodzicem... no możliwości masz od kopa.

1 użytkowników online, w tym zalogowanych: 0, gości: 1