import pygame
import sys
# Initialize Pygame
pygame.init()
# Screen settings
WIDTH, HEIGHT = 800, 600
screen =
pygame.display.set_mode((WIDTH,
HEIGHT))
pygame.display.set_caption("Basic
Player Mechanics")
# Colors
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
# Player settings
player_width, player_height = 40, 60
player_x, player_y = WIDTH // 2, HEIGHT
- player_height - 10
player_velocity = 5
player_jump_strength = 10
is_jumping = False
jump_velocity = player_jump_strength
# Other player states
running = False
moving_left = False
moving_right = False
# Main game loop
clock = pygame.time.Clock()
while True:
screen.fill(WHITE)
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type ==
pygame.KEYDOWN:
if event.key ==
pygame.K_LEFT:
moving_left = True
if event.key ==
pygame.K_RIGHT:
moving_right = True
if event.key ==
pygame.K_SPACE and not is_jumping:
is_jumping = True
if event.key ==
pygame.K_LSHIFT:
running = True
if event.type == pygame.KEYUP:
if event.key ==
pygame.K_LEFT:
moving_left = False
if event.key ==
pygame.K_RIGHT:
moving_right = False
if event.key ==
pygame.K_LSHIFT:
running = False
# Player movement
speed = player_velocity * (2 if
running else 1) # Double speed when
running
if moving_left:
player_x -= speed
if moving_right:
player_x += speed
# Jumping mechanics
if is_jumping:
player_y -= jump_velocity #
Move up by jump velocity
jump_velocity -= 1 # Simulate
gravity
if jump_velocity <
-player_jump_strength:
is_jumping = False
jump_velocity =
player_jump_strength # Reset jump
strength
# Prevent player from going
off-screen
player_x = max(0, min(WIDTH -
player_width, player_x))
# Draw player (rectangle)
pygame.draw.rect(screen, BLUE,
(player_x, player_y, player_width,
player_height))
# Update display
pygame.display.flip()
clock.tick(30) # FPS (frames per
second)