杰瑞科技汇

Slip Slide Python,如何实现流畅滑动效果?

Of course! "Slip and slide" is a classic game concept, and Python is a fantastic language for creating it. We'll build a simple, graphical version using the popular pygame library.

Slip Slide Python,如何实现流畅滑动效果?-图1
(图片来源网络,侵删)

This guide will walk you through creating a "slip and slide" game where the player controls a character on a slippery surface, trying to reach a goal while avoiding obstacles.

Final Result Preview

Here's what we're aiming for:


Step 1: Setting Up Your Environment

First, you need to install the pygame library. Open your terminal or command prompt and run:

pip install pygame

Now, create a new folder for your project. Inside that folder, create a Python file named slip_slide_game.py.

Slip Slide Python,如何实现流畅滑动效果?-图2
(图片来源网络,侵删)

Step 2: The Basic Game Window

Every pygame application starts by setting up a window. Let's get a window to appear.

# slip_slide_game.py
import pygame
import sys
# 1. Initialize Pygame
pygame.init()
# 2. Set up the screen
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Slip and Slide")
# 3. Define colors (RGB)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 100, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 4. Game loop
running = True
while running:
    # Event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # Drawing
    screen.fill(WHITE) # Fill the screen with white
    pygame.display.flip() # Update the display
# Quit Pygame
pygame.quit()
sys.exit()

Run this code. You should see a blank white window that you can close. This is the foundation of our game.


Step 3: Adding the Player and "Slippery" Physics

The core of a "slip and slide" game is momentum. When you press a key, the player doesn't instantly move; they accelerate. When you let go, they slide to a stop.

We'll represent the player with a simple circle and use variables for their position (x, y) and velocity (vel_x, vel_y).

# Add these variables inside the main game loop, before the while loop:
# Player properties
player_radius = 20
player_x = SCREEN_WIDTH // 2
player_y = SCREEN_HEIGHT // 2
player_vel_x = 0
player_vel_y = 0
# Physics constants
ACCELERATION = 0.5  # How fast the player speeds up
FRICTION = 0.95     # How much the player slows down (0.95 = 5% speed loss per frame)
MAX_SPEED = 8       # The maximum speed the player can reach
# Inside the while loop, replace the drawing section with this:
    # --- Drawing ---
    screen.fill(WHITE)
    # Draw the player
    pygame.draw.circle(screen, BLUE, (int(player_x), int(player_y)), player_radius)
    # --- Update ---
    # This will handle physics and input, we'll add this next

Run this. You should see a blue circle in the middle of the screen.


Step 4: Handling Input and Applying Physics

Now for the fun part! We'll check for key presses and update the player's velocity and position accordingly.

Add this block of code inside the while running: loop, right after the event handling for loop.

    # --- Input and Physics Update ---
    keys = pygame.key.get_pressed()
    # Accelerate based on key presses
    if keys[pygame.K_LEFT]:
        player_vel_x -= ACCELERATION
    if keys[pygame.K_RIGHT]:
        player_vel_x += ACCELERATION
    if keys[pygame.K_UP]:
        player_vel_y -= ACCELERATION
    if keys[pygame.K_DOWN]:
        player_vel_y += ACCELERATION
    # Apply friction to simulate sliding
    player_vel_x *= FRICTION
    player_vel_y *= FRICTION
    # Limit the maximum speed
    speed = (player_vel_x**2 + player_vel_y**2)**0.5
    if speed > MAX_SPEED:
        player_vel_x = (player_vel_x / speed) * MAX_SPEED
        player_vel_y = (player_vel_y / speed) * MAX_SPEED
    # Update the player's position
    player_x += player_vel_x
    player_y += player_vel_y
    # Keep the player on the screen (simple boundary collision)
    if player_x - player_radius < 0:
        player_x = player_radius
        player_vel_x *= -0.5 # Bounce and lose energy
    if player_x + player_radius > SCREEN_WIDTH:
        player_x = SCREEN_WIDTH - player_radius
        player_vel_x *= -0.5
    if player_y - player_radius < 0:
        player_y = player_radius
        player_vel_y *= -0.5
    if player_y + player_radius > SCREEN_HEIGHT:
        player_y = SCREEN_HEIGHT - player_radius
        player_vel_y *= -0.5

