• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
EricsonWillians

Selecting a new slot for an item in an inventory.

3 posts in this topic

I'm developing a game with procedurally generated dungeons with a somewhat minecrafty spirit (But 2D), and it's time for the inventory. I've never programmed an inventory before, so I'm figuring out how to do it by my own.

Here's my humble inventory with a humble item at a random position:

 

inventory.jpg

 

 

The first thing that came to my mind when I faced the necessity of creating an inventory, was, naturally: "A list!" (Python). So, here's the code of my Inventory class:
 

class Inventory(ImageEntity):

    def __init__(self,filename):
        ImageEntity.__init__(self,"GFX",filename,0,0)

        self.interface = gIBGI(filename)
        self.cursor = InterfaceSelectionCursor("GFX","selectionCursor.png",0,0)
        self.slots = []
        for i in range(8):
            self.slots.append([])
            for j in range(8):
                self.slots[i].append([0,"No hotkey",(j*interfaceWidth,i*interfaceHeight)])
        ew0InitialPos = (randint(0,7),randint(0,7))
        ew0.x = self.getInterfaceX(ew0InitialPos[0])
        ew0.y = self.getInterfaceY(ew0InitialPos[1])
        self.slots[ew0InitialPos[0]][ew0InitialPos[1]][0] = ew0

        self.slotHolder = 0
        self.itemSelectedByMouse = False
        
    def watchForHotkeyAssignments(self):

        for i in self.slots:
            for slot in i:
                if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_1] or key.get_pressed()[K_KP1])):
                    if slot[2] == (self.cursor.x,self.cursor.y):
                        slot[1] = "Hotkey 1"
                if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_2] or key.get_pressed()[K_KP2])):
                    if slot[2] == (self.cursor.x,self.cursor.y):
                        slot[1] = "Hotkey 2"
                if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_3] or key.get_pressed()[K_KP3])):
                    if slot[2] == (self.cursor.x,self.cursor.y):
                        slot[1] = "Hotkey 3"
                if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_4] or key.get_pressed()[K_KP4])):
                    if slot[2] == (self.cursor.x,self.cursor.y):
                        slot[1] = "Hotkey 4"
                if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_5] or key.get_pressed()[K_KP5])):
                    if slot[2] == (self.cursor.x,self.cursor.y):
                        slot[1] = "Hotkey 5"
                if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_6] or key.get_pressed()[K_KP6])):
                    if slot[2] == (self.cursor.x,self.cursor.y):
                        slot[1] = "Hotkey 6"
                if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_7] or key.get_pressed()[K_KP7])):
                    if slot[2] == (self.cursor.x,self.cursor.y):
                        slot[1] = "Hotkey 7"
                if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_8] or key.get_pressed()[K_KP8])):
                    if slot[2] == (self.cursor.x,self.cursor.y):
                        slot[1] = "Hotkey 8"
                if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_9] or key.get_pressed()[K_KP9])):
                    if slot[2] == (self.cursor.x,self.cursor.y):
                        slot[1] = "Hotkey 9"

    def watchForPositionalMouseRequests(self):

        for i in self.slots:
            for slot in i:
                if mouse.get_pressed()[0]:
                    if slot[2] == (self.cursor.x,self.cursor.y):
                        if slot[0] != 0:
                            pass
                        # At this point it iterates over all the slots (Which are filled with 0 by default.)
                        # If the slot[0] is equal to an item, then, I can access its x and y position (Set it to the cursor pos, for example).
                if mouse.get_pressed()[0] == False:
                    if slot[2] == (self.cursor.x,self.cursor.y):
                        pass # Do something when mouse button 1 released.

    def draw(self):

        screen.blit(self.interface,(0,0))
        self.cursor.draw("INTERFACE")
        self.cursor.move()
        for i in self.slots:
            for slot in i:
                if slot[0] != 0:
                    slot[0].draw("INTERFACE")   

