Make a pygame inventory UI, provide full code
- User
Make a pygame inventory UI, provide full code
- Assistant
Make a pygame inventory UI, provide full code
Sure! Below is a complete Pygame program that creates a simple inventory UI. The inventory is displayed as a grid of slots, and you can click on items to "pick them up" and move them to another slot. This example includes:
Item class representing items that can be placed in the inventory.Inventory class that manages inventory slots and item placement.Here's the complete code:
import pygame
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60
# Colors
WHITE = (255, 255, 255)
GRAY = (50, 50, 50)
LIGHT_GRAY = (170, 170, 170)
BLACK = (0, 0, 0)
# Set up the screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Inventory UI Example")
clock = pygame.time.Clock()
# Inventory settings
INVENTORY_ROWS = 4
INVENTORY_COLS = 6
SLOT_SIZE = 64
SLOT_MARGIN = 5
INVENTORY_LEFT = (SCREEN_WIDTH - (SLOT_SIZE + SLOT_MARGIN) * INVENTORY_COLS) // 2
INVENTORY_TOP = (SCREEN_HEIGHT - (SLOT_SIZE + SLOT_MARGIN) * INVENTORY_ROWS) // 2
# Item images (you can replace these with actual images)
ITEM_COLORS = [
(200, 0, 0), # Red
(0, 200, 0), # Green
(0, 0, 200), # Blue
(200, 200, 0), # Yellow
(200, 0, 200), # Magenta
(0, 200, 200), # Cyan
]
# Define the Item class
class Item:
def __init__(self, name, color):
self.name = name
self.image = pygame.Surface((SLOT_SIZE - 10, SLOT_SIZE - 10))
self.image.fill(color)
self.rect = self.image.get_rect()
self.slot = None # Inventory slot the item is in
def draw(self, surface, pos):
surface.blit(self.image, pos)
# Define the Inventory Slot class
class Slot:
def __init__(self, x, y):
self.rect = pygame.Rect(x, y, SLOT_SIZE, SLOT_SIZE)
self.item = None
def is_empty(self):
return self.item is None
def draw(self, surface):
pygame.draw.rect(surface, LIGHT_GRAY, self.rect)
pygame.draw.rect(surface, GRAY, self.rect, 2)
if self.item:
item_pos = (self.rect.x + 5, self.rect.y + 5)
self.item.draw(surface, item_pos)
# Define the Inventory class
class Inventory:
def __init__(self, rows, cols):
self.slots = []
for row in range(rows):
row_slots = []
for col in range(cols):
x = INVENTORY_LEFT + col * (SLOT_SIZE + SLOT_MARGIN)
y = INVENTORY_TOP + row * (SLOT_SIZE + SLOT_MARGIN)
slot = Slot(x, y)
row_slots.append(slot)
self.slots.append(row_slots)
def draw(self, surface):
for row in self.slots:
for slot in row:
slot.draw(surface)
def get_slot_at_pos(self, pos):
for row in self.slots:
for slot in row:
if slot.rect.collidepoint(pos):
return slot
return None
# Create the inventory and items
inventory = Inventory(INVENTORY_ROWS, INVENTORY_COLS)
# Create some items and place them in the inventory
items = []
for i in range(len(ITEM_COLORS)):
item = Item(f"Item {i+1}", ITEM_COLORS[i])
items.append(item)
# Place items in the first row of the inventory
for i, item in enumerate(items):
row = i // INVENTORY_COLS
col = i % INVENTORY_COLS
slot = inventory.slots[row][col]
slot.item = item
item.slot = slot
# Main loop variables
dragging = False
dragged_item = None
drag_offset = (0, 0)
# Main game loop
while True:
dt = clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # Left click
mouse_pos = pygame.mouse.get_pos()
slot = inventory.get_slot_at_pos(mouse_pos)
if slot and slot.item:
# Start dragging the item
dragging = True
dragged_item = slot.item
drag_offset = (slot.rect.x + 5 - mouse_pos[0], slot.rect.y + 5 - mouse_pos[1])
# Remove the item from the slot
slot.item = None
dragged_item.slot = None
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 1 and dragging:
mouse_pos = pygame.mouse.get_pos()
slot = inventory.get_slot_at_pos(mouse_pos)
if slot and slot.is_empty():
# Place the item in the new slot
slot.item = dragged_item
dragged_item.slot = slot
else:
# Return the item to its original slot
if dragged_item.slot is None:
# Find an empty slot to place the item back
original_slot = inventory.get_slot_at_pos((dragged_item.rect.x, dragged_item.rect.y))
if original_slot:
original_slot.item = dragged_item
dragged_item.slot = original_slot
dragging = False
dragged_item = None
# Clear the screen
screen.fill(WHITE)
# Draw the inventory
inventory.draw(screen)
# Draw the dragged item
if dragging and dragged_item:
mouse_pos = pygame.mouse.get_pos()
item_pos = (mouse_pos[0] + drag_offset[0], mouse_pos[1] + drag_offset[1])
dragged_item.draw(screen, item_pos)
# Update the display
pygame.display.flip()
Initialization: The code initializes Pygame and sets up the main window.
Classes:
Item: Represents an item that can be placed in the inventory. Each item has a name, an image (here represented by a colored rectangle), and a reference to the slot it's currently in.Slot: Represents a single inventory slot. It has a rectangle (rect) representing its position and size, and may hold an Item.Inventory: Manages a 2D grid of Slot objects. It can draw all the slots and find which slot is under the mouse cursor.Item Placement: A few items are created and placed into the inventory slots at the start.
Event Handling:
Drawing:
To run this code:
Make sure you have Python and Pygame installed. You can install Pygame using pip:
pip install pygame
Save the code to a file, for example, inventory_example.py.
Run the script:
python inventory_example.py
Adding Item Images: Replace the colored rectangles with actual images by loading images with pygame.image.load().
Inventory Size: Adjust INVENTORY_ROWS and INVENTORY_COLS to change the size of the inventory grid.
Slot Size: Change SLOT_SIZE to make the inventory slots larger or smaller.
Item Interaction: Extend the event handling to support right-clicking for additional actions (like using or dropping items).
This example provides a basic structure for an inventory UI in Pygame. You can expand upon this foundation to create more complex inventory systems, such as adding item stacking, tooltips, or integrating it into a larger game.
Not yet included in a published release.