Run the game now! You can control the blue circle with the arrow keys. Notice how it slides and doesn't stop instantly.


Step 5: Adding a Goal and Win Condition

A game needs an objective. Let's add a green goal circle. If the player touches it, they win!

Add these variables near the top of your script with the other constants:

# Goal properties
goal_radius = 30
goal_x = SCREEN_WIDTH - 100
goal_y = 100

Now, draw the goal in the main loop. Add this line inside the screen.fill(WHITE) block, right after you draw the player:

    # Draw the player
    pygame.draw.circle(screen, BLUE, (int(player_x), int(player_y)), player_radius)
    # Draw the goal
    pygame.draw.circle(screen, GREEN, (goal_x, goal_y), goal_radius)

Finally, let's add the win condition. Add this check at the very end of the while loop, after the boundary collision logic:

    # Check for win condition
    distance_to_goal = ((player_x - goal_x)**2 + (player_y - goal_y)**2)**0.5
    if distance_to_goal < player_radius + goal_radius:
        font = pygame.font.Font(None, 74)
        text = font.render("You Win!", True, GREEN)
        text_rect = text.get_rect(center=(SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
        screen.blit(text, text_rect)
        pygame.display.flip()
        pygame.time.wait(3000) # Wait for 3 seconds
        running = False # End the game

Run the game! Navigate the blue circle to the green goal to win.


Step 6: Adding Obstacles (Optional but Recommended)

Games are more fun with challenges. Let's add some red obstacles that the player must avoid.

First, create a list to hold the obstacles. We'll store each obstacle as a dictionary with its position and size.

# Add this near the top with other variables
obstacles = [
    {"x": 300, "y": 200, "width": 50, "height": 200},
    {"x": 500, "y": 350, "width": 200, "height": 50},
    {"x": 200, "y": 450, "width": 100, "height": 50}
]

Now, draw them in the main loop. Add this after drawing the goal:

    # Draw the goal
    pygame.draw.circle(screen, GREEN, (goal_x, goal_y), goal_radius)
    # Draw obstacles
    for obs in obstacles:
        pygame.draw.rect(screen, RED, (obs["x"], obs["y"], obs["width"], obs["height"]))

Finally, let's add collision detection with these obstacles. We'll use a simple rectangle-circle collision. Add this logic right before the win condition check.

    # Check for obstacle collisions
    player_rect = pygame.Rect(player_x - player_radius, player_y - player_radius, 
                              player_radius * 2, player_radius * 2)
    for obs in obstacles:
        obstacle_rect = pygame.Rect(obs["x"], obs["y"], obs["width"], obs["height"])
        if player_rect.colliderect(obstacle_rect):
            # Simple bounce back
            player_vel_x *= -0.8
            player_vel_y *= -0.8
            # Move player outside the obstacle to prevent getting stuck
            if player_x < obs["x"]:
                player_x = obs["x"] - player_radius - 1
            elif player_x > obs["x"] + obs["width"]:
                player_x = obs["x"] + obs["width"] + player_radius + 1
            if player_y < obs["y"]:
                player_y = obs["y"] - player_radius - 1
            elif player_y > obs["y"] + obs["height"]:
                player_y = obs["y"] + obs["height"] + player_radius + 1

The Complete Code

Here is the full, commented code for the game. You can copy and paste this into your slip_slide_game.py file.

import pygame
import sys
# 1. Initialize Pygame
pygame.init()
# 2. Set up the screen
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Slip and Slide")
# 3. Define colors (RGB)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
BLUE = (0, 100, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# Game objects
player_radius = 20
player_x = SCREEN_WIDTH // 2
player_y = SCREEN_HEIGHT // 2
player_vel_x = 0
player_vel_y = 0
# Physics constants
ACCELERATION = 0.5
FRICTION = 0.95
MAX_SPEED = 8
# Goal properties
goal_radius = 30
goal_x = SCREEN_WIDTH - 100
goal_y = 100
# Obstacles
obstacles = [
    {"x": 300, "y": 200, "width": 50, "height": 200},
    {"x": 500, "y": 350, "width": 200, "height": 50},
    {"x": 200, "y": 450, "width": 100, "height": 50}
]
# 4. Game loop
clock = pygame.time.Clock() # To control the frame rate
running = True
while running:
    # Event handling
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
    # --- Input and Physics Update ---
    keys = pygame.key.get_pressed()
    # Accelerate based on key presses
    if keys[pygame.K_LEFT]:
        player_vel_x -= ACCELERATION
    if keys[pygame.K_RIGHT]:
        player_vel_x += ACCELERATION
    if keys[pygame.K_UP]:
        player_vel_y -= ACCELERATION
    if keys[pygame.K_DOWN]:
        player_vel_y += ACCELERATION
    # Apply friction to simulate sliding
    player_vel_x *= FRICTION
    player_vel_y *= FRICTION
    # Limit the maximum speed
    speed = (player_vel_x**2 + player_vel_y**2)**0.5
    if speed > MAX_SPEED:
        player_vel_x = (player_vel_x / speed) * MAX_SPEED
        player_vel_y = (player_vel_y / speed) * MAX_SPEED
    # Update the player's position
    player_x += player_vel_x
    player_y += player_vel_y
    # Keep the player on the screen (simple boundary collision)
    if player_x - player_radius < 0:
        player_x = player_radius
        player_vel_x *= -0.5
    if player_x + player_radius > SCREEN_WIDTH:
        player_x = SCREEN_WIDTH - player_radius
        player_vel_x *= -0.5
    if player_y - player_radius < 0:
        player_y = player_radius
        player_vel_y *= -0.5
    if player_y + player_radius > SCREEN_HEIGHT:
        player_y = SCREEN_HEIGHT - player_radius
        player_vel_y *= -0.5
    # Check for obstacle collisions
    player_rect = pygame.Rect(player_x - player_radius, player_y - player_radius, 
                              player_radius * 2, player_radius * 2)
    for obs in obstacles:
        obstacle_rect = pygame.Rect(obs["x"], obs["y"], obs["width"], obs["height"])
        if player_rect.colliderect(obstacle_rect):
            # Simple bounce back
            player_vel_x *= -0.8
            player_vel_y *= -0.8
            # Move player outside the obstacle to prevent getting stuck
            if player_x < obs["x"]:
                player_x = obs["x"] - player_radius - 1
            elif player_x > obs["x"] + obs["width"]:
                player_x = obs["x"] + obs["width"] + player_radius + 1
            if player_y < obs["y"]:
                player_y = obs["y"] - player_radius - 1
            elif player_y > obs["y"] + obs["height"]:
                player_y = obs["y"] + obs["height"] + player_radius + 1
    # Check for win condition
    distance_to_goal = ((player_x - goal_x)**2 + (player_y - goal_y)**2)**0.5
    if distance_to_goal < player_radius + goal_radius:
        font = pygame.font.Font(None, 74)
        text = font.render("You Win!", True, GREEN)
        text_rect = text.get_rect(center=(SCREEN_WIDTH/2, SCREEN_HEIGHT/2))
        screen.blit(text, text_rect)
        pygame.display.flip()
        pygame.time.wait(3000) # Wait for 3 seconds
        running = False # End the game
    # --- Drawing ---
    screen.fill(WHITE)
    # Draw the player
    pygame.draw.circle(screen, BLUE, (int(player_x), int(player_y)), player_radius)
    # Draw the goal
    pygame.draw.circle(screen, GREEN, (goal_x, goal_y), goal_radius)
    # Draw obstacles
    for obs in obstacles:
        pygame.draw.rect(screen, RED, (obs["x"], obs["y"], obs["width"], obs["height"]))
    # Update the display
    pygame.display.flip()
    # Cap the frame rate
    clock.tick(60)
# Quit Pygame
pygame.quit()
sys.exit()

Next Steps and Improvements

This is a great starting point. Here are some ideas to expand the game:

  1. Levels: Load different obstacle layouts from a text file or a list of dictionaries.
  2. Restart Mechanism: Instead of quitting, add a "Game Over" or "You Win!" screen with a button to restart the level.
  3. Score/Timer: Add a timer to see how long it takes the player to complete the level.
  4. Better Graphics: Replace the simple shapes with actual images (sprites) for the player, goal, and obstacles.
  5. Sound Effects: Add sounds for movement, collisions, and winning.
  6. Different Surfaces: Create zones on the screen with different friction values (e.g., ice for low friction, mud for high friction).
分享:
扫描分享到社交APP
上一篇
下一篇