small-projects/pygame-imgui/example.py
2025-04-08 11:28:40 -05:00

88 lines
2.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import pygame
import sys
import math
from pygui import PyGUI
from pygui_pygame_backend import Render, Rect, get_mouse_pos, get_mouse_pressed, MOUSEBUTTONDOWN, MOUSEBUTTONUP, MOUSEMOTION
import pygui_pygame_backend as backend
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Bouncing Ball with Enhanced PyGUI")
clock = pygame.time.Clock()
# Create the backend renderer and assign the backend to PyGUI.
renderer = Render(screen)
PyGUI.set_backend(backend, renderer)
# ---------------------
# Ball Simulation
# ---------------------
class Ball:
def __init__(self, pos, velocity, radius, color):
self.pos = list(pos)
self.velocity = list(velocity)
self.radius = radius
self.color = color
def update(self):
self.pos[0] += self.velocity[0]
self.pos[1] += self.velocity[1]
if self.pos[0] - self.radius < 0 or self.pos[0] + self.radius > WIDTH:
self.velocity[0] = -self.velocity[0]
if self.pos[1] - self.radius < 0 or self.pos[1] + self.radius > HEIGHT:
self.velocity[1] = -self.velocity[1]
def draw(self, surface):
pygame.draw.circle(surface, self.color, (int(self.pos[0]), int(self.pos[1])), int(self.radius))
ball = Ball((WIDTH // 2, HEIGHT // 2), (4, 3), 30, (255, 100, 50))
ball_speed = 4.0
ball_direction = 0.0
ball_radius = 30.0
ball_color_r = 255.0
ball_color_g = 100.0
ball_color_b = 50.0
bounce_enabled = True
running = True
while running:
dt = clock.tick(60) / 1000.0
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
PyGUI.handle_event(event)
screen.fill((30, 30, 30))
# Draw a draggable, autosizing GUI window.
PyGUI.Begin("Ball Controls", 10, 10)
ball_speed = PyGUI.Slider("Speed", ball_speed, 1, 10)
ball_direction = PyGUI.Slider("Direction", ball_direction, 0, 360)
ball_radius = PyGUI.Slider("Radius", ball_radius, 10, 100)
ball_color_r = PyGUI.Slider("Red", ball_color_r, 0, 255)
ball_color_g = PyGUI.Slider("Green", ball_color_g, 0, 255)
ball_color_b = PyGUI.Slider("Blue", ball_color_b, 0, 255)
bounce_enabled = PyGUI.Checkbox("Bounce", bounce_enabled)
if PyGUI.Button("Reset Position"):
ball.pos = [WIDTH // 2, HEIGHT // 2]
PyGUI.End()
rad = math.radians(ball_direction)
ball.velocity[0] = ball_speed * math.cos(rad)
ball.velocity[1] = ball_speed * math.sin(rad)
ball.radius = ball_radius
ball.color = (int(ball_color_r), int(ball_color_g), int(ball_color_b))
if not bounce_enabled:
ball.velocity[0] *= 0.5
ball.velocity[1] *= 0.5
ball.update()
ball.draw(screen)
pygame.display.flip()
PyGUI.update()
pygame.quit()
sys.exit()