Interface width and height are 128 by 96 (The size of each tile, including the item and cursor (They are transformed for the inventory screen)). As you can see, I figured out how to assign hotkeys for each slot (A vital necessity in the game I'm developing). Nevertheless, I would like to move the item to a new slot when clicked.

How would you do that? I know how to filter the slot (I mean, when I click, I know how to capture the Item, which is an image-object with a x and y position). Things get weird when I try to make the item's x and y positions the position of the selection cursor, considering that I access it only when I filter to the first slot that was clicked (Therefore, if I move the item, I cannot move it again and things get pretty confusing).

Anyway, I would like to know how a more experienced programmer would deal with this problem. I thank you very much!

Edited by EricsonWillians
0

Share this post


Link to post
Share on other sites

Hi,

 

  • What are `interfaceWidth`  and `interfaceHeight`? Are they the width/height of each slot, or of the entire user interface? (If I'm reading right, they're being used as slot width/height. If that's correct, you should consider renaming these variables.)
  • The logic in `watchForHotkeyAssignments` could be simplified a lot. For example, `key.get_pressed()[K_LCTRL]` and `slot[2] == (self.cursor.x,self.cursor.y)` only need to be checked once in side the loop. How could you simplify the logic?
  • I think it's best to separate the _functionality_ as much as possible from the _presentation/UI_. For example, your data structure (the 2d list) `slots` contains information about the screen coordinates/pixels. Can you separate these somehow? Ideally, `slots` would just contain inventory data, and the Inventory class would have methods for performing certain actions (selectItem, moveItem, assignHotkey, etc.). Then you could have a method which will translate mouse cursor coordinates into slot coordinates.

Hope that helps.

0

Share this post


Link to post
Share on other sites

Greetings Thok,

 

I thank you very much for your answer. I've managed to solve the problem. It was really difficult, and probably because of my structure. Nonetheless, I've increassed the code's complexity. Now I'm using hashmaps/dictionaries for the slots (A storage-dictionary whose keys are tuple-positions, whose values are lists with two indexes: One for the item, other for the hotkey). I've commented the code step by step, and I'll post here so that you can see what I've done. As soon as I finish the game, I'll announce it here on Gamedev.

class Inventory(ImageEntity):


    def __init__(self,filename):
        ImageEntity.__init__(self,"GFX",filename,0,0)


        self.interface = gIBGI(filename)
        self.cursor = InterfaceSelectionCursor("GFX","selectionCursor.png",0,0)
        self.storage = GridMap(interfaceGrid) # A GridMap is a dictionary-custom-class with all possible positions within a grid as keys.
        for slot in self.storage: # Iterates through that empty dictionary with all the key-positions with empty values.
            self.storage[slot] = [0,"No hotkey"] # Assigns a default value to them (No item and no hotkey, inside a list).
        # Generate random starting-positions for the starting-item in the inventory.
        ew0InitialPos = (randint(0,7),randint(0,7)) 
        ew0.x = self.getInterfaceX(ew0InitialPos[0])
        ew0.y = self.getInterfaceY(ew0InitialPos[1])
        self.storage[(ew0InitialPos[0],ew0InitialPos[1])][0] = ew0


        self.isItemSelected = False # Necessary to move the item in real time through the slots.
        self.slotHolder = None # Necessary to transfer the item-object from the mouse-down loop to the mouse-up loop.
        self.slotToBeErased = None # Necessary to erase the previous item in order not to allow copies to be accidentally made.


    def watchForPositionalMouseRequests(self): 


        # Iterates over the event list.
        for e in event.get(): 
            # Checks if the mouse button 1 was pressed.
            if e.type == MOUSEBUTTONDOWN and mouse.get_pressed()[0] == True:
                # Checks if no item is already selected.
                if self.isItemSelected == False:
                    # Iterates over the storage dictionary (All the slots,
                    # which are lists with 2 indexes: One for a possible item and other for a possible hotkey).
                    for slot in self.storage: 
                        # Filters the slot specifically under the mouse selection cursor (The one that shall be used).
                        if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                            # Checks whether that slot under the mouse cursor has an item object or not.
                            if isinstance(self.storage[slot][0],Item): # If it has, then it is an instance of the Item class.
                                # If all those conditions are true, then, the item is finally selected.
                                self.isItemSelected = True
                                # Checks if there's no previous item in the slotholder.
                                if self.slotHolder is None:
                                    # Changes the drawing-positions of the item, but does not update them in real time.
                                    self.storage[slot][0].x = self.cursor.x 
                                    self.storage[slot][0].y = self.cursor.y
                                    # Copies the item to the slotholder.
                                    self.slotHolder = self.storage[slot][0]
                                    # Copies the slot that was initially clicked just
                                    # to keep track of it through the loops in order to erase it in the next one.
                                    self.slotToBeErased = slot


            # Checks if the mouse button 1 was released.
            if e.type == MOUSEBUTTONUP and mouse.get_pressed()[0] == False:
                # Guarantees that an item is indeed selected when the mouse button is released.
                if self.isItemSelected == True:
                    # Iterates over the storage dictionary again, separately. 
                    for slot in list(self.storage):
                        # Filters the slot specifically under the mouse selection cursor, again
                        # (But this is the new slot, which is the item's destination.)
                        if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                            # Checks if there is an item in the slotholder from the previous loop.
                            if self.slotHolder is not None:
                                # If all those conditions are true, then, there's really an item selected and
                                # it certainlly is that one that was firstly clicked to be moved.
                                # Then, since the mouse was now released, the item can be "dropped" to its final destination.
                                self.isItemSelected = False
                                self.storage[slot][0] = self.slotHolder
                                self.slotHolder = None
                                if self.slotToBeErased is not None:
                                    if slot != self.slotToBeErased:
                                        self.storage[self.slotToBeErased][0] = 0
                                        self.slotToBeErased = None
                                
    def draw(self):


        screen.blit(self.interface,(0,0))
        self.cursor.draw("INTERFACE")
        self.cursor.move()
        for slot in self.storage:
            try:
                if isinstance(self.storage[slot][0],Item):
                    if self.isItemSelected == True:
                        self.storage[slot][0].x = self.cursor.x
                        self.storage[slot][0].y = self.cursor.y
                    self.storage[slot][0].draw("INTERFACE")
                for n in range(1,10,1):
                    if str(n) in self.storage[slot][1]:
                        gPT([str(n),self.storage[slot][0].x,self.storage[slot][0].y],
                            [str(n),self.storage[slot][0].x,self.storage[slot][0].y],(255,255,255),32)
            except:
                pass
        if self.slotHolder is not None:
            self.slotHolder.draw("INTERFACE")


    def watchForHotkeyAssignments(self):


        for slot in self.storage:
            
            if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_0] or key.get_pressed()[K_KP0])):
                if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                    self.storage[slot][1] = "No hotkey"
            if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_1] or key.get_pressed()[K_KP1])):
                if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                    self.storage[slot][1] = "Hotkey 1"
            if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_2] or key.get_pressed()[K_KP2])):
                if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                    self.storage[slot][1] = "Hotkey 2"
            if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_3] or key.get_pressed()[K_KP3])):
                if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                    self.storage[slot][1] = "Hotkey 3"
            if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_4] or key.get_pressed()[K_KP4])):
                if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                    self.storage[slot][1] = "Hotkey 4"
            if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_5] or key.get_pressed()[K_KP5])):
                if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                    self.storage[slot][1] = "Hotkey 5"
            if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_6] or key.get_pressed()[K_KP6])):
                if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                    self.storage[slot][1] = "Hotkey 6"
            if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_7] or key.get_pressed()[K_KP7])):
                if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                    self.storage[slot][1] = "Hotkey 7"
            if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_8] or key.get_pressed()[K_KP8])):
                if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                    self.storage[slot][1] = "Hotkey 8"
            if (key.get_pressed()[K_LCTRL] and (key.get_pressed()[K_9] or key.get_pressed()[K_KP9])):
                if (self.getInterfaceX(slot[0]),self.getInterfaceY(slot[1])) == (self.cursor.x,self.cursor.y):
                    self.storage[slot][1] = "Hotkey 9"

 

0

Share this post


Link to post
Share on other sites
You probably should seriously reconsider your code design if you need a comment on every line or every few lines explaining what each thing is doing. Even if your code is meant to be a tutorial or something its a little overboard.

The only time you should really have to use comments in code is to explain -intent- of something rather than trying to write out what an actual line of code is doing. It makes a lot more sense to explain that a couple lines of code are a safeguard against potential hacks than it does to write a couple lines of comments explaining that line 27 puts some object into a list for some reason and then line 29 loops through it looking for some character you don't want, or whatever your case may be.

I recently commented on a similar topic to this about inventory in a game, as was stated above the presentation should really be seperate from the data, thats a concept that is very common in game development. Pretty much everything can be split up into: receive input, do logic, present results.
1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0