Untitled
Anonymous
plain_text
02/22/2026 7:38 AM
13.5 KB
10
Indexable
import pygame
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
# Game Objects
square_pos = pygame.Rect(WIDTH // 2, HEIGHT // 2, 50, 50)
speed = 5
# Define Button Rects (Bottom Left Corner)
btn_size = 60
up_btn = pygame.Rect(100, HEIGHT - 180, btn_size, btn_size)
down_btn = pygame.Rect(100, HEIGHT - 70, btn_size, btn_size)
left_btn = pygame.Rect(30, HEIGHT - 125, btn_size, btn_size)
right_btn = pygame.Rect(170, HEIGHT - 125, btn_size, btn_size)
clock = pygame.time.Clock()
active_touches = {} # Track multiple fingers
running = True
while running:
# 1. Event Handling (Touch & Mouse)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Track when a finger touches the screen
if event.type == pygame.FINGERDOWN:
# Convert normalized 0.0-1.0 coordinates to pixel coordinates
px = event.x * WIDTH
py = event.y * HEIGHT
active_touches[event.finger_id] = (px, py)
# Update finger position as it moves
elif event.type == pygame.FINGERMOTION:
active_touches[event.finger_id] = (event.x * WIDTH, event.y * HEIGHT)
# Remove tracking when finger is lifted
elif event.type == pygame.FINGERUP:
active_touches.pop(event.finger_id, None)
# 2. Movement Logic
# Check if any active touch is inside our button areas
for finger_pos in active_touches.values():
if up_btn.collidepoint(finger_pos) and square_pos.top > 0:
square_pos.y -= speed
if down_btn.collidepoint(finger_pos) and square_pos.bottom < HEIGHT:
square_pos.y += speed
if left_btn.collidepoint(finger_pos) and square_pos.left > 0:
square_pos.x -= speed
if right_btn.collidepoint(finger_pos) and square_pos.right < WIDTH:
square_pos.x += speed
# 3. Drawing
screen.fill("black")
# Draw Player
pygame.draw.rect(screen, "red", square_pos)
# Draw Touch Controls (Semi-transparent gray)
for btn in [up_btn, down_btn, left_btn, right_btn]:
pygame.draw.rect(screen, (100, 100, 100), btn, 2) # Outline
pygame.display.flip()
clock.tick(60)
pygame.quit()
Editor is loading...
Leave a Comment