Using pygame generate endless mountain and ball with physics, allow user change amount…
- User
Using pygame generate endless mountain and ball with physics, allow user change amount of curves on mountain, provide full code
- Assistant
Using pygame generate endless mountain and ball with physics, allow user change amount of curves on mountain, provide full code
Sure! Below is a complete Pygame program that generates an endless mountain with adjustable curvature and a ball that interacts with the mountain using basic physics. Users can increase or decrease the number of curves on the mountain using the up and down arrow keys.
Mountain Generation: The mountain is generated using a list of points that form a continuous terrain. As the game progresses, new points are added to the right, and old points are removed from the left to create an endless scrolling effect. The "number of curves" parameter controls the roughness or frequency of the terrain's undulations.
Ball Physics: The ball moves under the influence of gravity and can roll along the mountain. Collision detection ensures that the ball stays on the terrain, responding to changes in slope.
User Controls: The user can press the up arrow key to increase the number of curves (making the mountain more jagged) or the down arrow key to decrease the number of curves (smoother terrain).
Before running the code, ensure you have Pygame installed. If not, you can install it using:
pip install pygame
Now, here's the full code:
import pygame
import sys
import random
import math
# Initialize Pygame
pygame.init()
# Screen dimensions
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Endless Mountain with Ball Physics")
# Clock for controlling frame rate
clock = pygame.time.Clock()
FPS = 60
# Colors
WHITE = (255, 255, 255)
GREEN = (34, 139, 34)
BLUE = (70, 130, 180)
BLACK = (0, 0, 0)
RED = (220, 20, 60)
# Physics constants
GRAVITY = 0.5
FRICTION = 0.02
BALL_RADIUS = 15
# Mountain settings
INITIAL_CURVES = 10 # Initial number of curves on the mountain
MIN_CURVES = 2
MAX_CURVES = 20
class Mountain:
def __init__(self, num_curves):
self.num_curves = num_curves
self.points = []
self.generate_initial_mountain()
def generate_initial_mountain(self):
self.points = []
step = WIDTH // self.num_curves
for i in range(self.num_curves + 2):
x = i * step
y = HEIGHT // 2 + random.randint(-100, 100)
self.points.append([x, y])
def update(self, speed):
# Move all points to the left based on speed
for point in self.points:
point[0] -= speed
# Remove points that are off-screen
while self.points and self.points[0][0] < -step:
self.points.pop(0)
# Add new points to the right if needed
while self.points[-1][0] < WIDTH + step:
last_x, last_y = self.points[-1]
new_x = last_x + step
# Ensure the new y is not too steep
new_y = last_y + random.randint(-50, 50)
new_y = max(HEIGHT // 2 - 200, min(HEIGHT - 50, new_y))
self.points.append([new_x, new_y])
def draw(self, surface):
pygame.draw.polygon(surface, GREEN, self.points + [[self.points[-1][0], HEIGHT], [self.points[0][0], HEIGHT]])
def get_height_at(self, x):
# Find two points between which x lies
for i in range(len(self.points) - 1):
if self.points[i][0] <= x <= self.points[i+1][0]:
# Linear interpolation
x1, y1 = self.points[i]
x2, y2 = self.points[i+1]
if x2 - x1 == 0:
return y1
t = (x - x1) / (x2 - x1)
return y1 + t * (y2 - y1)
return HEIGHT # Fallback
def increase_curves(self):
if self.num_curves < MAX_CURVES:
self.num_curves += 1
self.regenerate()
def decrease_curves(self):
if self.num_curves > MIN_CURVES:
self.num_curves -= 1
self.regenerate()
def regenerate(self):
# Regenerate mountain points based on new number of curves
self.generate_initial_mountain()
class Ball:
def __init__(self, mountain):
self.mountain = mountain
self.x = WIDTH // 4
self.y = self.mountain.get_height_at(self.x) - BALL_RADIUS
self.vx = 0
self.vy = 0
self.on_ground = True
def update(self):
# Apply gravity
if not self.on_ground:
self.vy += GRAVITY
else:
self.vy = 0
# Update position
self.x += self.vx
self.y += self.vy
# Collision with mountain
terrain_y = self.mountain.get_height_at(self.x)
if self.y + BALL_RADIUS >= terrain_y:
self.y = terrain_y - BALL_RADIUS
self.on_ground = True
# Calculate slope
delta_x = 1
y1 = self.mountain.get_height_at(self.x)
y2 = self.mountain.get_height_at(self.x + delta_x)
slope = (y2 - y1) / delta_x
angle = math.atan(slope)
# Apply slope to velocity
self.vx += GRAVITY * math.sin(angle)
self.vy = 0
# Apply friction
if self.vx > 0:
self.vx -= FRICTION
if self.vx < 0:
self.vx = 0
elif self.vx < 0:
self.vx += FRICTION
if self.vx > 0:
self.vx = 0
else:
self.on_ground = False
def draw(self, surface):
pygame.draw.circle(surface, RED, (int(self.x), int(self.y)), BALL_RADIUS)
def main():
mountain = Mountain(INITIAL_CURVES)
ball = Ball(mountain)
scroll_speed = 2
step = WIDTH // mountain.num_curves
font = pygame.font.SysFont(None, 24)
running = True
while running:
clock.tick(FPS)
# Event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
mountain.increase_curves()
step = WIDTH // mountain.num_curves
elif event.key == pygame.K_DOWN:
mountain.decrease_curves()
step = WIDTH // mountain.num_curves
# Update mountain and ball
mountain.update(scroll_speed)
ball.update()
# Move the mountain and simulate camera by adjusting ball's position
# For simplicity, we keep the ball's x fixed and scroll the mountain
# Adjust ball's x based on scroll
# Alternatively, implement a camera system
# Clear screen
screen.fill(BLUE)
# Draw mountain
mountain.draw(screen)
# Draw ball
ball.draw(screen)
# Display number of curves
text = font.render(f"Number of Curves: {mountain.num_curves} (Up/Down to change)", True, BLACK)
screen.blit(text, (10, 10))
# Update display
pygame.display.flip()
pygame.quit()
sys.exit()
if __name__ == "__main__":
main()
Mountain Class: Manages the generation and rendering of the mountain terrain.
generate_initial_mountain(): Initializes the mountain with a set number of curves. Each point is spaced evenly along the x-axis, and the y-coordinate is randomly varied to create the terrain's undulations.
update(speed): Moves all points to the left to simulate scrolling. Removes points that are off-screen and adds new points to the right to maintain the endless effect.
get_height_at(x): Returns the y-coordinate of the terrain at a given x-position using linear interpolation between the two surrounding points.
increase_curves() and decrease_curves(): Adjust the number of curves, regenerating the mountain to reflect the new setting.
Ball Class: Represents the ball and handles its physics interactions with the mountain.
update(): Applies gravity if the ball is in the air, updates the ball's position, and handles collision detection with the mountain. If the ball is on the ground, it calculates the slope of the terrain to adjust the ball's velocity accordingly and applies friction to simulate realistic movement.The draw methods in both Mountain and Ball classes handle rendering the terrain and the ball on the screen.
The number of curves is displayed at the top-left corner of the screen for user reference.
Ensure Pygame is Installed: If you haven't installed Pygame yet, do so using pip install pygame.
Run the Script: Save the code to a file, for example, endless_mountain.py, and run it using Python:
python endless_mountain.py
Controls:
Exit: Close the window or press the close button to exit the game.
Camera Movement: Implement a camera system to allow the ball to move horizontally while the mountain scrolls, providing a more dynamic experience.
Enhanced Physics: Add more realistic physics, such as angular velocity for the ball, better collision handling, and energy conservation.
Visual Improvements: Add textures, shadows, or more detailed graphics to enhance the visual appeal.
Obstacles and Levels: Introduce obstacles, collectibles, or different levels to increase the game's complexity and fun.
Feel free to modify and expand upon this basic implementation to create a more feature-rich game!
Not yet included in a published release.