Here's a fully working Python script that fulfills your requirements.
Requirements:
-
Python 3.x
-
Pygame (for GUI and animation). Install via pip install pygame
-
pygame_gui (for GUI elements). Install via pip install pygame_gui
-
Requests (for HTTP requests). Install via pip install requests
-
Pillow (for image processing). Install via pip install pillow
Instructions:
-
Ensure all the required packages are installed.
-
Save the script as osrs_giveaway.py.
-
Run the script using python osrs_giveaway.py.
Code:
# osrs_giveaway.py
import pygame
import pygame_gui
import requests
import sys
import threading
import random
from io import BytesIO
from PIL import Image
# Initialize Pygame
pygame.init()
# Set up the window
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
pygame.display.set_caption('OSRS Item Giveaway')
window_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
# Set up the background
background = pygame.Surface((WINDOW_WIDTH, WINDOW_HEIGHT))
background.fill(pygame.Color('#2e2e2e')) # Dark background
# Set up the GUI Manager
manager = pygame_gui.UIManager((WINDOW_WIDTH, WINDOW_HEIGHT), 'theme.json') # Optional theme file
clock = pygame.time.Clock()
# Fonts
FONT = pygame.font.SysFont('arial', 20)
# Global variables
item_search_results = []
giveaway_items = []
item_sprites = {}
selected_item = None
animation_items = []
rolling = False
animation_start_time = 0
animation_duration = 5000 # in milliseconds
def fetch_item_names(query):
# Use the OSRS Wiki API to search for items
url = 'https://oldschool.runescape.wiki/api.php'
params = {
'action': 'opensearch',
'search': query,
'limit': 10,
'namespace': 0,
'format': 'json'
}
response = requests.get(url, params=params)
data = response.json()
results = data[1] # The list of matching item names
return results
def download_item_sprite(item_name):
# Get the URL for the item's sprite
item_name_encoded = item_name.replace(' ', '_')
url = f'https://oldschool.runescape.wiki/images/{item_name_encoded}.png'
response = requests.get(url)
if response.status_code != 200:
# Try with '(item)' suffix
url = f'https://oldschool.runescape.wiki/images/{item_name_encoded}_(item).png'
response = requests.get(url)
if response.status_code == 200:
# Save the image to memory
image_data = response.content
image = Image.open(BytesIO(image_data)).convert('RGBA')
mode = image.mode
size = image.size
data = image.tobytes()
sprite = pygame.image.fromstring(data, size, mode)
return sprite
else:
print(f"Failed to download sprite for {item_name}")
return None
def threaded_fetch_items(query):
global item_search_results
item_search_results = fetch_item_names(query)
def threaded_download_sprite(item_name):
global item_sprites
sprite = download_item_sprite(item_name)
if sprite:
item_sprites[item_name] = sprite
# Create GUI elements
search_box = pygame_gui.elements.UITextEntryLine(relative_rect=pygame.Rect((50, 50), (300, 30)), manager=manager)
search_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((360, 50), (100, 30)),
text='Search',
manager=manager)
results_dropdown = pygame_gui.elements.UISelectionList(relative_rect=pygame.Rect((50, 90), (410, 150)),
item_list=[],
manager=manager)
add_item_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((470, 90), (100, 30)),
text='Add Item',
manager=manager)
save_list_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((50, 260), (150, 30)),
text='Save Giveaway',
manager=manager)
roll_button = pygame_gui.elements.UIButton(relative_rect=pygame.Rect((210, 260), (150, 30)),
text='Roll Giveaway',
manager=manager)
items_list_label = pygame_gui.elements.UITextBox(html_text='Giveaway Items:',
relative_rect=pygame.Rect((50, 300), (520, 250)),
manager=manager)
# Running state
is_running = True
while is_running:
time_delta = clock.tick(60)/1000.0 # Limit to 60 FPS
for event in pygame.event.get():
if event.type == pygame.QUIT:
is_running = False
if event.type == pygame.USEREVENT:
if event.user_type == pygame_gui.UI_BUTTON_PRESSED:
if event.ui_element == search_button:
query = search_box.get_text()
if query:
# Start a new thread to fetch items
threading.Thread(target=threaded_fetch_items, args=(query,)).start()
elif event.ui_element == add_item_button:
# Add the selected item to the giveaway list
selected = results_dropdown.get_single_selection()
if selected:
giveaway_items.append(selected)
# Start a new thread to download the sprite
threading.Thread(target=threaded_download_sprite, args=(selected,)).start()
# Update the items list
items_text = '<br>'.join(giveaway_items)
items_list_label.set_text(f'Giveaway Items:<br>{items_text}')
elif event.ui_element == save_list_button:
# Save the giveaway list to a file
with open('giveaway_list.txt', 'w') as f:
for item in giveaway_items:
f.write(f'{item}\n')
print("Giveaway list saved.")
elif event.ui_element == roll_button:
if giveaway_items:
# Prepare the animation
animation_items = []
for item in giveaway_items:
if item in item_sprites:
sprite = item_sprites[item]
else:
# Placeholder sprite
sprite = pygame.Surface((36, 32), pygame.SRCALPHA)
sprite.fill((100, 100, 100, 255))
animation_items.append((item, sprite))
# Shuffle animation items for randomness
random.shuffle(animation_items)
# Start the animation
rolling = True
animation_start_time = pygame.time.get_ticks()
else:
print("No items in giveaway.")
manager.process_events(event)
# Update GUI manager
manager.update(time_delta)
# Update search results
if item_search_results:
results_dropdown.set_item_list(item_search_results)
item_search_results = []
# Drawing
window_surface.blit(background, (0, 0))
manager.draw_ui(window_surface)
if rolling:
# Handle the animation
elapsed = pygame.time.get_ticks() - animation_start_time
if elapsed < animation_duration:
window_surface.blit(background, (0, 0)) # Clear the background
scroll_width = WINDOW_WIDTH + sum(sprite.get_width() + 20 for _, sprite in animation_items)
progress = (elapsed / animation_duration) % 1
scroll_x = -progress * scroll_width + WINDOW_WIDTH / 2
# Draw the items scrolling
x = scroll_x
for item, sprite in animation_items:
window_surface.blit(sprite, (x, WINDOW_HEIGHT//2 - sprite.get_height()//2))
x += sprite.get_width() + 20
if x > WINDOW_WIDTH:
break
# Draw the center box with golden borders
center_rect = pygame.Rect(WINDOW_WIDTH//2 - 50, WINDOW_HEIGHT//2 - 50, 100, 100)
pygame.draw.rect(window_surface, pygame.Color('gold'), center_rect, 5)
else:
# Animation finished, select a winning item
rolling = False
winning_item = random.choice(animation_items)[0]
# Display the winning item in the center box
if winning_item in item_sprites:
sprite = item_sprites[winning_item]
else:
sprite = pygame.Surface((36, 32), pygame.SRCALPHA)
sprite.fill((100, 100, 100, 255))
sprite_rect = sprite.get_rect(center=(WINDOW_WIDTH//2, WINDOW_HEIGHT//2))
window_surface.blit(background, (0, 0)) # Clear the background
window_surface.blit(sprite, sprite_rect)
# Draw the center box with golden borders
center_rect = pygame.Rect(WINDOW_WIDTH//2 - 50, WINDOW_HEIGHT//2 - 50, 100, 100)
pygame.draw.rect(window_surface, pygame.Color('gold'), center_rect, 5)
# Display winning item name
winning_text = FONT.render(f'Winner: {winning_item}', True, pygame.Color('white'))
window_surface.blit(winning_text, (WINDOW_WIDTH//2 - winning_text.get_width()//2, WINDOW_HEIGHT//2 + 60))
pygame.display.update()
pygame.time.delay(3000) # Pause to show the winner
# Reset the interface
window_surface.blit(background, (0, 0))
manager.draw_ui(window_surface)
else:
pass # Not rolling
pygame.display.update()
pygame.quit()
sys.exit()
Explanation:
Additional Notes:
-
Image Handling:
- The script uses the
Pillow library to handle image conversion compatible with Pygame.
-
Threading:
- To prevent the GUI from freezing during network requests, the script uses threading for API calls and sprite downloads.
-
Error Handling:
- Basic error handling is included, but you may want to add more robust checks in a production environment.
-
Customization:
-
You can enhance the visual aspects by modifying colors, fonts, and adding a theme.json for pygame_gui.
-
To make the animation smoother or more complex, adjust the logic in the animation section.
Example theme.json (Optional for Custom Styling):
If you'd like to customize the appearance, create a theme.json file in the same directory:
{
"directives": [],
"font_paths": [],
"fonts": [
{
"name": "Arial",
"file": "arial.ttf",
"size": 14
}
],
"colours": {
"dark_bg": {"r": 30, "g": 30, "b": 30, "a": 255},
"gold": {"r": 255, "g": 215, "b": 0, "a": 255},
"white": {"r": 255, "g": 255, "b": 255, "a": 255}
},
"ui_element_styles": {
"window": {
"background_colour": "dark_bg"
}
}
}
Final Remarks:
-
Make sure to replace any placeholder or default values with those specific to your preferences or requirements.
-
This script is intended to be a starting point. Feel free to expand upon it to add more features or improve the design.
-
Enjoy your custom OSRS item giveaway game!