Inventory-система для Text-RPG - глобальная ошибка - PullRequest
0 голосов
/ 23 сентября 2018

РПГ-инвентарь не работает хорошо.Извините, если мой код слишком плох, я только начал изучать Python.

Python 3.7.0

IDLE 3.6.(64-разрядная версия)

Sublime Text 3.1.1. (3176)

#firstly I created classes for items and items_in_body_parts.
#for example, one of them:
class item_for_put_on:
    def __init__(self):
    self.name = ''
    self.body_part = '' #for what body part? like in Diablo, for example, you can take a weapon in your hand and put on a helmet on your head
#there is a lot of other staff, i deleted it to make it simple, here are the main things:
right_hand_item_1 = right_hand_item() 
on_head_item_1 = on_head_item() 
item_for_put_on_1 = item_for_put_on() 
item_check_on = item_check_on_class() 
right_hand_item_1.name = ''
right_hand_item_1.body_part = ''
on_head_item_1.name = ''
on_head_item_1.body_part = ''
item_for_put_on_1.name = ''
item_check_on.name = ''
i_stick = ['Stick', 'in_hands']
i_helmet = ['Helmet', 'on_head']
all_item_names = {'Stick' : i_stick, 'Helmet' : i_helmet}

def item_put_on():
    global item_for_put_on_1, right_hand_item_1, on_head_item_1
    if item_for_put_on_1.body_part == 'on_head' and on_head_item_1.name == '':
        on_head_item_1.name = item_for_put_on_1.name
        #go back to function inventory_menu
    if item_for_put_on_1.body_part == 'in_hands'and right_hand_item_1.name == '':
        right_hand_item_1.name = item_for_put_on_1.name
        #go back to function inventory_menu

#def inventory_menu(): --- this and a lot of other functions i don't decribe you, it's not necessary

def inventory_bag():
    #we come here from inventory menu to see what we have in the bag
    #global item_check_on, item_for_put_on_1 ---- should be globals here?
    #here was some code - to describe to player all content of the bag - it works good
    #NOW PLAYER DECIDES WHAT ITEM TO CHOOSE TO READ INFO ABOUT IT AND AFTER THAT HE CAN PUT IT ON HIS HERO
    #command4 - it is the list of items.names in bag - it works good; player should type full name or to choose item's number
    com4 = input ("> ")
    while com4 not in commands4 and com4.lower() != 'back':
        print ("Unknown command, try again.\n")
        com4 = input ("> ")
    if com4 in commands4: 
        ppp = com4
        for i in all_item_names: #i - str!!!
            if ppp == all_item_names[i][0]: 
                item_check_on.name = all_item_names[i][0]
                item_check_on.body_part = all_item_names[i][1]
                # remember ---- i_stick = ['Stick', 'in_hands']
                # remember ---- i_helmet = ['Helmet', 'on_head']
                # remember ---- all_item_names = {'Stick' : i_stick, 'Helmet' : i_helmet}
                print("You are looking to the item " + item_check_on.name) #this is just info to display for player
                print("item body part: " + item_check_on.body_part) #this is just info to display for player
                ppp = ''
                com4=''
                print ("Would you like to 'equip'('eq') it or 'back'?\n")
                com5 = input ("> ")
                commands5 = ['back', 'equip', 'eq']
                while com5.lower() not in commands5:
                    print ("Unknown command, try again.\n")
                    com5 = input ("> ") 
                if com5.lower() == 'back':
                    inventory_bag()
                    break
                elif com5.lower() in ['equip', 'eq']:
                    item_for_put_on_1.name = all_item_names[i][0]
                    item_for_put_on_1.body_part = all_item_names[i][1]
                    item_put_on()
                    break
                break
            else: 
                print('test looping') #loop while going to this again and again, searching for the correct name of item in dictionary all_item_names
                if ppp == '' and action4 == '':
                    break
    elif action4.lower() == 'back':
        #inventory_menu()

def inventory_eq():
    #we come here from inventory menu to see what is equipped on our hero
    #global right_hand_item_1, on_head_item_1 ---- should be globals here?
    print("right arm - " + str(right_hand_item_1.name) + "\n")
    print("head - " + str(on_head_item_1.name) + "\n")
    #SO HERE WE CAN SEE WRONG INFO --- if you put on only one thing, everything is right, but if you put on the second thing - there will be two sticks (one on head, one in hand) or two helmets (one on head, one in hand)

ТАК, ЧТО МЫ МОЖЕМ УВИДЕТЬ НЕПРАВИЛЬНУЮ ИНФОРМАЦИЮ: если вы надеваете только одну вещь, все правильно, ноесли вы наденете вторую вещь - там будет две палки (одна на голове, одна в руках) или два шлема (одна на голове, одна в руках);из-за проблем с названиями предметов.И если я добавлю для них больше предметов и слотов для тела, и последним будет, например, Щит - на теле героя будет много щитов вместо правильных предметов.И, конечно, в инвентаре нет предыдущих предметов.

На мой взгляд, проблема в том, что где-то с глобальными переменными или, может быть, где-то цикл не работает хорошо (может быть, назначая каждую секунду навсегда, я не знаю).

Кажется, чтокогда мы меняем item_for_put_on_1, он меняет все, что ему было присвоено - on_head_item_1 и right_hand_item_1 в функции item_put_on ().

И если я использую функцию очистки для item_for_put_on_1 (чтобы сделать его = '') в item_put_on () после itemбыл оснащен - он каким-то образом удаляет имена предметов из оборудования

Так что основная проблема связана с item_for_put_on_1, но мне нужна помощь, чтобы найти способ исправить это.

1 Ответ

0 голосов
/ 24 сентября 2018

Я решил проблему, удалив объекты и имена объектов.Теперь я использую простые переменные - я сделал их глобальными везде.

Теперь это работает!Но я не понимаю, в чем была проблема, даже если мы заменим глупое ненужное "item_for_put_on_1" на прямое имя из словаря "all_item_names [i] [0]".Проблема не была решена с этим методом.Приведенный ниже код все еще не работал (та же проблема с изменением имен)

# item_left_hand, item_on_head - these are objects, they got .name firstly

# below code is in item_put_on(): #I also saved global i from inventory_bag() for that
if all_item_names[i][1] == 'in hands':
    item_left_hand.name = all_item_names[i][0]
elif all_item_names[i][1] == 'on head':
    item_on_head.name = all_item_names[i][0]

Но обычные глобальные переменные (не объекты) работают очень хорошо:

global item_left_hand, item_on_head #in all functions

# below code is in item_put_on(): #I also saved global i from inventory_bag() for that
if all_item_names[i][1] == 'in hands':
    item_left_hand = all_item_names[i][0]
elif all_item_names[i][1] == 'on head':
    item_on_head = all_item_names[i][0]
...