杰瑞科技汇

Python机器人如何实现骑行控制?

Of course! Let's build a simple but fun Python Robot Ride game using the pygame library. This game will be a classic endless runner where you control a robot, dodge obstacles, and try to get the highest score.

Python机器人如何实现骑行控制?-图1
(图片来源网络,侵删)

Game Concept

  • You control a robot that can move left and right at the bottom of the screen.
  • Obstacles (meteors) fall from the top of the screen.
  • You must dodge the meteors.
  • If a meteor hits you, the game is over.
  • Your score increases over the longer you survive.

Step 1: Installation

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

pip install pygame

Step 2: The Complete Code

Here is the full code for the game. You can copy and paste this into a file named robot_ride.py.

import pygame
import random
# --- Constants ---
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60
# Colors (R, G, B)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
# --- Classes ---
class Player(pygame.sprite.Sprite):
    """This class represents the player (the robot)."""
    def __init__(self):
        super().__init__()
        # We'll use a simple colored rectangle for the robot for now.
        # You can replace this with an image.
        self.image = pygame.Surface([50, 50])
        self.image.fill(BLUE)
        self.rect = self.image.get_rect()
        # Position the player at the bottom center of the screen
        self.rect.x = SCREEN_WIDTH // 2 - self.rect.width // 2
        self.rect.y = SCREEN_HEIGHT - self.rect.height - 20
        self.speed_x = 0
        self.speed_y = 0
    def update(self):
        """Update the player's position."""
        self.speed_x = 0
        keystate = pygame.key.get_pressed() # Get the state of all keyboard keys
        # If left arrow is pressed, move left
        if keystate[pygame.K_LEFT]:
            self.speed_x = -8
        # If right arrow is pressed, move right
        if keystate[pygame.K_RIGHT]:
            self.speed_x = 8
        self.rect.x += self.speed_x
        # Keep the player on the screen
        if self.rect.left < 0:
            self.rect.left = 0
        if self.rect.right > SCREEN_WIDTH:
            self.rect.right = SCREEN_WIDTH
class Obstacle(pygame.sprite.Sprite):
    """This class represents the falling obstacles (meteors)."""
    def __init__(self):
        super().__init__()
        # Simple colored rectangle for the obstacle
        self.image = pygame.Surface([30, 30])
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        # Start the obstacle at a random x position at the top of the screen
        self.rect.x = random.randrange(SCREEN_WIDTH - self.rect.width)
        self.rect.y = random.randrange(-100, -40)
        # Set a random falling speed
        self.speed_y = random.randrange(4, 8)
    def update(self):
        """Move the obstacle down."""
        self.rect.y += self.speed_y
        # If the obstacle goes off the bottom of the screen, remove it
        if self.rect.top > SCREEN_HEIGHT + 10:
            self.kill() # kill() removes the sprite from all groups
# --- Functions ---
def draw_text(surface, text, size, x, y, color):
    """Draw text on the screen."""
    font = pygame.font.Font(pygame.font.match_font('arial'), size)
    text_surface = font.render(text, True, color)
    text_rect = text_surface.get_rect()
    text_rect.midtop = (x, y)
    surface.blit(text_surface, text_rect)
def show_game_over_screen(screen, score):
    """Display the game over screen."""
    screen.fill(BLACK)
    draw_text(screen, "GAME OVER", 64, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4, WHITE)
    draw_text(screen, f"Your Score: {score}", 32, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, WHITE)
    draw_text(screen, "Press any key to play again", 22, SCREEN_WIDTH / 2, SCREEN_HEIGHT * 3/4, WHITE)
    pygame.display.flip()
    # Wait for the player to press a key
    waiting = True
    while waiting:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
            if event.type == pygame.KEYUP:
                waiting = False
def show_start_screen(screen):
    """Display the start screen."""
    screen.fill(BLACK)
    draw_text(screen, "ROBOT RIDE", 64, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 4, GREEN)
    draw_text(screen, "Use LEFT and RIGHT arrows to move", 22, SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2, WHITE)
    draw_text(screen, "Press any key to start", 22, SCREEN_WIDTH / 2, SCREEN_HEIGHT * 3/4, WHITE)
    pygame.display.flip()
    # Wait for the player to press a key
    waiting = True
    while waiting:
        clock.tick(FPS)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                exit()
            if event.type == pygame.KEYUP:
                waiting = False
