Using pygame use rectangles to draw a human, then apply physics to him, provide full code
- User
Using pygame use rectangles to draw a human, then apply physics to him, provide full code
- Assistant
Using pygame use rectangles to draw a human, then apply physics to him, provide full code
Certainly! Below is a complete Pygame program that draws a simple human figure using rectangles and applies basic physics to it, such as gravity and collision with the ground. The human figure is composed of multiple rectangles representing different body parts: head, torso, arms, and legs. The physics will make the figure fall under gravity and stop when it hits the ground.
Human class is defined to manage the figure's properties and behaviors.import pygame
import sys
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
GROUND_LEVEL = HEIGHT - 100 # Y-coordinate for the ground
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
SKY_BLUE = (135, 206, 235)
GREEN = (34, 139, 34)
# Set up the display
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Human with Physics in Pygame")
# Clock to control frame rate
clock = pygame.time.Clock()
FPS = 60
# Physics constants
GRAVITY = 0.5 # Acceleration per frame
class Human:
def __init__(self, x, y):
# Position (x, y) refers to the top-center of the torso
self.x = x
self.y = y
self.vx = 0 # Horizontal velocity
self.vy = 0 # Vertical velocity
# Dimensions
self.torso_width = 40
self.torso_height = 80
self.head_size = 30
self.arm_width = 10
self.arm_height = 60
self.leg_width = 12
self.leg_height = 70
# Calculate initial rectangles positions relative to (self.x, self.y)
self.update_rects()
def update_rects(self):
"""Update the rectangles based on current position."""
# Torso
self.torso_rect = pygame.Rect(
self.x - self.torso_width // 2,
self.y,
self.torso_width,
self.torso_height
)
# Head
self.head_rect = pygame.Rect(
self.x - self.head_size // 2,
self.y - self.head_size - 10, # 10 pixels above the torso
self.head_size,
self.head_size
)
# Left Arm
self.left_arm_rect = pygame.Rect(
self.x - self.torso_width // 2 - self.arm_width,
self.y + 10, # Slight offset from top of torso
self.arm_width,
self.arm_height
)
# Right Arm
self.right_arm_rect = pygame.Rect(
self.x + self.torso_width // 2,
self.y + 10,
self.arm_width,
self.arm_height
)
# Left Leg
self.left_leg_rect = pygame.Rect(
self.x - self.leg_width - 5, # 5 pixels gap from torso
self.y + self.torso_height,
self.leg_width,
self.leg_height
)
# Right Leg
self.right_leg_rect = pygame.Rect(
self.x + 5, # 5 pixels gap from torso
self.y + self.torso_height,
self.leg_width,
self.leg_height
)
def apply_gravity(self):
"""Apply gravity to vertical velocity."""
self.vy += GRAVITY
def move(self):
"""Update position based on velocity."""
self.x += self.vx
self.y += self.vy
def collide_ground(self):
"""Handle collision with the ground."""
# Find the lowest part of the human (legs)
lowest_y = self.y + self.torso_height + self.leg_height
if lowest_y >= GROUND_LEVEL:
# Adjust position so that legs sit on the ground
overlap = lowest_y - GROUND_LEVEL
self.y -= overlap
self.vy = 0 # Stop vertical movement
def update(self):
"""Update human state."""
self.apply_gravity()
self.move()
self.update_rects()
self.collide_ground()
def draw(self, surface):
"""Draw the human on the given surface."""
# Draw head
pygame.draw.rect(surface, BLACK, self.head_rect)
# Draw torso
pygame.draw.rect(surface, BLACK, self.torso_rect)
# Draw arms
pygame.draw.rect(surface, BLACK, self.left_arm_rect)
pygame.draw.rect(surface, BLACK, self.right_arm_rect)
# Draw legs
pygame.draw.rect(surface, BLACK, self.left_leg_rect)
pygame.draw.rect(surface, BLACK, self.right_leg_rect)
def draw_ground(surface):
"""Draw the ground."""
ground_rect = pygame.Rect(0, GROUND_LEVEL, WIDTH, HEIGHT - GROUND_LEVEL)
pygame.draw.rect(surface, GREEN, ground_rect)
def main():
# Create a human instance at the top-center of the screen
human = Human(WIDTH // 2, 50)
running = True
while running:
clock.tick(FPS) # Maintain frame rate
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update human physics
human.update()
# Drawing
screen.fill(SKY_BLUE) # Clear screen with sky blue
draw_ground(screen) # Draw the ground
human.draw(screen) # Draw the human
pygame.display.flip() # Update the display
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Imports and Initialization:
pygame and sys).Color Definitions:
Physics Constants:
GRAVITY which affects the vertical velocity of the human each frame.Human Class:
Human class encapsulates all properties and behaviors of the human figure.__init__):
update_rects to calculate the initial positions of all rectangles.update_rects Method:
apply_gravity Method:
vy) by the gravity constant.move Method:
collide_ground Method:
update Method:
draw Method:
Ground Drawing:
draw_ground function draws a green rectangle representing the ground.Main Function:
Human positioned near the top-center of the screen.pip install pygame
human_physics.py.python human_physics.py
Adding Movement:
vx accordingly.Enhancing Physics:
Improving Graphics:
Feel free to modify and enhance the code to suit your specific needs or to experiment with more advanced physics and graphics!
Not yet included in a published release.
Execution:
main function is called if the script is run directly.