Code
Code
import sys
import random
# Initialize Pygame
pygame.init()
# Screen settings
SCREEN_WIDTH = 400
SCREEN_HEIGHT = 600
FPS = 60
# Colors
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 200, 0)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
SKY_BLUE = (135, 206, 235)
SUN_YELLOW = (255, 255, 0)
CLOUD_WHITE = (255, 255, 255)
# Ball settings
BALL_RADIUS = 20
BALL_COLOR = RED
BALL_SPEED_X = 5
GRAVITY = 0.5
JUMP_VELOCITY = 12
# Platform settings
PLATFORM_WIDTH = 80
PLATFORM_HEIGHT = 10
PLATFORM_COLOR = GREEN
PLATFORM_COUNT = 6
PLATFORM_GAP_MIN = 80 # Reduced gap for closer platforms
PLATFORM_GAP_MAX = 120 # Adjusted to make platforms more reachable
# Initialize screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Doodle Jump with Restart")
clock = pygame.time.Clock()
# Ball class
class Ball:
def __init__(self, start_y):
self.x = SCREEN_WIDTH // 2
self.y = start_y
self.velocity_y = 0
self.score = 0
self.reached_platforms = set() # Track platforms that have been reached
def jump(self):
self.velocity_y = -JUMP_VELOCITY
# Platform class
class Platform:
def __init__(self, x, y, id):
self.rect = pygame.Rect(x, y, PLATFORM_WIDTH, PLATFORM_HEIGHT)
self.id = id # Unique identifier for each platform
# Initial reset
ball, platforms, bottom_platform_visible = reset_game()
# Game loop
running = True
game_over = False
while running:
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if game_over and event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
game_over = False
ball, platforms, bottom_platform_visible = reset_game()
if not game_over:
# Ball movement
keys_pressed = pygame.key.get_pressed()
ball.move(keys_pressed)
ball.apply_gravity()
# Ball-platform collision
if ball.velocity_y > 0: # Ball is falling
for platform in platforms:
if platform.rect.collidepoint(ball.x, ball.y + BALL_RADIUS):
# Only increase score once per platform
if platform.id not in ball.reached_platforms:
ball.jump()
ball.score += 1 # Increment score for each platform
reached
ball.reached_platforms.add(platform.id) # Mark
platform as reached
# Bottom platform
if bottom_platform_visible and ball.y + BALL_RADIUS >=
SCREEN_HEIGHT - PLATFORM_HEIGHT:
ball.jump()
# Drawing
draw_background() # Draw the background (sun, clouds, and sky)
if bottom_platform_visible:
pygame.draw.rect(screen, BLUE, (0, SCREEN_HEIGHT - PLATFORM_HEIGHT,
SCREEN_WIDTH, PLATFORM_HEIGHT))
# Update display
pygame.display.flip()
clock.tick(FPS)
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()