# --- Main Game Loop ---
def main():
    pygame.init()
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("Robot Ride")
    clock = pygame.time.Clock()
    show_start_screen(screen)
    # Sprite groups
    all_sprites = pygame.sprite.Group()
    obstacles = pygame.sprite.Group()
    player = Player()
    all_sprites.add(player)
    # Game variables
    score = 0
    running = True
    # --- Main Game Loop ---
    while running:
        # Keep loop running at the right speed
        clock.tick(FPS)
        # Process input (events)
        for event in pygame.event.get():
            # Check for closing the window
            if event.type == pygame.QUIT:
                running = False
        # Update
        # Spawn a new obstacle
        if len(obstacles) < 8: # Limit the number of obstacles on screen
            if random.random() > 0.98: # Control spawn rate
                o = Obstacle()
                all_sprites.add(o)
                obstacles.add(o)
        all_sprites.update()
        # Check if an obstacle hit the player
        # spritecollide returns a list of all sprites that collided
        hits = pygame.sprite.spritecollide(player, obstacles, False)
        if hits:
            running = False # Game over if there's a collision
        # Increase score
        score += 1
        # Draw / Render
        screen.fill(BLACK)
        # Draw all sprites
        all_sprites.draw(screen)
        # Draw the score
        draw_text(screen, f"Score: {score}", 24, 60, 10, YELLOW)
        # After drawing everything, flip the display
        pygame.display.flip()
    # Game Over
    show_game_over_screen(screen, score)
    # Quit the game
    pygame.quit()
    exit()
if __name__ == "__main__":
    main()

Step 3: How to Run the Game

  1. Save the code above as a Python file (e.g., robot_ride.py).
  2. Open your terminal or command prompt.
  3. Navigate to the directory where you saved the file.
  4. Run the script with the command: python robot_ride.py

A window should appear, and you can start playing!


Step 4: How the Code Works (Explanation)

Imports and Setup

import pygame
import random

We import pygame for all the game functionality and random to make the game unpredictable (e.g., where obstacles spawn).

Python机器人如何实现骑行控制?-图2
(图片来源网络,侵删)

Constants

SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
FPS = 60
BLACK = (0, 0, 0)
# ... etc

Constants are defined at the top for easy modification.

  • SCREEN_WIDTH and SCREEN_HEIGHT set the size of the game window.
  • FPS (Frames Per Second) controls how fast the game loop runs.
  • Color constants like BLACK, WHITE make the code more readable.

The Player Class

class Player(pygame.sprite.Sprite):

This class defines our robot.

  • __init__(self): This is the constructor. It creates the robot's image (a blue rectangle for now) and sets its starting position at the bottom center of the screen.
  • update(self): This method is called on every frame. It checks for key presses (left/right arrows) and updates the robot's x position accordingly. It also contains logic to prevent the robot from moving off the screen.

The Obstacle Class

class Obstacle(pygame.sprite.Sprite):

This class defines the falling meteors.

  • __init__(self): It creates a red rectangle for the meteor and gives it a random starting x position at the top of the screen. It also assigns a random falling speed.
  • update(self): This moves the meteor down by its speed_y value. If it goes past the bottom of the screen, self.kill() is called to remove it from the game, which is important for performance.

Helper Functions

  • draw_text(): A useful function to draw text on the screen, as pygame doesn't have a simple "draw text" command.
  • show_game_over_screen() and show_start_screen(): These functions handle the screens that appear before and after the main game. They use a while loop to wait for the player to press a key before continuing.

The main() Function

This is the heart of the game.

Python机器人如何实现骑行控制?-图3
(图片来源网络,侵删)
  • Initialization: It sets up the pygame window, clock, and sprite groups. A "sprite group" is a pygame feature that makes it easy to manage and update all your game objects at once.
  • Main Loop (while running): This loop runs 60 times every second.
    1. Event Handling: It checks for events like quitting the game or pressing keys.
    2. Spawning Obstacles: It randomly creates new Obstacle sprites and adds them to the game.
    3. Updating: all_sprites.update() is called, which in turn calls the update() method for every single sprite in the game (the player and all obstacles).
    4. Collision Detection: pygame.sprite.spritecollide(player, obstacles, False) is the magic line. It checks if the player sprite has collided with any sprites in the obstacles group. If it has, running is set to False, ending the game loop.
    5. Drawing: Everything is drawn on the screen in this order: fill the background with black, draw all the sprites, draw the score text, and finally, pygame.display.flip() updates the screen to show the player what was drawn.

Step 5: How to Improve and Customize the Game

This is a great starting point. Here are some ideas to make it even better:

  1. Add Images: Instead of colored rectangles, load actual images for the robot and the meteors.

    # In the Player class __init__
    self.image = pygame.image.load("robot.png").convert_alpha()
    self.rect = self.image.get_rect()
    # ... do the same for the Obstacle class
  2. Add Sound Effects: Add sounds for jumping, collisions, and background music.

    pygame.mixer.init()
    jump_sound = pygame.mixer.Sound("jump.wav")
    # ... in your code
    # jump_sound.play()
  3. Increase Difficulty: Make the game harder over time. You could increase the speed of obstacles or the rate at which they spawn as the player's score gets higher.

  4. Add a Power-Up: Create a new PowerUp class. Maybe a green square that makes the player invincible for a few seconds if they touch it.

  5. Add a Jump: Modify the Player class to have a jump() method and add gravity to make the robot jump and fall. This would make the gameplay more dynamic.

分享:
扫描分享到社交APP
上一篇
下一篇