Công cụ trò chơi dựa trên văn bản Python

Giống như nhiều người, có thể bạn muốn viết trò chơi điện tử khi mới học viết mã. Nhưng những trò chơi đó có giống những trò chơi bạn đã chơi không? . Không có hướng dẫn hoặc khuôn khổ thực sự để hỗ trợ bạn, đồ họa và âm thanh tiên tiến mà bạn đã trải nghiệm trong các trò chơi khác có thể vẫn nằm ngoài tầm với

Giờ đây, đã có Python và rất nhiều công cụ trò chơi Python tuyệt vời có sẵn. Sự kết hợp mạnh mẽ này làm cho việc tạo ra các trò chơi máy tính tuyệt vời trở nên dễ dàng hơn nhiều so với trước đây. Trong hướng dẫn này, bạn sẽ khám phá một số công cụ trò chơi này, tìm hiểu những gì bạn cần để bắt đầu tạo trò chơi điện tử Python của riêng mình

Đến cuối bài viết này, bạn sẽ

  • Hiểu ưu và nhược điểm của một số công cụ trò chơi Python phổ biến
  • Xem các công cụ trò chơi này đang hoạt động
  • Hiểu cách chúng so sánh với các công cụ trò chơi độc lập
  • Tìm hiểu về các công cụ trò chơi Python khác có sẵn

Để tận dụng tối đa hướng dẫn này, bạn nên thành thạo lập trình Python, bao gồm cả lập trình hướng đối tượng. Sự hiểu biết về các khái niệm trò chơi cơ bản là hữu ích, nhưng không cần thiết

Ready to dive in? Click the link below to download the source code for all the games that you’ll be creating

Get Source Code. Click here to get the source code you’ll use to try out Python game engines

Python Game Engines Overview

Game engines for Python most often take the form of Python libraries, which can be installed in a variety of ways. Most are available on PyPI and can be installed with

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
7. However, a few are available only on GitHub, GitLab, or other code sharing locations, and they may require other installation steps. This article will cover installation methods for all the engines discussed

Python is a general purpose programming language, and it’s used for a variety of tasks other than writing computer games. In contrast, there are many different stand-alone game engines that are tailored specifically to writing games. Some of these include

  • The Unreal Engine
  • Unity
  • Godot

These stand-alone game engines differ from Python game engines in several key aspects

  • Language support. Languages like C++, C#, and JavaScript are popular for games written in stand-alone game engines, as the engines themselves are often written in these languages. Very few stand-alone engines support Python
  • Proprietary scripting support. In addition, many stand-alone game engines maintain and support their own scripting languages, which may not resemble Python. For example, Unity uses C# natively, while Unreal works best with C++
  • Platform support. Many modern stand-alone game engines can produce games for a variety of platforms, including mobile and dedicated game systems, with very little effort. In contrast, porting a Python game across various platforms, especially mobile platforms, can be a major undertaking
  • Licensing options. Games written using a stand-alone game engine may have different licensing options and restrictions, based on the engine used

So why use Python to write games at all? In a word, Python. Using a stand-alone game engine often requires you to learn a new programming or scripting language. Python game engines leverage your existing knowledge of Python, reducing the learning curve and getting you moving forward quickly

There are many game engines available for the Python environment. The engines that you’ll learn about here all share the following criteria

  • They’re relatively popular engines, or they cover aspects of gaming that aren’t usually covered
  • They’re currently maintained
  • They have good documentation available

For each engine, you’ll learn about

  • Installation methods
  • Basic concepts, as well as assumptions that the engine makes
  • Major features and capabilities
  • Two game implementations, to allow for comparison

Where appropriate, you should install these game engines in a virtual environment. Full source code for the games in this tutorial is available for download at the link below and will be referenced throughout the article

Get Source Code. Click here to get the source code you’ll use to try out Python game engines

With the source code downloaded, you’re ready to begin

Remove ads

trò chơi ghép hình

When people think of Python game engines, the first thought many have is Pygame. In fact, there’s already a great primer on Pygame available at Real Python

Written as a replacement for the stalled PySDL library, Pygame wraps and extends the SDL library, which stands for Simple DirectMedia Layer. SDL provides cross-platform access to your system’s underlying multimedia hardware components, such as sound, video, mouse, keyboard, and joystick. The cross-platform nature of both SDL and Pygame means that you can write games and rich multimedia Python programs for every platform that supports them

Pygame Installation

Pygame is available on PyPI, so after creating and activating a virtual environment, you can install it using the appropriate

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
7 command

(venv) $ python -m pip install pygame

Once that’s done, you can verify the installation by running an example that comes with the library

(venv) $ python -m pygame.examples.aliens

Now that you’ve installed Pygame, you can begin using it right away. If you run into problems during installation, then the Getting Started guide outlines some known issues and possible solutions for all platforms

Basic Concepts

Pygame is organized into several different modules, which provide abstracted access to your computer graphics, sound, and input hardware. Pygame also defines numerous classes, which encapsulate concepts that aren’t hardware dependent. For example, drawing is done on

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
9 objects, whose rectangular limits are defined by their
(venv) $ python pygame/pygame_basic.py
0 object

Every game utilizes a game loop to control game play. This loop iterates constantly as the game progresses. Pygame provides methods and functions to implement a game loop, but it doesn’t provide one automatically. The game author is expected to implement the functionality of a game loop

Each iteration of the game loop is called a frame. Every frame, the game performs four vital actions

  1. Processing user input. User input in Pygame is handled using an . Mouse and keyboard input generate events, which can be read and handled, or ignored as you see fit. Pygame itself doesn’t provide any event handlers

  2. Updating the state of game objects. Game objects can be represented using any Pygame data structure or special Pygame class. Objects such as , , fonts, and colors can be created and extended in Python to provide as much state information as necessary

  3. Updating the display and audio output. Pygame provides abstract access to display and . The

    (venv) $ python pygame/pygame_basic.py
    
    1,
    (venv) $ python pygame/pygame_basic.py
    
    2, and
    (venv) $ python pygame/pygame_basic.py
    
    3 modules allow game authors flexibility in game design and implementation

  4. Maintaining the speed of the game. Pygame’s

    (venv) $ python pygame/pygame_basic.py
    
    4 module allows game authors to . By ensuring each frame completes within a specified time limit, game authors can ensure the game runs similarly on different hardware

You can see these concepts come together in a basic example

Basic Application

This basic Pygame program draws a few shapes and some text on the screen

Công cụ trò chơi dựa trên văn bản Python

The code for this sample can be found below and in the downloadable materials

Source for

(venv) $ python pygame/pygame_basic.py
5Show/Hide

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()

Mặc dù có nguyện vọng khiêm tốn, ngay cả chương trình Pygame cơ bản này cũng yêu cầu vòng lặp trò chơi và trình xử lý sự kiện. Vòng lặp trò chơi bắt đầu ở dòng 27 và được điều khiển bởi biến

(venv) $ python pygame/pygame_basic.py
6. Đặt biến này thành
(venv) $ python pygame/pygame_basic.py
7 sẽ kết thúc chương trình

Xử lý sự kiện bắt đầu trên dòng 30 với vòng lặp sự kiện. Các sự kiện được truy xuất từ ​​hàng đợi bằng cách sử dụng

(venv) $ python pygame/pygame_basic.py
8 và được xử lý lần lượt trong mỗi lần lặp lại vòng lặp. Trong trường hợp này, sự kiện duy nhất được xử lý là sự kiện
(venv) $ python pygame/pygame_basic.py
9, sự kiện này được tạo khi người dùng đóng cửa sổ trò chơi. Khi sự kiện này được xử lý, bạn đặt
  1"""
  2Complete Game in Pygame
  3
  4This game demonstrates some of the more advanced features of
  5Pygame, including:
  6- Using sprites to render complex graphics
  7- Handling user mouse input
  8- Basic sound output
  9"""
 10
 11# Import and initialize the pygame library
 12import pygame
 13
 14# To randomize coin placement
 15from random import randint
 16
 17# To find your assets
 18from pathlib import Path
 19
 20# For type hinting
 21from typing import Tuple
 22
 23# Set the width and height of the output window, in pixels
 24WIDTH = 800
 25HEIGHT = 600
 26
 27# How quickly do you generate coins? Time is in milliseconds
 28coin_countdown = 2500
 29coin_interval = 100
 30
 31# How many coins can be on the screen before you end?
 32COIN_COUNT = 10
 33
 34# Define the Player sprite
 35class Player(pygame.sprite.Sprite):
 36    def __init__(self):
 37        """Initialize the player sprite"""
 38        super(Player, self).__init__()
 39
 40        # Get the image to draw for the player
 41        player_image = str(
 42            Path.cwd() / "pygame" / "images" / "alien_green_stand.png"
 43        )
 44        # Load the image, preserve alpha channel for transparency
 45        self.surf = pygame.image.load(player_image).convert_alpha()
 46        # Save the rect so you can move it
 47        self.rect = self.surf.get_rect()
 48
 49    def update(self, pos: Tuple):
 50        """Update the position of the player
 51
 52        Arguments:
 53            pos {Tuple} -- the (X,Y) position to move the player
 54        """
 55        self.rect.center = pos
 56
 57# Define the Coin sprite
 58class Coin(pygame.sprite.Sprite):
 59    def __init__(self):
 60        """Initialize the coin sprite"""
 61        super(Coin, self).__init__()
 62
 63        # Get the image to draw for the coin
 64        coin_image = str(Path.cwd() / "pygame" / "images" / "coin_gold.png")
 65
 66        # Load the image, preserve alpha channel for transparency
 67        self.surf = pygame.image.load(coin_image).convert_alpha()
 68
 69        # The starting position is randomly generated
 70        self.rect = self.surf.get_rect(
 71            center=(
 72                randint(10, WIDTH - 10),
 73                randint(10, HEIGHT - 10),
 74            )
 75        )
 76
 77# Initialize the Pygame engine
 78pygame.init()
 79
 80# Set up the drawing window
 81screen = pygame.display.set_mode(size=[WIDTH, HEIGHT])
 82
 83# Hide the mouse cursor
 84pygame.mouse.set_visible(False)
 85
 86# Set up the clock for a decent frame rate
 87clock = pygame.time.Clock()
 88
 89# Create a custom event for adding a new coin
 90ADDCOIN = pygame.USEREVENT + 1
 91pygame.time.set_timer(ADDCOIN, coin_countdown)
 92
 93# Set up the coin_list
 94coin_list = pygame.sprite.Group()
 95
 96# Initialize the score
 97score = 0
 98
 99# Set up the coin pickup sound
100coin_pickup_sound = pygame.mixer.Sound(
101    str(Path.cwd() / "pygame" / "sounds" / "coin_pickup.wav")
102)
103
104# Create a player sprite and set its initial position
105player = Player()
106player.update(pygame.mouse.get_pos())
107
108# Run until you get to an end condition
109running = True
110while running:
111
112    # Did the user click the window close button?
113    for event in pygame.event.get():
114        if event.type == pygame.QUIT:
115            running = False
116
117        # Should you add a new coin?
118        elif event.type == ADDCOIN:
119            # Create a new coin and add it to the coin_list
120            new_coin = Coin()
121            coin_list.add(new_coin)
122
123            # Speed things up if fewer than three coins are on-screen
124            if len(coin_list) < 3:
125                coin_countdown -= coin_interval
126            # Need to have some interval
127            if coin_countdown < 100:
128                coin_countdown = 100
129
130            # Stop the previous timer by setting the interval to 0
131            pygame.time.set_timer(ADDCOIN, 0)
132
133            # Start a new timer
134            pygame.time.set_timer(ADDCOIN, coin_countdown)
135
136    # Update the player position
137    player.update(pygame.mouse.get_pos())
138
139    # Check if the player has collided with a coin, removing the coin if so
140    coins_collected = pygame.sprite.spritecollide(
141        sprite=player, group=coin_list, dokill=True
142    )
143    for coin in coins_collected:
144        # Each coin is worth 10 points
145        score += 10
146        # Play the coin collected sound
147        coin_pickup_sound.play()
148
149    # Are there too many coins on the screen?
150    if len(coin_list) >= COIN_COUNT:
151        # This counts as an end condition, so you end your game loop
152        running = False
153
154    # To render the screen, first fill the background with pink
155    screen.fill((255, 170, 164))
156
157    # Draw the coins next
158    for coin in coin_list:
159        screen.blit(coin.surf, coin.rect)
160
161    # Then draw the player
162    screen.blit(player.surf, player.rect)
163
164    # Finally, draw the score at the bottom left
165    score_font = pygame.font.SysFont("any_font", 36)
166    score_block = score_font.render(f"Score: {score}", False, (0, 0, 0))
167    screen.blit(score_block, (50, HEIGHT - 50))
168
169    # Flip the display to make everything appear
170    pygame.display.flip()
171
172    # Ensure you maintain a 30 frames per second rate
173    clock.tick(30)
174
175# Done! Print the final score
176print(f"Game over! Final score: {score}")
177
178# Make the mouse visible again
179pygame.mouse.set_visible(True)
180
181# Quit the game
182pygame.quit()
0, điều này cuối cùng sẽ kết thúc vòng lặp trò chơi và chương trình

Pygame cung cấp nhiều phương pháp khác nhau để vẽ các hình cơ bản, chẳng hạn như hình tròn và hình chữ nhật. Trong mẫu này, một vòng tròn màu xanh được vẽ trên dòng 38 và một hình vuông màu đỏ được vẽ trên các dòng 41 và 42. Lưu ý rằng việc vẽ một hình chữ nhật yêu cầu bạn tạo một đối tượng

(venv) $ python pygame/pygame_basic.py
0 trước

Vẽ văn bản trên màn hình liên quan nhiều hơn một chút. Đầu tiên, ở dòng 45, bạn chọn một phông chữ và tạo một đối tượng

  1"""
  2Complete Game in Pygame
  3
  4This game demonstrates some of the more advanced features of
  5Pygame, including:
  6- Using sprites to render complex graphics
  7- Handling user mouse input
  8- Basic sound output
  9"""
 10
 11# Import and initialize the pygame library
 12import pygame
 13
 14# To randomize coin placement
 15from random import randint
 16
 17# To find your assets
 18from pathlib import Path
 19
 20# For type hinting
 21from typing import Tuple
 22
 23# Set the width and height of the output window, in pixels
 24WIDTH = 800
 25HEIGHT = 600
 26
 27# How quickly do you generate coins? Time is in milliseconds
 28coin_countdown = 2500
 29coin_interval = 100
 30
 31# How many coins can be on the screen before you end?
 32COIN_COUNT = 10
 33
 34# Define the Player sprite
 35class Player(pygame.sprite.Sprite):
 36    def __init__(self):
 37        """Initialize the player sprite"""
 38        super(Player, self).__init__()
 39
 40        # Get the image to draw for the player
 41        player_image = str(
 42            Path.cwd() / "pygame" / "images" / "alien_green_stand.png"
 43        )
 44        # Load the image, preserve alpha channel for transparency
 45        self.surf = pygame.image.load(player_image).convert_alpha()
 46        # Save the rect so you can move it
 47        self.rect = self.surf.get_rect()
 48
 49    def update(self, pos: Tuple):
 50        """Update the position of the player
 51
 52        Arguments:
 53            pos {Tuple} -- the (X,Y) position to move the player
 54        """
 55        self.rect.center = pos
 56
 57# Define the Coin sprite
 58class Coin(pygame.sprite.Sprite):
 59    def __init__(self):
 60        """Initialize the coin sprite"""
 61        super(Coin, self).__init__()
 62
 63        # Get the image to draw for the coin
 64        coin_image = str(Path.cwd() / "pygame" / "images" / "coin_gold.png")
 65
 66        # Load the image, preserve alpha channel for transparency
 67        self.surf = pygame.image.load(coin_image).convert_alpha()
 68
 69        # The starting position is randomly generated
 70        self.rect = self.surf.get_rect(
 71            center=(
 72                randint(10, WIDTH - 10),
 73                randint(10, HEIGHT - 10),
 74            )
 75        )
 76
 77# Initialize the Pygame engine
 78pygame.init()
 79
 80# Set up the drawing window
 81screen = pygame.display.set_mode(size=[WIDTH, HEIGHT])
 82
 83# Hide the mouse cursor
 84pygame.mouse.set_visible(False)
 85
 86# Set up the clock for a decent frame rate
 87clock = pygame.time.Clock()
 88
 89# Create a custom event for adding a new coin
 90ADDCOIN = pygame.USEREVENT + 1
 91pygame.time.set_timer(ADDCOIN, coin_countdown)
 92
 93# Set up the coin_list
 94coin_list = pygame.sprite.Group()
 95
 96# Initialize the score
 97score = 0
 98
 99# Set up the coin pickup sound
100coin_pickup_sound = pygame.mixer.Sound(
101    str(Path.cwd() / "pygame" / "sounds" / "coin_pickup.wav")
102)
103
104# Create a player sprite and set its initial position
105player = Player()
106player.update(pygame.mouse.get_pos())
107
108# Run until you get to an end condition
109running = True
110while running:
111
112    # Did the user click the window close button?
113    for event in pygame.event.get():
114        if event.type == pygame.QUIT:
115            running = False
116
117        # Should you add a new coin?
118        elif event.type == ADDCOIN:
119            # Create a new coin and add it to the coin_list
120            new_coin = Coin()
121            coin_list.add(new_coin)
122
123            # Speed things up if fewer than three coins are on-screen
124            if len(coin_list) < 3:
125                coin_countdown -= coin_interval
126            # Need to have some interval
127            if coin_countdown < 100:
128                coin_countdown = 100
129
130            # Stop the previous timer by setting the interval to 0
131            pygame.time.set_timer(ADDCOIN, 0)
132
133            # Start a new timer
134            pygame.time.set_timer(ADDCOIN, coin_countdown)
135
136    # Update the player position
137    player.update(pygame.mouse.get_pos())
138
139    # Check if the player has collided with a coin, removing the coin if so
140    coins_collected = pygame.sprite.spritecollide(
141        sprite=player, group=coin_list, dokill=True
142    )
143    for coin in coins_collected:
144        # Each coin is worth 10 points
145        score += 10
146        # Play the coin collected sound
147        coin_pickup_sound.play()
148
149    # Are there too many coins on the screen?
150    if len(coin_list) >= COIN_COUNT:
151        # This counts as an end condition, so you end your game loop
152        running = False
153
154    # To render the screen, first fill the background with pink
155    screen.fill((255, 170, 164))
156
157    # Draw the coins next
158    for coin in coin_list:
159        screen.blit(coin.surf, coin.rect)
160
161    # Then draw the player
162    screen.blit(player.surf, player.rect)
163
164    # Finally, draw the score at the bottom left
165    score_font = pygame.font.SysFont("any_font", 36)
166    score_block = score_font.render(f"Score: {score}", False, (0, 0, 0))
167    screen.blit(score_block, (50, HEIGHT - 50))
168
169    # Flip the display to make everything appear
170    pygame.display.flip()
171
172    # Ensure you maintain a 30 frames per second rate
173    clock.tick(30)
174
175# Done! Print the final score
176print(f"Game over! Final score: {score}")
177
178# Make the mouse visible again
179pygame.mouse.set_visible(True)
180
181# Quit the game
182pygame.quit()
2. Sử dụng phông chữ đó trên các dòng 46 đến 48, bạn gọi phương thức
  1"""
  2Complete Game in Pygame
  3
  4This game demonstrates some of the more advanced features of
  5Pygame, including:
  6- Using sprites to render complex graphics
  7- Handling user mouse input
  8- Basic sound output
  9"""
 10
 11# Import and initialize the pygame library
 12import pygame
 13
 14# To randomize coin placement
 15from random import randint
 16
 17# To find your assets
 18from pathlib import Path
 19
 20# For type hinting
 21from typing import Tuple
 22
 23# Set the width and height of the output window, in pixels
 24WIDTH = 800
 25HEIGHT = 600
 26
 27# How quickly do you generate coins? Time is in milliseconds
 28coin_countdown = 2500
 29coin_interval = 100
 30
 31# How many coins can be on the screen before you end?
 32COIN_COUNT = 10
 33
 34# Define the Player sprite
 35class Player(pygame.sprite.Sprite):
 36    def __init__(self):
 37        """Initialize the player sprite"""
 38        super(Player, self).__init__()
 39
 40        # Get the image to draw for the player
 41        player_image = str(
 42            Path.cwd() / "pygame" / "images" / "alien_green_stand.png"
 43        )
 44        # Load the image, preserve alpha channel for transparency
 45        self.surf = pygame.image.load(player_image).convert_alpha()
 46        # Save the rect so you can move it
 47        self.rect = self.surf.get_rect()
 48
 49    def update(self, pos: Tuple):
 50        """Update the position of the player
 51
 52        Arguments:
 53            pos {Tuple} -- the (X,Y) position to move the player
 54        """
 55        self.rect.center = pos
 56
 57# Define the Coin sprite
 58class Coin(pygame.sprite.Sprite):
 59    def __init__(self):
 60        """Initialize the coin sprite"""
 61        super(Coin, self).__init__()
 62
 63        # Get the image to draw for the coin
 64        coin_image = str(Path.cwd() / "pygame" / "images" / "coin_gold.png")
 65
 66        # Load the image, preserve alpha channel for transparency
 67        self.surf = pygame.image.load(coin_image).convert_alpha()
 68
 69        # The starting position is randomly generated
 70        self.rect = self.surf.get_rect(
 71            center=(
 72                randint(10, WIDTH - 10),
 73                randint(10, HEIGHT - 10),
 74            )
 75        )
 76
 77# Initialize the Pygame engine
 78pygame.init()
 79
 80# Set up the drawing window
 81screen = pygame.display.set_mode(size=[WIDTH, HEIGHT])
 82
 83# Hide the mouse cursor
 84pygame.mouse.set_visible(False)
 85
 86# Set up the clock for a decent frame rate
 87clock = pygame.time.Clock()
 88
 89# Create a custom event for adding a new coin
 90ADDCOIN = pygame.USEREVENT + 1
 91pygame.time.set_timer(ADDCOIN, coin_countdown)
 92
 93# Set up the coin_list
 94coin_list = pygame.sprite.Group()
 95
 96# Initialize the score
 97score = 0
 98
 99# Set up the coin pickup sound
100coin_pickup_sound = pygame.mixer.Sound(
101    str(Path.cwd() / "pygame" / "sounds" / "coin_pickup.wav")
102)
103
104# Create a player sprite and set its initial position
105player = Player()
106player.update(pygame.mouse.get_pos())
107
108# Run until you get to an end condition
109running = True
110while running:
111
112    # Did the user click the window close button?
113    for event in pygame.event.get():
114        if event.type == pygame.QUIT:
115            running = False
116
117        # Should you add a new coin?
118        elif event.type == ADDCOIN:
119            # Create a new coin and add it to the coin_list
120            new_coin = Coin()
121            coin_list.add(new_coin)
122
123            # Speed things up if fewer than three coins are on-screen
124            if len(coin_list) < 3:
125                coin_countdown -= coin_interval
126            # Need to have some interval
127            if coin_countdown < 100:
128                coin_countdown = 100
129
130            # Stop the previous timer by setting the interval to 0
131            pygame.time.set_timer(ADDCOIN, 0)
132
133            # Start a new timer
134            pygame.time.set_timer(ADDCOIN, coin_countdown)
135
136    # Update the player position
137    player.update(pygame.mouse.get_pos())
138
139    # Check if the player has collided with a coin, removing the coin if so
140    coins_collected = pygame.sprite.spritecollide(
141        sprite=player, group=coin_list, dokill=True
142    )
143    for coin in coins_collected:
144        # Each coin is worth 10 points
145        score += 10
146        # Play the coin collected sound
147        coin_pickup_sound.play()
148
149    # Are there too many coins on the screen?
150    if len(coin_list) >= COIN_COUNT:
151        # This counts as an end condition, so you end your game loop
152        running = False
153
154    # To render the screen, first fill the background with pink
155    screen.fill((255, 170, 164))
156
157    # Draw the coins next
158    for coin in coin_list:
159        screen.blit(coin.surf, coin.rect)
160
161    # Then draw the player
162    screen.blit(player.surf, player.rect)
163
164    # Finally, draw the score at the bottom left
165    score_font = pygame.font.SysFont("any_font", 36)
166    score_block = score_font.render(f"Score: {score}", False, (0, 0, 0))
167    screen.blit(score_block, (50, HEIGHT - 50))
168
169    # Flip the display to make everything appear
170    pygame.display.flip()
171
172    # Ensure you maintain a 30 frames per second rate
173    clock.tick(30)
174
175# Done! Print the final score
176print(f"Game over! Final score: {score}")
177
178# Make the mouse visible again
179pygame.mouse.set_visible(True)
180
181# Quit the game
182pygame.quit()
3. Thao tác này tạo đối tượng
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
9 chứa văn bản được hiển thị bằng phông chữ và màu sắc đã chỉ định. Cuối cùng, bạn sao chép
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
9 ra màn hình bằng cách sử dụng phương thức
  1"""
  2Complete Game in Pygame
  3
  4This game demonstrates some of the more advanced features of
  5Pygame, including:
  6- Using sprites to render complex graphics
  7- Handling user mouse input
  8- Basic sound output
  9"""
 10
 11# Import and initialize the pygame library
 12import pygame
 13
 14# To randomize coin placement
 15from random import randint
 16
 17# To find your assets
 18from pathlib import Path
 19
 20# For type hinting
 21from typing import Tuple
 22
 23# Set the width and height of the output window, in pixels
 24WIDTH = 800
 25HEIGHT = 600
 26
 27# How quickly do you generate coins? Time is in milliseconds
 28coin_countdown = 2500
 29coin_interval = 100
 30
 31# How many coins can be on the screen before you end?
 32COIN_COUNT = 10
 33
 34# Define the Player sprite
 35class Player(pygame.sprite.Sprite):
 36    def __init__(self):
 37        """Initialize the player sprite"""
 38        super(Player, self).__init__()
 39
 40        # Get the image to draw for the player
 41        player_image = str(
 42            Path.cwd() / "pygame" / "images" / "alien_green_stand.png"
 43        )
 44        # Load the image, preserve alpha channel for transparency
 45        self.surf = pygame.image.load(player_image).convert_alpha()
 46        # Save the rect so you can move it
 47        self.rect = self.surf.get_rect()
 48
 49    def update(self, pos: Tuple):
 50        """Update the position of the player
 51
 52        Arguments:
 53            pos {Tuple} -- the (X,Y) position to move the player
 54        """
 55        self.rect.center = pos
 56
 57# Define the Coin sprite
 58class Coin(pygame.sprite.Sprite):
 59    def __init__(self):
 60        """Initialize the coin sprite"""
 61        super(Coin, self).__init__()
 62
 63        # Get the image to draw for the coin
 64        coin_image = str(Path.cwd() / "pygame" / "images" / "coin_gold.png")
 65
 66        # Load the image, preserve alpha channel for transparency
 67        self.surf = pygame.image.load(coin_image).convert_alpha()
 68
 69        # The starting position is randomly generated
 70        self.rect = self.surf.get_rect(
 71            center=(
 72                randint(10, WIDTH - 10),
 73                randint(10, HEIGHT - 10),
 74            )
 75        )
 76
 77# Initialize the Pygame engine
 78pygame.init()
 79
 80# Set up the drawing window
 81screen = pygame.display.set_mode(size=[WIDTH, HEIGHT])
 82
 83# Hide the mouse cursor
 84pygame.mouse.set_visible(False)
 85
 86# Set up the clock for a decent frame rate
 87clock = pygame.time.Clock()
 88
 89# Create a custom event for adding a new coin
 90ADDCOIN = pygame.USEREVENT + 1
 91pygame.time.set_timer(ADDCOIN, coin_countdown)
 92
 93# Set up the coin_list
 94coin_list = pygame.sprite.Group()
 95
 96# Initialize the score
 97score = 0
 98
 99# Set up the coin pickup sound
100coin_pickup_sound = pygame.mixer.Sound(
101    str(Path.cwd() / "pygame" / "sounds" / "coin_pickup.wav")
102)
103
104# Create a player sprite and set its initial position
105player = Player()
106player.update(pygame.mouse.get_pos())
107
108# Run until you get to an end condition
109running = True
110while running:
111
112    # Did the user click the window close button?
113    for event in pygame.event.get():
114        if event.type == pygame.QUIT:
115            running = False
116
117        # Should you add a new coin?
118        elif event.type == ADDCOIN:
119            # Create a new coin and add it to the coin_list
120            new_coin = Coin()
121            coin_list.add(new_coin)
122
123            # Speed things up if fewer than three coins are on-screen
124            if len(coin_list) < 3:
125                coin_countdown -= coin_interval
126            # Need to have some interval
127            if coin_countdown < 100:
128                coin_countdown = 100
129
130            # Stop the previous timer by setting the interval to 0
131            pygame.time.set_timer(ADDCOIN, 0)
132
133            # Start a new timer
134            pygame.time.set_timer(ADDCOIN, coin_countdown)
135
136    # Update the player position
137    player.update(pygame.mouse.get_pos())
138
139    # Check if the player has collided with a coin, removing the coin if so
140    coins_collected = pygame.sprite.spritecollide(
141        sprite=player, group=coin_list, dokill=True
142    )
143    for coin in coins_collected:
144        # Each coin is worth 10 points
145        score += 10
146        # Play the coin collected sound
147        coin_pickup_sound.play()
148
149    # Are there too many coins on the screen?
150    if len(coin_list) >= COIN_COUNT:
151        # This counts as an end condition, so you end your game loop
152        running = False
153
154    # To render the screen, first fill the background with pink
155    screen.fill((255, 170, 164))
156
157    # Draw the coins next
158    for coin in coin_list:
159        screen.blit(coin.surf, coin.rect)
160
161    # Then draw the player
162    screen.blit(player.surf, player.rect)
163
164    # Finally, draw the score at the bottom left
165    score_font = pygame.font.SysFont("any_font", 36)
166    score_block = score_font.render(f"Score: {score}", False, (0, 0, 0))
167    screen.blit(score_block, (50, HEIGHT - 50))
168
169    # Flip the display to make everything appear
170    pygame.display.flip()
171
172    # Ensure you maintain a 30 frames per second rate
173    clock.tick(30)
174
175# Done! Print the final score
176print(f"Game over! Final score: {score}")
177
178# Make the mouse visible again
179pygame.mouse.set_visible(True)
180
181# Quit the game
182pygame.quit()
6 ở dòng 49

Vòng lặp kết thúc trò chơi xảy ra ở dòng 52, khi mọi thứ được vẽ trước đó được hiển thị trên màn hình. Không có dòng này, sẽ không có gì được hiển thị

Để chạy mã này, hãy sử dụng lệnh sau

(venv) $ python pygame/pygame_basic.py

Bạn sẽ thấy một cửa sổ xuất hiện với hình ảnh hiển thị ở trên. Xin chúc mừng. Bạn vừa chạy chương trình Pygame đầu tiên của mình

Remove ads

Ứng dụng nâng cao

Tất nhiên, Pygame được thiết kế để viết game bằng Python. Để khám phá các khả năng và yêu cầu của một trò chơi Pygame thực tế, bạn sẽ kiểm tra một trò chơi được viết bằng Pygame với các chi tiết sau

  • Người chơi là một nhân vật duy nhất trên màn hình, được điều khiển bằng cách di chuyển chuột
  • Theo các khoảng thời gian đều đặn, từng đồng xu xuất hiện trên màn hình
  • Khi người chơi di chuyển qua từng đồng xu, nó sẽ biến mất và người chơi được thưởng mười điểm
  • Khi trò chơi tiến triển, tiền xu được thêm vào nhanh hơn
  • Trò chơi kết thúc khi có hơn mười đồng xu hiển thị trên màn hình

Khi hoàn thành, trò chơi sẽ giống như thế này

Công cụ trò chơi dựa trên văn bản Python

Bạn có thể tìm thấy mã hoàn chỉnh cho trò chơi này trong các tài liệu đã tải xuống và bên dưới

Nguồn cho

  1"""
  2Complete Game in Pygame
  3
  4This game demonstrates some of the more advanced features of
  5Pygame, including:
  6- Using sprites to render complex graphics
  7- Handling user mouse input
  8- Basic sound output
  9"""
 10
 11# Import and initialize the pygame library
 12import pygame
 13
 14# To randomize coin placement
 15from random import randint
 16
 17# To find your assets
 18from pathlib import Path
 19
 20# For type hinting
 21from typing import Tuple
 22
 23# Set the width and height of the output window, in pixels
 24WIDTH = 800
 25HEIGHT = 600
 26
 27# How quickly do you generate coins? Time is in milliseconds
 28coin_countdown = 2500
 29coin_interval = 100
 30
 31# How many coins can be on the screen before you end?
 32COIN_COUNT = 10
 33
 34# Define the Player sprite
 35class Player(pygame.sprite.Sprite):
 36    def __init__(self):
 37        """Initialize the player sprite"""
 38        super(Player, self).__init__()
 39
 40        # Get the image to draw for the player
 41        player_image = str(
 42            Path.cwd() / "pygame" / "images" / "alien_green_stand.png"
 43        )
 44        # Load the image, preserve alpha channel for transparency
 45        self.surf = pygame.image.load(player_image).convert_alpha()
 46        # Save the rect so you can move it
 47        self.rect = self.surf.get_rect()
 48
 49    def update(self, pos: Tuple):
 50        """Update the position of the player
 51
 52        Arguments:
 53            pos {Tuple} -- the (X,Y) position to move the player
 54        """
 55        self.rect.center = pos
 56
 57# Define the Coin sprite
 58class Coin(pygame.sprite.Sprite):
 59    def __init__(self):
 60        """Initialize the coin sprite"""
 61        super(Coin, self).__init__()
 62
 63        # Get the image to draw for the coin
 64        coin_image = str(Path.cwd() / "pygame" / "images" / "coin_gold.png")
 65
 66        # Load the image, preserve alpha channel for transparency
 67        self.surf = pygame.image.load(coin_image).convert_alpha()
 68
 69        # The starting position is randomly generated
 70        self.rect = self.surf.get_rect(
 71            center=(
 72                randint(10, WIDTH - 10),
 73                randint(10, HEIGHT - 10),
 74            )
 75        )
 76
 77# Initialize the Pygame engine
 78pygame.init()
 79
 80# Set up the drawing window
 81screen = pygame.display.set_mode(size=[WIDTH, HEIGHT])
 82
 83# Hide the mouse cursor
 84pygame.mouse.set_visible(False)
 85
 86# Set up the clock for a decent frame rate
 87clock = pygame.time.Clock()
 88
 89# Create a custom event for adding a new coin
 90ADDCOIN = pygame.USEREVENT + 1
 91pygame.time.set_timer(ADDCOIN, coin_countdown)
 92
 93# Set up the coin_list
 94coin_list = pygame.sprite.Group()
 95
 96# Initialize the score
 97score = 0
 98
 99# Set up the coin pickup sound
100coin_pickup_sound = pygame.mixer.Sound(
101    str(Path.cwd() / "pygame" / "sounds" / "coin_pickup.wav")
102)
103
104# Create a player sprite and set its initial position
105player = Player()
106player.update(pygame.mouse.get_pos())
107
108# Run until you get to an end condition
109running = True
110while running:
111
112    # Did the user click the window close button?
113    for event in pygame.event.get():
114        if event.type == pygame.QUIT:
115            running = False
116
117        # Should you add a new coin?
118        elif event.type == ADDCOIN:
119            # Create a new coin and add it to the coin_list
120            new_coin = Coin()
121            coin_list.add(new_coin)
122
123            # Speed things up if fewer than three coins are on-screen
124            if len(coin_list) < 3:
125                coin_countdown -= coin_interval
126            # Need to have some interval
127            if coin_countdown < 100:
128                coin_countdown = 100
129
130            # Stop the previous timer by setting the interval to 0
131            pygame.time.set_timer(ADDCOIN, 0)
132
133            # Start a new timer
134            pygame.time.set_timer(ADDCOIN, coin_countdown)
135
136    # Update the player position
137    player.update(pygame.mouse.get_pos())
138
139    # Check if the player has collided with a coin, removing the coin if so
140    coins_collected = pygame.sprite.spritecollide(
141        sprite=player, group=coin_list, dokill=True
142    )
143    for coin in coins_collected:
144        # Each coin is worth 10 points
145        score += 10
146        # Play the coin collected sound
147        coin_pickup_sound.play()
148
149    # Are there too many coins on the screen?
150    if len(coin_list) >= COIN_COUNT:
151        # This counts as an end condition, so you end your game loop
152        running = False
153
154    # To render the screen, first fill the background with pink
155    screen.fill((255, 170, 164))
156
157    # Draw the coins next
158    for coin in coin_list:
159        screen.blit(coin.surf, coin.rect)
160
161    # Then draw the player
162    screen.blit(player.surf, player.rect)
163
164    # Finally, draw the score at the bottom left
165    score_font = pygame.font.SysFont("any_font", 36)
166    score_block = score_font.render(f"Score: {score}", False, (0, 0, 0))
167    screen.blit(score_block, (50, HEIGHT - 50))
168
169    # Flip the display to make everything appear
170    pygame.display.flip()
171
172    # Ensure you maintain a 30 frames per second rate
173    clock.tick(30)
174
175# Done! Print the final score
176print(f"Game over! Final score: {score}")
177
178# Make the mouse visible again
179pygame.mouse.set_visible(True)
180
181# Quit the game
182pygame.quit()
7Hiển thị/Ẩn

  1"""
  2Complete Game in Pygame
  3
  4This game demonstrates some of the more advanced features of
  5Pygame, including:
  6- Using sprites to render complex graphics
  7- Handling user mouse input
  8- Basic sound output
  9"""
 10
 11# Import and initialize the pygame library
 12import pygame
 13
 14# To randomize coin placement
 15from random import randint
 16
 17# To find your assets
 18from pathlib import Path
 19
 20# For type hinting
 21from typing import Tuple
 22
 23# Set the width and height of the output window, in pixels
 24WIDTH = 800
 25HEIGHT = 600
 26
 27# How quickly do you generate coins? Time is in milliseconds
 28coin_countdown = 2500
 29coin_interval = 100
 30
 31# How many coins can be on the screen before you end?
 32COIN_COUNT = 10
 33
 34# Define the Player sprite
 35class Player(pygame.sprite.Sprite):
 36    def __init__(self):
 37        """Initialize the player sprite"""
 38        super(Player, self).__init__()
 39
 40        # Get the image to draw for the player
 41        player_image = str(
 42            Path.cwd() / "pygame" / "images" / "alien_green_stand.png"
 43        )
 44        # Load the image, preserve alpha channel for transparency
 45        self.surf = pygame.image.load(player_image).convert_alpha()
 46        # Save the rect so you can move it
 47        self.rect = self.surf.get_rect()
 48
 49    def update(self, pos: Tuple):
 50        """Update the position of the player
 51
 52        Arguments:
 53            pos {Tuple} -- the (X,Y) position to move the player
 54        """
 55        self.rect.center = pos
 56
 57# Define the Coin sprite
 58class Coin(pygame.sprite.Sprite):
 59    def __init__(self):
 60        """Initialize the coin sprite"""
 61        super(Coin, self).__init__()
 62
 63        # Get the image to draw for the coin
 64        coin_image = str(Path.cwd() / "pygame" / "images" / "coin_gold.png")
 65
 66        # Load the image, preserve alpha channel for transparency
 67        self.surf = pygame.image.load(coin_image).convert_alpha()
 68
 69        # The starting position is randomly generated
 70        self.rect = self.surf.get_rect(
 71            center=(
 72                randint(10, WIDTH - 10),
 73                randint(10, HEIGHT - 10),
 74            )
 75        )
 76
 77# Initialize the Pygame engine
 78pygame.init()
 79
 80# Set up the drawing window
 81screen = pygame.display.set_mode(size=[WIDTH, HEIGHT])
 82
 83# Hide the mouse cursor
 84pygame.mouse.set_visible(False)
 85
 86# Set up the clock for a decent frame rate
 87clock = pygame.time.Clock()
 88
 89# Create a custom event for adding a new coin
 90ADDCOIN = pygame.USEREVENT + 1
 91pygame.time.set_timer(ADDCOIN, coin_countdown)
 92
 93# Set up the coin_list
 94coin_list = pygame.sprite.Group()
 95
 96# Initialize the score
 97score = 0
 98
 99# Set up the coin pickup sound
100coin_pickup_sound = pygame.mixer.Sound(
101    str(Path.cwd() / "pygame" / "sounds" / "coin_pickup.wav")
102)
103
104# Create a player sprite and set its initial position
105player = Player()
106player.update(pygame.mouse.get_pos())
107
108# Run until you get to an end condition
109running = True
110while running:
111
112    # Did the user click the window close button?
113    for event in pygame.event.get():
114        if event.type == pygame.QUIT:
115            running = False
116
117        # Should you add a new coin?
118        elif event.type == ADDCOIN:
119            # Create a new coin and add it to the coin_list
120            new_coin = Coin()
121            coin_list.add(new_coin)
122
123            # Speed things up if fewer than three coins are on-screen
124            if len(coin_list) < 3:
125                coin_countdown -= coin_interval
126            # Need to have some interval
127            if coin_countdown < 100:
128                coin_countdown = 100
129
130            # Stop the previous timer by setting the interval to 0
131            pygame.time.set_timer(ADDCOIN, 0)
132
133            # Start a new timer
134            pygame.time.set_timer(ADDCOIN, coin_countdown)
135
136    # Update the player position
137    player.update(pygame.mouse.get_pos())
138
139    # Check if the player has collided with a coin, removing the coin if so
140    coins_collected = pygame.sprite.spritecollide(
141        sprite=player, group=coin_list, dokill=True
142    )
143    for coin in coins_collected:
144        # Each coin is worth 10 points
145        score += 10
146        # Play the coin collected sound
147        coin_pickup_sound.play()
148
149    # Are there too many coins on the screen?
150    if len(coin_list) >= COIN_COUNT:
151        # This counts as an end condition, so you end your game loop
152        running = False
153
154    # To render the screen, first fill the background with pink
155    screen.fill((255, 170, 164))
156
157    # Draw the coins next
158    for coin in coin_list:
159        screen.blit(coin.surf, coin.rect)
160
161    # Then draw the player
162    screen.blit(player.surf, player.rect)
163
164    # Finally, draw the score at the bottom left
165    score_font = pygame.font.SysFont("any_font", 36)
166    score_block = score_font.render(f"Score: {score}", False, (0, 0, 0))
167    screen.blit(score_block, (50, HEIGHT - 50))
168
169    # Flip the display to make everything appear
170    pygame.display.flip()
171
172    # Ensure you maintain a 30 frames per second rate
173    clock.tick(30)
174
175# Done! Print the final score
176print(f"Game over! Final score: {score}")
177
178# Make the mouse visible again
179pygame.mouse.set_visible(True)
180
181# Quit the game
182pygame.quit()

Sprites trong Pygame cung cấp một số chức năng cơ bản, nhưng chúng được thiết kế để phân lớp thay vì sử dụng riêng. Các sprite Pygame không có hình ảnh được liên kết với chúng theo mặc định và chúng không thể tự định vị chúng

Để vẽ và quản lý người chơi và đồng xu trên màn hình một cách hợp lý, một lớp

  1"""
  2Complete Game in Pygame
  3
  4This game demonstrates some of the more advanced features of
  5Pygame, including:
  6- Using sprites to render complex graphics
  7- Handling user mouse input
  8- Basic sound output
  9"""
 10
 11# Import and initialize the pygame library
 12import pygame
 13
 14# To randomize coin placement
 15from random import randint
 16
 17# To find your assets
 18from pathlib import Path
 19
 20# For type hinting
 21from typing import Tuple
 22
 23# Set the width and height of the output window, in pixels
 24WIDTH = 800
 25HEIGHT = 600
 26
 27# How quickly do you generate coins? Time is in milliseconds
 28coin_countdown = 2500
 29coin_interval = 100
 30
 31# How many coins can be on the screen before you end?
 32COIN_COUNT = 10
 33
 34# Define the Player sprite
 35class Player(pygame.sprite.Sprite):
 36    def __init__(self):
 37        """Initialize the player sprite"""
 38        super(Player, self).__init__()
 39
 40        # Get the image to draw for the player
 41        player_image = str(
 42            Path.cwd() / "pygame" / "images" / "alien_green_stand.png"
 43        )
 44        # Load the image, preserve alpha channel for transparency
 45        self.surf = pygame.image.load(player_image).convert_alpha()
 46        # Save the rect so you can move it
 47        self.rect = self.surf.get_rect()
 48
 49    def update(self, pos: Tuple):
 50        """Update the position of the player
 51
 52        Arguments:
 53            pos {Tuple} -- the (X,Y) position to move the player
 54        """
 55        self.rect.center = pos
 56
 57# Define the Coin sprite
 58class Coin(pygame.sprite.Sprite):
 59    def __init__(self):
 60        """Initialize the coin sprite"""
 61        super(Coin, self).__init__()
 62
 63        # Get the image to draw for the coin
 64        coin_image = str(Path.cwd() / "pygame" / "images" / "coin_gold.png")
 65
 66        # Load the image, preserve alpha channel for transparency
 67        self.surf = pygame.image.load(coin_image).convert_alpha()
 68
 69        # The starting position is randomly generated
 70        self.rect = self.surf.get_rect(
 71            center=(
 72                randint(10, WIDTH - 10),
 73                randint(10, HEIGHT - 10),
 74            )
 75        )
 76
 77# Initialize the Pygame engine
 78pygame.init()
 79
 80# Set up the drawing window
 81screen = pygame.display.set_mode(size=[WIDTH, HEIGHT])
 82
 83# Hide the mouse cursor
 84pygame.mouse.set_visible(False)
 85
 86# Set up the clock for a decent frame rate
 87clock = pygame.time.Clock()
 88
 89# Create a custom event for adding a new coin
 90ADDCOIN = pygame.USEREVENT + 1
 91pygame.time.set_timer(ADDCOIN, coin_countdown)
 92
 93# Set up the coin_list
 94coin_list = pygame.sprite.Group()
 95
 96# Initialize the score
 97score = 0
 98
 99# Set up the coin pickup sound
100coin_pickup_sound = pygame.mixer.Sound(
101    str(Path.cwd() / "pygame" / "sounds" / "coin_pickup.wav")
102)
103
104# Create a player sprite and set its initial position
105player = Player()
106player.update(pygame.mouse.get_pos())
107
108# Run until you get to an end condition
109running = True
110while running:
111
112    # Did the user click the window close button?
113    for event in pygame.event.get():
114        if event.type == pygame.QUIT:
115            running = False
116
117        # Should you add a new coin?
118        elif event.type == ADDCOIN:
119            # Create a new coin and add it to the coin_list
120            new_coin = Coin()
121            coin_list.add(new_coin)
122
123            # Speed things up if fewer than three coins are on-screen
124            if len(coin_list) < 3:
125                coin_countdown -= coin_interval
126            # Need to have some interval
127            if coin_countdown < 100:
128                coin_countdown = 100
129
130            # Stop the previous timer by setting the interval to 0
131            pygame.time.set_timer(ADDCOIN, 0)
132
133            # Start a new timer
134            pygame.time.set_timer(ADDCOIN, coin_countdown)
135
136    # Update the player position
137    player.update(pygame.mouse.get_pos())
138
139    # Check if the player has collided with a coin, removing the coin if so
140    coins_collected = pygame.sprite.spritecollide(
141        sprite=player, group=coin_list, dokill=True
142    )
143    for coin in coins_collected:
144        # Each coin is worth 10 points
145        score += 10
146        # Play the coin collected sound
147        coin_pickup_sound.play()
148
149    # Are there too many coins on the screen?
150    if len(coin_list) >= COIN_COUNT:
151        # This counts as an end condition, so you end your game loop
152        running = False
153
154    # To render the screen, first fill the background with pink
155    screen.fill((255, 170, 164))
156
157    # Draw the coins next
158    for coin in coin_list:
159        screen.blit(coin.surf, coin.rect)
160
161    # Then draw the player
162    screen.blit(player.surf, player.rect)
163
164    # Finally, draw the score at the bottom left
165    score_font = pygame.font.SysFont("any_font", 36)
166    score_block = score_font.render(f"Score: {score}", False, (0, 0, 0))
167    screen.blit(score_block, (50, HEIGHT - 50))
168
169    # Flip the display to make everything appear
170    pygame.display.flip()
171
172    # Ensure you maintain a 30 frames per second rate
173    clock.tick(30)
174
175# Done! Print the final score
176print(f"Game over! Final score: {score}")
177
178# Make the mouse visible again
179pygame.mouse.set_visible(True)
180
181# Quit the game
182pygame.quit()
8 được tạo trên các dòng 35 đến 55 và một lớp
  1"""
  2Complete Game in Pygame
  3
  4This game demonstrates some of the more advanced features of
  5Pygame, including:
  6- Using sprites to render complex graphics
  7- Handling user mouse input
  8- Basic sound output
  9"""
 10
 11# Import and initialize the pygame library
 12import pygame
 13
 14# To randomize coin placement
 15from random import randint
 16
 17# To find your assets
 18from pathlib import Path
 19
 20# For type hinting
 21from typing import Tuple
 22
 23# Set the width and height of the output window, in pixels
 24WIDTH = 800
 25HEIGHT = 600
 26
 27# How quickly do you generate coins? Time is in milliseconds
 28coin_countdown = 2500
 29coin_interval = 100
 30
 31# How many coins can be on the screen before you end?
 32COIN_COUNT = 10
 33
 34# Define the Player sprite
 35class Player(pygame.sprite.Sprite):
 36    def __init__(self):
 37        """Initialize the player sprite"""
 38        super(Player, self).__init__()
 39
 40        # Get the image to draw for the player
 41        player_image = str(
 42            Path.cwd() / "pygame" / "images" / "alien_green_stand.png"
 43        )
 44        # Load the image, preserve alpha channel for transparency
 45        self.surf = pygame.image.load(player_image).convert_alpha()
 46        # Save the rect so you can move it
 47        self.rect = self.surf.get_rect()
 48
 49    def update(self, pos: Tuple):
 50        """Update the position of the player
 51
 52        Arguments:
 53            pos {Tuple} -- the (X,Y) position to move the player
 54        """
 55        self.rect.center = pos
 56
 57# Define the Coin sprite
 58class Coin(pygame.sprite.Sprite):
 59    def __init__(self):
 60        """Initialize the coin sprite"""
 61        super(Coin, self).__init__()
 62
 63        # Get the image to draw for the coin
 64        coin_image = str(Path.cwd() / "pygame" / "images" / "coin_gold.png")
 65
 66        # Load the image, preserve alpha channel for transparency
 67        self.surf = pygame.image.load(coin_image).convert_alpha()
 68
 69        # The starting position is randomly generated
 70        self.rect = self.surf.get_rect(
 71            center=(
 72                randint(10, WIDTH - 10),
 73                randint(10, HEIGHT - 10),
 74            )
 75        )
 76
 77# Initialize the Pygame engine
 78pygame.init()
 79
 80# Set up the drawing window
 81screen = pygame.display.set_mode(size=[WIDTH, HEIGHT])
 82
 83# Hide the mouse cursor
 84pygame.mouse.set_visible(False)
 85
 86# Set up the clock for a decent frame rate
 87clock = pygame.time.Clock()
 88
 89# Create a custom event for adding a new coin
 90ADDCOIN = pygame.USEREVENT + 1
 91pygame.time.set_timer(ADDCOIN, coin_countdown)
 92
 93# Set up the coin_list
 94coin_list = pygame.sprite.Group()
 95
 96# Initialize the score
 97score = 0
 98
 99# Set up the coin pickup sound
100coin_pickup_sound = pygame.mixer.Sound(
101    str(Path.cwd() / "pygame" / "sounds" / "coin_pickup.wav")
102)
103
104# Create a player sprite and set its initial position
105player = Player()
106player.update(pygame.mouse.get_pos())
107
108# Run until you get to an end condition
109running = True
110while running:
111
112    # Did the user click the window close button?
113    for event in pygame.event.get():
114        if event.type == pygame.QUIT:
115            running = False
116
117        # Should you add a new coin?
118        elif event.type == ADDCOIN:
119            # Create a new coin and add it to the coin_list
120            new_coin = Coin()
121            coin_list.add(new_coin)
122
123            # Speed things up if fewer than three coins are on-screen
124            if len(coin_list) < 3:
125                coin_countdown -= coin_interval
126            # Need to have some interval
127            if coin_countdown < 100:
128                coin_countdown = 100
129
130            # Stop the previous timer by setting the interval to 0
131            pygame.time.set_timer(ADDCOIN, 0)
132
133            # Start a new timer
134            pygame.time.set_timer(ADDCOIN, coin_countdown)
135
136    # Update the player position
137    player.update(pygame.mouse.get_pos())
138
139    # Check if the player has collided with a coin, removing the coin if so
140    coins_collected = pygame.sprite.spritecollide(
141        sprite=player, group=coin_list, dokill=True
142    )
143    for coin in coins_collected:
144        # Each coin is worth 10 points
145        score += 10
146        # Play the coin collected sound
147        coin_pickup_sound.play()
148
149    # Are there too many coins on the screen?
150    if len(coin_list) >= COIN_COUNT:
151        # This counts as an end condition, so you end your game loop
152        running = False
153
154    # To render the screen, first fill the background with pink
155    screen.fill((255, 170, 164))
156
157    # Draw the coins next
158    for coin in coin_list:
159        screen.blit(coin.surf, coin.rect)
160
161    # Then draw the player
162    screen.blit(player.surf, player.rect)
163
164    # Finally, draw the score at the bottom left
165    score_font = pygame.font.SysFont("any_font", 36)
166    score_block = score_font.render(f"Score: {score}", False, (0, 0, 0))
167    screen.blit(score_block, (50, HEIGHT - 50))
168
169    # Flip the display to make everything appear
170    pygame.display.flip()
171
172    # Ensure you maintain a 30 frames per second rate
173    clock.tick(30)
174
175# Done! Print the final score
176print(f"Game over! Final score: {score}")
177
178# Make the mouse visible again
179pygame.mouse.set_visible(True)
180
181# Quit the game
182pygame.quit()
9 trên các dòng 58 đến 75. Khi mỗi đối tượng sprite được tạo, đầu tiên nó định vị và tải hình ảnh mà nó sẽ hiển thị, lưu nó vào
(venv) $ python -m pip install pgzero
0. Thuộc tính
(venv) $ python -m pip install pgzero
1 định vị và di chuyển sprite trên màn hình

Việc thêm tiền vào màn hình đều đặn được thực hiện bằng đồng hồ bấm giờ. Trong Pygame, các sự kiện được kích hoạt bất cứ khi nào hết giờ và người tạo trò chơi có thể xác định các sự kiện của riêng họ dưới dạng hằng số nguyên. Sự kiện

(venv) $ python -m pip install pgzero
2 được xác định trên dòng 90 và bộ hẹn giờ kích hoạt sự kiện sau
(venv) $ python -m pip install pgzero
3 mili giây trên dòng 91

(venv) $ python -m pip install pgzero
2 là một sự kiện nên nó cần được xử lý trong một vòng lặp sự kiện, xảy ra ở các dòng 118 đến 134. Sự kiện tạo một đối tượng
  1"""
  2Complete Game in Pygame
  3
  4This game demonstrates some of the more advanced features of
  5Pygame, including:
  6- Using sprites to render complex graphics
  7- Handling user mouse input
  8- Basic sound output
  9"""
 10
 11# Import and initialize the pygame library
 12import pygame
 13
 14# To randomize coin placement
 15from random import randint
 16
 17# To find your assets
 18from pathlib import Path
 19
 20# For type hinting
 21from typing import Tuple
 22
 23# Set the width and height of the output window, in pixels
 24WIDTH = 800
 25HEIGHT = 600
 26
 27# How quickly do you generate coins? Time is in milliseconds
 28coin_countdown = 2500
 29coin_interval = 100
 30
 31# How many coins can be on the screen before you end?
 32COIN_COUNT = 10
 33
 34# Define the Player sprite
 35class Player(pygame.sprite.Sprite):
 36    def __init__(self):
 37        """Initialize the player sprite"""
 38        super(Player, self).__init__()
 39
 40        # Get the image to draw for the player
 41        player_image = str(
 42            Path.cwd() / "pygame" / "images" / "alien_green_stand.png"
 43        )
 44        # Load the image, preserve alpha channel for transparency
 45        self.surf = pygame.image.load(player_image).convert_alpha()
 46        # Save the rect so you can move it
 47        self.rect = self.surf.get_rect()
 48
 49    def update(self, pos: Tuple):
 50        """Update the position of the player
 51
 52        Arguments:
 53            pos {Tuple} -- the (X,Y) position to move the player
 54        """
 55        self.rect.center = pos
 56
 57# Define the Coin sprite
 58class Coin(pygame.sprite.Sprite):
 59    def __init__(self):
 60        """Initialize the coin sprite"""
 61        super(Coin, self).__init__()
 62
 63        # Get the image to draw for the coin
 64        coin_image = str(Path.cwd() / "pygame" / "images" / "coin_gold.png")
 65
 66        # Load the image, preserve alpha channel for transparency
 67        self.surf = pygame.image.load(coin_image).convert_alpha()
 68
 69        # The starting position is randomly generated
 70        self.rect = self.surf.get_rect(
 71            center=(
 72                randint(10, WIDTH - 10),
 73                randint(10, HEIGHT - 10),
 74            )
 75        )
 76
 77# Initialize the Pygame engine
 78pygame.init()
 79
 80# Set up the drawing window
 81screen = pygame.display.set_mode(size=[WIDTH, HEIGHT])
 82
 83# Hide the mouse cursor
 84pygame.mouse.set_visible(False)
 85
 86# Set up the clock for a decent frame rate
 87clock = pygame.time.Clock()
 88
 89# Create a custom event for adding a new coin
 90ADDCOIN = pygame.USEREVENT + 1
 91pygame.time.set_timer(ADDCOIN, coin_countdown)
 92
 93# Set up the coin_list
 94coin_list = pygame.sprite.Group()
 95
 96# Initialize the score
 97score = 0
 98
 99# Set up the coin pickup sound
100coin_pickup_sound = pygame.mixer.Sound(
101    str(Path.cwd() / "pygame" / "sounds" / "coin_pickup.wav")
102)
103
104# Create a player sprite and set its initial position
105player = Player()
106player.update(pygame.mouse.get_pos())
107
108# Run until you get to an end condition
109running = True
110while running:
111
112    # Did the user click the window close button?
113    for event in pygame.event.get():
114        if event.type == pygame.QUIT:
115            running = False
116
117        # Should you add a new coin?
118        elif event.type == ADDCOIN:
119            # Create a new coin and add it to the coin_list
120            new_coin = Coin()
121            coin_list.add(new_coin)
122
123            # Speed things up if fewer than three coins are on-screen
124            if len(coin_list) < 3:
125                coin_countdown -= coin_interval
126            # Need to have some interval
127            if coin_countdown < 100:
128                coin_countdown = 100
129
130            # Stop the previous timer by setting the interval to 0
131            pygame.time.set_timer(ADDCOIN, 0)
132
133            # Start a new timer
134            pygame.time.set_timer(ADDCOIN, coin_countdown)
135
136    # Update the player position
137    player.update(pygame.mouse.get_pos())
138
139    # Check if the player has collided with a coin, removing the coin if so
140    coins_collected = pygame.sprite.spritecollide(
141        sprite=player, group=coin_list, dokill=True
142    )
143    for coin in coins_collected:
144        # Each coin is worth 10 points
145        score += 10
146        # Play the coin collected sound
147        coin_pickup_sound.play()
148
149    # Are there too many coins on the screen?
150    if len(coin_list) >= COIN_COUNT:
151        # This counts as an end condition, so you end your game loop
152        running = False
153
154    # To render the screen, first fill the background with pink
155    screen.fill((255, 170, 164))
156
157    # Draw the coins next
158    for coin in coin_list:
159        screen.blit(coin.surf, coin.rect)
160
161    # Then draw the player
162    screen.blit(player.surf, player.rect)
163
164    # Finally, draw the score at the bottom left
165    score_font = pygame.font.SysFont("any_font", 36)
166    score_block = score_font.render(f"Score: {score}", False, (0, 0, 0))
167    screen.blit(score_block, (50, HEIGHT - 50))
168
169    # Flip the display to make everything appear
170    pygame.display.flip()
171
172    # Ensure you maintain a 30 frames per second rate
173    clock.tick(30)
174
175# Done! Print the final score
176print(f"Game over! Final score: {score}")
177
178# Make the mouse visible again
179pygame.mouse.set_visible(True)
180
181# Quit the game
182pygame.quit()
9 mới và thêm nó vào đối tượng
(venv) $ python -m pip install pgzero
6 hiện có. Số lượng xu trên màn hình được kiểm tra. Nếu có ít hơn ba, thì
(venv) $ python -m pip install pgzero
3 bị giảm. Cuối cùng, bộ đếm thời gian trước đó bị dừng và một bộ đếm thời gian mới bắt đầu

Khi người chơi di chuyển, họ va chạm với các đồng xu, thu thập chúng khi họ làm. Thao tác này sẽ tự động xóa từng đồng xu đã thu thập khỏi

(venv) $ python -m pip install pgzero
6. Thao tác này cũng cập nhật điểm số và phát âm thanh

Chuyển động của người chơi xảy ra trên dòng 137. Các va chạm với đồng xu trên màn hình được kiểm tra trên các dòng 140 đến 142. Tham số

(venv) $ python -m pip install pgzero
9 sẽ tự động xóa đồng xu khỏi
(venv) $ python -m pip install pgzero
6. Cuối cùng, dòng 143 đến 147 cập nhật tỷ số và phát âm thanh cho mỗi đồng xu thu được

Trò chơi kết thúc khi người dùng đóng cửa sổ hoặc khi có hơn mười đồng xu trên màn hình. Kiểm tra hơn mười xu được thực hiện trên các dòng 150 đến 152

Bởi vì các nhân vật Pygame không có kiến ​​thức tích hợp về hình ảnh, nên họ cũng không biết cách tự vẽ mình trên màn hình. Tác giả trò chơi cần xóa màn hình, vẽ tất cả các họa tiết theo đúng thứ tự, vẽ điểm số trên màn hình, sau đó

 1"""
 2Basic "Hello, World!" program in Pygame Zero
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame Zero. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10"""
11
12# Import pgzrun allows the program to run in Python IDLE
13import pgzrun
14
15# Set the width and height of your output window, in pixels
16WIDTH = 800
17HEIGHT = 600
18
19def draw():
20    """Draw is called once per frame to render everything on the screen"""
21
22    # Clear the screen first
23    screen.clear()
24
25    # Set the background color to white
26    screen.fill("white")
27
28    # Draw a blue circle with a radius of 50 in the center of the screen
29    screen.draw.filled_circle(
30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
31    )
32
33    # Draw a red-outlined square in the top-left corner of the screen
34    red_square = Rect((50, 50), (100, 100))
35    screen.draw.rect(red_square, (200, 0, 0))
36
37    # Draw an orange caption along the bottom in 60-point font
38    screen.draw.text(
39        "Hello, World! From Pygame Zero!",
40        (100, HEIGHT - 50),
41        fontsize=60,
42        color="orange",
43    )
44
45# Run the program
46pgzrun.go()
1 màn hình để mọi thứ xuất hiện. Tất cả điều đó xảy ra trên các dòng 155 đến 170

Pygame là một thư viện rất mạnh và được thiết lập tốt, nhưng nó cũng có nhược điểm. Pygame khiến các tác giả trò chơi làm việc để đạt được kết quả của họ. Tác giả trò chơi có thể thực hiện hành vi sprite cơ bản và thực hiện các yêu cầu chính của trò chơi như vòng lặp trò chơi và trình xử lý sự kiện cơ bản tùy thuộc vào tác giả trò chơi. Tiếp theo, bạn sẽ thấy các công cụ trò chơi khác mang lại kết quả tương tự như thế nào trong khi giảm khối lượng công việc bạn phải làm

trò chơi số không

Có nhiều điều Pygame làm tốt, nhưng những điều khác mà tuổi của nó là hiển nhiên. Đối với những người mới bắt đầu viết trò chơi, có thể tìm thấy một tùy chọn tốt hơn trong Pygame Zero. Được thiết kế cho giáo dục, Pygame Zero được hướng dẫn bởi một bộ nguyên tắc đơn giản nhằm mục đích trở nên hoàn hảo cho các lập trình viên trẻ và mới bắt đầu

  • Làm cho nó có thể truy cập. Tất cả mọi thứ được thiết kế cho các lập trình viên mới bắt đầu
  • Hãy bảo thủ. Hỗ trợ nền tảng chung và tránh các tính năng thử nghiệm
  • chỉ cần làm việc. Đảm bảo mọi thứ hoạt động trơn tru
  • Giảm thiểu chi phí thời gian chạy. Nếu một cái gì đó có thể thất bại, thất bại sớm
  • Lỗi rõ ràng. Không có gì tệ hơn là không biết tại sao lại xảy ra sự cố
  • tài liệu tốt. Một khung chỉ tốt như tài liệu của nó
  • Giảm thiểu các thay đổi vi phạm. Nâng cấp không nên yêu cầu viết lại trò chơi của bạn

Tài liệu dành cho Pygame Zero rất dễ tiếp cận đối với những người mới bắt đầu lập trình và nó bao gồm một hướng dẫn từng bước hoàn chỉnh. Hơn nữa, nhóm Pygame Zero nhận ra rằng nhiều lập trình viên mới bắt đầu viết mã bằng Scratch, vì vậy họ cung cấp hướng dẫn minh họa cách di chuyển chương trình Scratch sang Pygame Zero

Remove ads

Cài đặt Pygame Zero

Pygame Zero có sẵn trên PyPI và bạn có thể cài đặt nó giống như bất kỳ thư viện Python nào khác trên Windows, macOS hoặc Linux

(venv) $ python -m pip install pgzero

Pygame Zero, đúng như tên gọi, được xây dựng dựa trên Pygame nên bước này cũng cài đặt Pygame như một thư viện phụ thuộc. Pygame Zero được cài đặt theo mặc định trên nền tảng Raspberry Pi, trên Raspbian Jessie hoặc bản phát hành mới hơn

Basic Concepts

Pygame Zero tự động hóa nhiều thứ mà lập trình viên phải làm thủ công trong Pygame. Theo mặc định, Pygame Zero cung cấp cho người tạo trò chơi

  • Một vòng lặp trò chơi, vì vậy không cần phải viết một vòng lặp
  • Một mô hình sự kiện để xử lý bản vẽ, cập nhật và xử lý đầu vào
  • Xử lý hình ảnh, văn bản và âm thanh thống nhất
  • Một lớp sprite có thể sử dụng và các phương thức hoạt ảnh hữu ích cho các sprite của người dùng

Do những điều khoản này, một chương trình Pygame Zero cơ bản có thể rất ngắn

Nguồn cho

 1"""
 2Basic "Hello, World!" program in Pygame Zero
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame Zero. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10"""
11
12# Import pgzrun allows the program to run in Python IDLE
13import pgzrun
14
15# Set the width and height of your output window, in pixels
16WIDTH = 800
17HEIGHT = 600
18
19def draw():
20    """Draw is called once per frame to render everything on the screen"""
21
22    # Clear the screen first
23    screen.clear()
24
25    # Set the background color to white
26    screen.fill("white")
27
28    # Draw a blue circle with a radius of 50 in the center of the screen
29    screen.draw.filled_circle(
30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
31    )
32
33    # Draw a red-outlined square in the top-left corner of the screen
34    red_square = Rect((50, 50), (100, 100))
35    screen.draw.rect(red_square, (200, 0, 0))
36
37    # Draw an orange caption along the bottom in 60-point font
38    screen.draw.text(
39        "Hello, World! From Pygame Zero!",
40        (100, HEIGHT - 50),
41        fontsize=60,
42        color="orange",
43    )
44
45# Run the program
46pgzrun.go()
2Hiển thị/Ẩn

 1"""
 2Basic "Hello, World!" program in Pygame Zero
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame Zero. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10"""
11
12# Import pgzrun allows the program to run in Python IDLE
13import pgzrun
14
15# Set the width and height of your output window, in pixels
16WIDTH = 800
17HEIGHT = 600
18
19def draw():
20    """Draw is called once per frame to render everything on the screen"""
21
22    # Clear the screen first
23    screen.clear()
24
25    # Set the background color to white
26    screen.fill("white")
27
28    # Draw a blue circle with a radius of 50 in the center of the screen
29    screen.draw.filled_circle(
30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
31    )
32
33    # Draw a red-outlined square in the top-left corner of the screen
34    red_square = Rect((50, 50), (100, 100))
35    screen.draw.rect(red_square, (200, 0, 0))
36
37    # Draw an orange caption along the bottom in 60-point font
38    screen.draw.text(
39        "Hello, World! From Pygame Zero!",
40        (100, HEIGHT - 50),
41        fontsize=60,
42        color="orange",
43    )
44
45# Run the program
46pgzrun.go()

Pygame Zero nhận ra rằng các hằng số

 1"""
 2Basic "Hello, World!" program in Pygame Zero
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame Zero. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10"""
11
12# Import pgzrun allows the program to run in Python IDLE
13import pgzrun
14
15# Set the width and height of your output window, in pixels
16WIDTH = 800
17HEIGHT = 600
18
19def draw():
20    """Draw is called once per frame to render everything on the screen"""
21
22    # Clear the screen first
23    screen.clear()
24
25    # Set the background color to white
26    screen.fill("white")
27
28    # Draw a blue circle with a radius of 50 in the center of the screen
29    screen.draw.filled_circle(
30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
31    )
32
33    # Draw a red-outlined square in the top-left corner of the screen
34    red_square = Rect((50, 50), (100, 100))
35    screen.draw.rect(red_square, (200, 0, 0))
36
37    # Draw an orange caption along the bottom in 60-point font
38    screen.draw.text(
39        "Hello, World! From Pygame Zero!",
40        (100, HEIGHT - 50),
41        fontsize=60,
42        color="orange",
43    )
44
45# Run the program
46pgzrun.go()
3 và
 1"""
 2Basic "Hello, World!" program in Pygame Zero
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame Zero. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10"""
11
12# Import pgzrun allows the program to run in Python IDLE
13import pgzrun
14
15# Set the width and height of your output window, in pixels
16WIDTH = 800
17HEIGHT = 600
18
19def draw():
20    """Draw is called once per frame to render everything on the screen"""
21
22    # Clear the screen first
23    screen.clear()
24
25    # Set the background color to white
26    screen.fill("white")
27
28    # Draw a blue circle with a radius of 50 in the center of the screen
29    screen.draw.filled_circle(
30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
31    )
32
33    # Draw a red-outlined square in the top-left corner of the screen
34    red_square = Rect((50, 50), (100, 100))
35    screen.draw.rect(red_square, (200, 0, 0))
36
37    # Draw an orange caption along the bottom in 60-point font
38    screen.draw.text(
39        "Hello, World! From Pygame Zero!",
40        (100, HEIGHT - 50),
41        fontsize=60,
42        color="orange",
43    )
44
45# Run the program
46pgzrun.go()
4 trên các dòng 16 và 17 đề cập đến kích thước của cửa sổ và tự động sử dụng các kích thước đó để tạo ra nó. Ngoài ra, Pygame Zero cung cấp vòng lặp trò chơi tích hợp và gọi hàm
 1"""
 2Basic "Hello, World!" program in Pygame Zero
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame Zero. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10"""
11
12# Import pgzrun allows the program to run in Python IDLE
13import pgzrun
14
15# Set the width and height of your output window, in pixels
16WIDTH = 800
17HEIGHT = 600
18
19def draw():
20    """Draw is called once per frame to render everything on the screen"""
21
22    # Clear the screen first
23    screen.clear()
24
25    # Set the background color to white
26    screen.fill("white")
27
28    # Draw a blue circle with a radius of 50 in the center of the screen
29    screen.draw.filled_circle(
30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
31    )
32
33    # Draw a red-outlined square in the top-left corner of the screen
34    red_square = Rect((50, 50), (100, 100))
35    screen.draw.rect(red_square, (200, 0, 0))
36
37    # Draw an orange caption along the bottom in 60-point font
38    screen.draw.text(
39        "Hello, World! From Pygame Zero!",
40        (100, HEIGHT - 50),
41        fontsize=60,
42        color="orange",
43    )
44
45# Run the program
46pgzrun.go()
5 được xác định trên các dòng 19 đến 43 một lần trên mỗi khung hình để hiển thị màn hình

Vì Pygame Zero dựa trên Pygame nên một số mã vẽ hình được kế thừa. Bạn có thể thấy sự giống nhau khi vẽ hình tròn ở dòng 29 và hình vuông ở dòng 34 đến 35

Công cụ trò chơi dựa trên văn bản Python

Tuy nhiên, vẽ văn bản hiện là một lệnh gọi hàm duy nhất trên các dòng 38 đến 43, thay vì ba hàm riêng biệt

Pygame Zero cũng cung cấp mã xử lý cửa sổ cơ bản, vì vậy bạn có thể đóng cửa sổ bằng cách nhấp vào nút đóng thích hợp mà không yêu cầu trình xử lý sự kiện

Bạn có thể tìm mã thể hiện một số khả năng cơ bản của Pygame Zero trong các tài liệu có thể tải xuống

Get Source Code. Click here to get the source code you’ll use to try out Python game engines

Chạy các chương trình Pygame Zero được thực hiện từ dòng lệnh bằng lệnh

(venv) $ python pygame_zero/pygame_zero_basic.py

Chạy lệnh này sẽ bắt đầu trò chơi Pygame Zero của bạn. Bạn sẽ thấy một cửa sổ xuất hiện với các hình dạng cơ bản và lời chào Pygame Zero của bạn

Sprites và hình ảnh

Các nhân vật được gọi là Diễn viên trong Pygame Zero và họ có một vài đặc điểm cần được giải thích

  1. Pygame Zero cung cấp lớp
     1"""
     2Basic "Hello, World!" program in Pygame Zero
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame Zero. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10"""
    11
    12# Import pgzrun allows the program to run in Python IDLE
    13import pgzrun
    14
    15# Set the width and height of your output window, in pixels
    16WIDTH = 800
    17HEIGHT = 600
    18
    19def draw():
    20    """Draw is called once per frame to render everything on the screen"""
    21
    22    # Clear the screen first
    23    screen.clear()
    24
    25    # Set the background color to white
    26    screen.fill("white")
    27
    28    # Draw a blue circle with a radius of 50 in the center of the screen
    29    screen.draw.filled_circle(
    30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
    31    )
    32
    33    # Draw a red-outlined square in the top-left corner of the screen
    34    red_square = Rect((50, 50), (100, 100))
    35    screen.draw.rect(red_square, (200, 0, 0))
    36
    37    # Draw an orange caption along the bottom in 60-point font
    38    screen.draw.text(
    39        "Hello, World! From Pygame Zero!",
    40        (100, HEIGHT - 50),
    41        fontsize=60,
    42        color="orange",
    43    )
    44
    45# Run the program
    46pgzrun.go()
    
    6. Mỗi
     1"""
     2Basic "Hello, World!" program in Pygame Zero
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame Zero. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10"""
    11
    12# Import pgzrun allows the program to run in Python IDLE
    13import pgzrun
    14
    15# Set the width and height of your output window, in pixels
    16WIDTH = 800
    17HEIGHT = 600
    18
    19def draw():
    20    """Draw is called once per frame to render everything on the screen"""
    21
    22    # Clear the screen first
    23    screen.clear()
    24
    25    # Set the background color to white
    26    screen.fill("white")
    27
    28    # Draw a blue circle with a radius of 50 in the center of the screen
    29    screen.draw.filled_circle(
    30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
    31    )
    32
    33    # Draw a red-outlined square in the top-left corner of the screen
    34    red_square = Rect((50, 50), (100, 100))
    35    screen.draw.rect(red_square, (200, 0, 0))
    36
    37    # Draw an orange caption along the bottom in 60-point font
    38    screen.draw.text(
    39        "Hello, World! From Pygame Zero!",
    40        (100, HEIGHT - 50),
    41        fontsize=60,
    42        color="orange",
    43    )
    44
    45# Run the program
    46pgzrun.go()
    
    6 có tối thiểu một hình ảnh và một vị trí
  2. Tất cả hình ảnh được sử dụng trong chương trình Pygame Zero phải được đặt trong thư mục con có tên là
     1"""
     2Basic "Hello, World!" program in Pygame Zero
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame Zero. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10"""
    11
    12# Import pgzrun allows the program to run in Python IDLE
    13import pgzrun
    14
    15# Set the width and height of your output window, in pixels
    16WIDTH = 800
    17HEIGHT = 600
    18
    19def draw():
    20    """Draw is called once per frame to render everything on the screen"""
    21
    22    # Clear the screen first
    23    screen.clear()
    24
    25    # Set the background color to white
    26    screen.fill("white")
    27
    28    # Draw a blue circle with a radius of 50 in the center of the screen
    29    screen.draw.filled_circle(
    30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
    31    )
    32
    33    # Draw a red-outlined square in the top-left corner of the screen
    34    red_square = Rect((50, 50), (100, 100))
    35    screen.draw.rect(red_square, (200, 0, 0))
    36
    37    # Draw an orange caption along the bottom in 60-point font
    38    screen.draw.text(
    39        "Hello, World! From Pygame Zero!",
    40        (100, HEIGHT - 50),
    41        fontsize=60,
    42        color="orange",
    43    )
    44
    45# Run the program
    46pgzrun.go()
    
    8 và chỉ được đặt tên bằng chữ thường, số và dấu gạch dưới
  3. Hình ảnh được tham chiếu chỉ bằng tên cơ sở của hình ảnh. Ví dụ: nếu hình ảnh của bạn có tên là
     1"""
     2Basic "Hello, World!" program in Pygame Zero
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame Zero. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10"""
    11
    12# Import pgzrun allows the program to run in Python IDLE
    13import pgzrun
    14
    15# Set the width and height of your output window, in pixels
    16WIDTH = 800
    17HEIGHT = 600
    18
    19def draw():
    20    """Draw is called once per frame to render everything on the screen"""
    21
    22    # Clear the screen first
    23    screen.clear()
    24
    25    # Set the background color to white
    26    screen.fill("white")
    27
    28    # Draw a blue circle with a radius of 50 in the center of the screen
    29    screen.draw.filled_circle(
    30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
    31    )
    32
    33    # Draw a red-outlined square in the top-left corner of the screen
    34    red_square = Rect((50, 50), (100, 100))
    35    screen.draw.rect(red_square, (200, 0, 0))
    36
    37    # Draw an orange caption along the bottom in 60-point font
    38    screen.draw.text(
    39        "Hello, World! From Pygame Zero!",
    40        (100, HEIGHT - 50),
    41        fontsize=60,
    42        color="orange",
    43    )
    44
    45# Run the program
    46pgzrun.go()
    
    9, thì bạn tham chiếu nó trong chương trình của mình là
    (venv) $ python pygame_zero/pygame_zero_basic.py
    
    0

Do các tính năng tích hợp này của Pygame Zero, việc vẽ các họa tiết trên màn hình cần rất ít mã

 1alien = Actor("alien")
 2alien.pos = 100, 56
 3
 4WIDTH = 500
 5HEIGHT = alien.height + 20
 6
 7def draw():
 8    screen.clear()
 9    alien.draw()

Bây giờ bạn sẽ chia mẫu nhỏ này xuống từng dòng

  • Dòng 1 tạo đối tượng
     1"""
     2Basic "Hello, World!" program in Pygame Zero
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame Zero. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10"""
    11
    12# Import pgzrun allows the program to run in Python IDLE
    13import pgzrun
    14
    15# Set the width and height of your output window, in pixels
    16WIDTH = 800
    17HEIGHT = 600
    18
    19def draw():
    20    """Draw is called once per frame to render everything on the screen"""
    21
    22    # Clear the screen first
    23    screen.clear()
    24
    25    # Set the background color to white
    26    screen.fill("white")
    27
    28    # Draw a blue circle with a radius of 50 in the center of the screen
    29    screen.draw.filled_circle(
    30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
    31    )
    32
    33    # Draw a red-outlined square in the top-left corner of the screen
    34    red_square = Rect((50, 50), (100, 100))
    35    screen.draw.rect(red_square, (200, 0, 0))
    36
    37    # Draw an orange caption along the bottom in 60-point font
    38    screen.draw.text(
    39        "Hello, World! From Pygame Zero!",
    40        (100, HEIGHT - 50),
    41        fontsize=60,
    42        color="orange",
    43    )
    44
    45# Run the program
    46pgzrun.go()
    
    6 mới, đặt cho nó tên của hình ảnh để vẽ
  • Dòng 2 đặt vị trí x và y ban đầu của
     1"""
     2Basic "Hello, World!" program in Pygame Zero
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame Zero. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10"""
    11
    12# Import pgzrun allows the program to run in Python IDLE
    13import pgzrun
    14
    15# Set the width and height of your output window, in pixels
    16WIDTH = 800
    17HEIGHT = 600
    18
    19def draw():
    20    """Draw is called once per frame to render everything on the screen"""
    21
    22    # Clear the screen first
    23    screen.clear()
    24
    25    # Set the background color to white
    26    screen.fill("white")
    27
    28    # Draw a blue circle with a radius of 50 in the center of the screen
    29    screen.draw.filled_circle(
    30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
    31    )
    32
    33    # Draw a red-outlined square in the top-left corner of the screen
    34    red_square = Rect((50, 50), (100, 100))
    35    screen.draw.rect(red_square, (200, 0, 0))
    36
    37    # Draw an orange caption along the bottom in 60-point font
    38    screen.draw.text(
    39        "Hello, World! From Pygame Zero!",
    40        (100, HEIGHT - 50),
    41        fontsize=60,
    42        color="orange",
    43    )
    44
    45# Run the program
    46pgzrun.go()
    
    6
  • Dòng 4 và 5 đặt kích thước của cửa sổ Pygame Zero. Lưu ý rằng
     1"""
     2Basic "Hello, World!" program in Pygame Zero
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame Zero. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10"""
    11
    12# Import pgzrun allows the program to run in Python IDLE
    13import pgzrun
    14
    15# Set the width and height of your output window, in pixels
    16WIDTH = 800
    17HEIGHT = 600
    18
    19def draw():
    20    """Draw is called once per frame to render everything on the screen"""
    21
    22    # Clear the screen first
    23    screen.clear()
    24
    25    # Set the background color to white
    26    screen.fill("white")
    27
    28    # Draw a blue circle with a radius of 50 in the center of the screen
    29    screen.draw.filled_circle(
    30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
    31    )
    32
    33    # Draw a red-outlined square in the top-left corner of the screen
    34    red_square = Rect((50, 50), (100, 100))
    35    screen.draw.rect(red_square, (200, 0, 0))
    36
    37    # Draw an orange caption along the bottom in 60-point font
    38    screen.draw.text(
    39        "Hello, World! From Pygame Zero!",
    40        (100, HEIGHT - 50),
    41        fontsize=60,
    42        color="orange",
    43    )
    44
    45# Run the program
    46pgzrun.go()
    
    4 dựa trên thuộc tính
    (venv) $ python pygame_zero/pygame_zero_basic.py
    
    4 của sprite. Giá trị này xuất phát từ chiều cao của hình ảnh được sử dụng để tạo sprite
  • Dòng 9 vẽ sprite bằng cách gọi
    (venv) $ python pygame_zero/pygame_zero_basic.py
    
    5 trên đối tượng
     1"""
     2Basic "Hello, World!" program in Pygame Zero
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame Zero. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10"""
    11
    12# Import pgzrun allows the program to run in Python IDLE
    13import pgzrun
    14
    15# Set the width and height of your output window, in pixels
    16WIDTH = 800
    17HEIGHT = 600
    18
    19def draw():
    20    """Draw is called once per frame to render everything on the screen"""
    21
    22    # Clear the screen first
    23    screen.clear()
    24
    25    # Set the background color to white
    26    screen.fill("white")
    27
    28    # Draw a blue circle with a radius of 50 in the center of the screen
    29    screen.draw.filled_circle(
    30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
    31    )
    32
    33    # Draw a red-outlined square in the top-left corner of the screen
    34    red_square = Rect((50, 50), (100, 100))
    35    screen.draw.rect(red_square, (200, 0, 0))
    36
    37    # Draw an orange caption along the bottom in 60-point font
    38    screen.draw.text(
    39        "Hello, World! From Pygame Zero!",
    40        (100, HEIGHT - 50),
    41        fontsize=60,
    42        color="orange",
    43    )
    44
    45# Run the program
    46pgzrun.go()
    
    6. Điều này vẽ hình ảnh sprite trên màn hình tại vị trí được cung cấp bởi
    (venv) $ python pygame_zero/pygame_zero_basic.py
    
    7

Bạn sẽ sử dụng những kỹ thuật này trong một trò chơi nâng cao hơn tiếp theo

Remove ads

Ứng dụng nâng cao

Để chứng minh sự khác biệt giữa các công cụ trò chơi, bạn sẽ xem lại cùng một trò chơi nâng cao mà bạn đã thấy trong phần Pygame, hiện được viết bằng Pygame Zero. Xin nhắc lại, các chi tiết chính của trò chơi đó là

  • Người chơi là một nhân vật duy nhất trên màn hình, được điều khiển bằng cách di chuyển chuột
  • Theo các khoảng thời gian đều đặn, từng đồng xu xuất hiện trên màn hình
  • Khi người chơi di chuyển qua từng đồng xu, nó sẽ biến mất và người chơi được thưởng mười điểm
  • Khi trò chơi tiến triển, tiền xu được thêm vào nhanh hơn
  • Trò chơi kết thúc khi có hơn mười đồng xu hiển thị trên màn hình

Trò chơi này sẽ có giao diện và hoạt động giống với phiên bản Pygame đã trình bày trước đó, chỉ có thanh tiêu đề cửa sổ phản bội nguồn gốc của Pygame Zero

Công cụ trò chơi dựa trên văn bản Python

Bạn có thể tìm thấy mã hoàn chỉnh cho mẫu này trong các tài liệu đã tải xuống và bên dưới

Nguồn cho

(venv) $ python pygame_zero/pygame_zero_basic.py
8Hiển thị/Ẩn

  1"""
  2Complete game in Pygame Zero
  3
  4This game demonstrates some of the more advanced features of
  5Pygame Zero, including:
  6- Using sprites to render complex graphics
  7- Handling user input
  8- Sound output
  9
 10"""
 11
 12# Import pgzrun allows the program to run in Python IDLE
 13import pgzrun
 14
 15# For type-hinting support
 16from typing import Tuple
 17
 18# To randomize coin placement
 19from random import randint
 20
 21# Set the width and height of your output window, in pixels
 22WIDTH = 800
 23HEIGHT = 600
 24
 25# Set up the player
 26player = Actor("alien_green_stand")
 27player_position = WIDTH // 2, HEIGHT // 2
 28player.center = player_position
 29
 30# Set up the coins to collect
 31COIN_COUNT = 10
 32coin_list = list()
 33
 34# Set up a timer to create new coins
 35coin_countdown = 2.5
 36coin_interval = 0.1
 37
 38# Score is initially zero
 39score = 0
 40
 41def add_coin():
 42    """Adds a new coin to playfield, then
 43    schedules the next coin to be added
 44    """
 45    global coin_countdown
 46
 47    # Create a new coin Actor at a random location
 48    new_coin = Actor(
 49        "coin_gold", (randint(10, WIDTH - 10), randint(10, HEIGHT - 10))
 50    )
 51
 52    # Add it to the global coin list
 53    coin_list.append(new_coin)
 54
 55    # Decrease the time between coin appearances if there are
 56    # fewer than three coins on the screen.
 57    if len(coin_list) < 3:
 58        coin_countdown -= coin_interval
 59
 60    # Make sure you don't go too quickly
 61    if coin_countdown < 0.1:
 62        coin_countdown = 0.1
 63
 64    # Schedule the next coin addition
 65    clock.schedule(add_coin, coin_countdown)
 66
 67def on_mouse_move(pos: Tuple):
 68    """Called whenever the mouse changes position
 69
 70    Arguments:
 71        pos {Tuple} -- The current position of the mouse
 72    """
 73    global player_position
 74
 75    # Set the player to the mouse position
 76    player_position = pos
 77
 78    # Ensure the player doesn't move off the screen
 79    if player_position[0] < 0:
 80        player_position[0] = 0
 81    if player_position[0] > WIDTH:
 82        player_position[0] = WIDTH
 83
 84    if player_position[1] < 0:
 85        player_position[1] = 0
 86    if player_position[1] > HEIGHT:
 87        player_position[1] = HEIGHT
 88
 89def update(delta_time: float):
 90    """Called every frame to update game objects
 91
 92    Arguments:
 93        delta_time {float} -- Time since the last frame
 94    """
 95    global score
 96
 97    # Update the player position
 98    player.center = player_position
 99
100    # Check if the player has collided with a coin
101    # First, set up a list of coins to remove
102    coin_remove_list = []
103
104    # Check each coin in the list for a collision
105    for coin in coin_list:
106        if player.colliderect(coin):
107            sounds.coin_pickup.play()
108            coin_remove_list.append(coin)
109            score += 10
110
111    # Remove any coins with which you collided
112    for coin in coin_remove_list:
113        coin_list.remove(coin)
114
115    # The game is over when there are too many coins on the screen
116    if len(coin_list) >= COIN_COUNT:
117        # Stop making new coins
118        clock.unschedule(add_coin)
119
120        # Print the final score and exit the game
121        print(f"Game over! Final score: {score}")
122        exit()
123
124def draw():
125    """Render everything on the screen once per frame"""
126
127    # Clear the screen first
128    screen.clear()
129
130    # Set the background color to pink
131    screen.fill("pink")
132
133    # Draw the remaining coins
134    for coin in coin_list:
135        coin.draw()
136
137    # Draw the player
138    player.draw()
139
140    # Draw the current score at the bottom
141    screen.draw.text(
142        f"Score: {score}",
143        (50, HEIGHT - 50),
144        fontsize=48,
145        color="black",
146    )
147
148# Schedule the first coin to appear
149clock.schedule(add_coin, coin_countdown)
150
151# Run the program
152pgzrun.go()

Tạo trình phát

 1"""
 2Basic "Hello, World!" program in Pygame Zero
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame Zero. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10"""
11
12# Import pgzrun allows the program to run in Python IDLE
13import pgzrun
14
15# Set the width and height of your output window, in pixels
16WIDTH = 800
17HEIGHT = 600
18
19def draw():
20    """Draw is called once per frame to render everything on the screen"""
21
22    # Clear the screen first
23    screen.clear()
24
25    # Set the background color to white
26    screen.fill("white")
27
28    # Draw a blue circle with a radius of 50 in the center of the screen
29    screen.draw.filled_circle(
30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
31    )
32
33    # Draw a red-outlined square in the top-left corner of the screen
34    red_square = Rect((50, 50), (100, 100))
35    screen.draw.rect(red_square, (200, 0, 0))
36
37    # Draw an orange caption along the bottom in 60-point font
38    screen.draw.text(
39        "Hello, World! From Pygame Zero!",
40        (100, HEIGHT - 50),
41        fontsize=60,
42        color="orange",
43    )
44
45# Run the program
46pgzrun.go()
6 được thực hiện từ dòng 26 đến 28. Vị trí ban đầu là trung tâm của màn hình

Phương thức

 1alien = Actor("alien")
 2alien.pos = 100, 56
 3
 4WIDTH = 500
 5HEIGHT = alien.height + 20
 6
 7def draw():
 8    screen.clear()
 9    alien.draw()
0 xử lý việc tạo tiền theo định kỳ. Phương thức này nhận một chức năng để gọi và số giây để trì hoãn trước khi gọi chức năng đó

Dòng 41 đến 65 định nghĩa hàm

 1alien = Actor("alien")
 2alien.pos = 100, 56
 3
 4WIDTH = 500
 5HEIGHT = alien.height + 20
 6
 7def draw():
 8    screen.clear()
 9    alien.draw()
1 sẽ được lên lịch. Nó tạo ra một đồng xu mới
 1"""
 2Basic "Hello, World!" program in Pygame Zero
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame Zero. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10"""
11
12# Import pgzrun allows the program to run in Python IDLE
13import pgzrun
14
15# Set the width and height of your output window, in pixels
16WIDTH = 800
17HEIGHT = 600
18
19def draw():
20    """Draw is called once per frame to render everything on the screen"""
21
22    # Clear the screen first
23    screen.clear()
24
25    # Set the background color to white
26    screen.fill("white")
27
28    # Draw a blue circle with a radius of 50 in the center of the screen
29    screen.draw.filled_circle(
30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
31    )
32
33    # Draw a red-outlined square in the top-left corner of the screen
34    red_square = Rect((50, 50), (100, 100))
35    screen.draw.rect(red_square, (200, 0, 0))
36
37    # Draw an orange caption along the bottom in 60-point font
38    screen.draw.text(
39        "Hello, World! From Pygame Zero!",
40        (100, HEIGHT - 50),
41        fontsize=60,
42        color="orange",
43    )
44
45# Run the program
46pgzrun.go()
6 tại một vị trí ngẫu nhiên trên các dòng 48 đến 50 và thêm nó vào danh sách toàn cầu về các đồng xu có thể nhìn thấy

Khi trò chơi diễn ra, tiền xu sẽ xuất hiện ngày càng nhanh, nhưng không quá nhanh. Quản lý khoảng thời gian được thực hiện trên các dòng 57 đến 62. Bởi vì

 1alien = Actor("alien")
 2alien.pos = 100, 56
 3
 4WIDTH = 500
 5HEIGHT = alien.height + 20
 6
 7def draw():
 8    screen.clear()
 9    alien.draw()
0 sẽ chỉ kích hoạt một lần duy nhất, bạn lên lịch một cuộc gọi khác trên đường dây 65

Chuyển động của chuột được xử lý trong trình xử lý sự kiện

 1alien = Actor("alien")
 2alien.pos = 100, 56
 3
 4WIDTH = 500
 5HEIGHT = alien.height + 20
 6
 7def draw():
 8    screen.clear()
 9    alien.draw()
4 trên các dòng 67 đến 87. Vị trí chuột được chụp và lưu trữ trong một biến toàn cầu trên dòng 76. Dòng 79 đến 87 đảm bảo vị trí này không bao giờ tắt màn hình

Lưu trữ vị trí của người chơi trong một biến

 1alien = Actor("alien")
 2alien.pos = 100, 56
 3
 4WIDTH = 500
 5HEIGHT = alien.height + 20
 6
 7def draw():
 8    screen.clear()
 9    alien.draw()
5 là một tiện ích giúp đơn giản hóa mã và tập trung cho phép bạn tập trung vào các khả năng của Pygame Zero. Lựa chọn thiết kế của bạn có thể khác trong các trò chơi hoàn chỉnh hơn

Hàm

 1alien = Actor("alien")
 2alien.pos = 100, 56
 3
 4WIDTH = 500
 5HEIGHT = alien.height + 20
 6
 7def draw():
 8    screen.clear()
 9    alien.draw()
6 được xác định trên các dòng 89 đến 122 được gọi một lần trên mỗi khung bởi Pygame Zero. Bạn sử dụng điều này để di chuyển
 1"""
 2Basic "Hello, World!" program in Pygame Zero
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame Zero. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10"""
11
12# Import pgzrun allows the program to run in Python IDLE
13import pgzrun
14
15# Set the width and height of your output window, in pixels
16WIDTH = 800
17HEIGHT = 600
18
19def draw():
20    """Draw is called once per frame to render everything on the screen"""
21
22    # Clear the screen first
23    screen.clear()
24
25    # Set the background color to white
26    screen.fill("white")
27
28    # Draw a blue circle with a radius of 50 in the center of the screen
29    screen.draw.filled_circle(
30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
31    )
32
33    # Draw a red-outlined square in the top-left corner of the screen
34    red_square = Rect((50, 50), (100, 100))
35    screen.draw.rect(red_square, (200, 0, 0))
36
37    # Draw an orange caption along the bottom in 60-point font
38    screen.draw.text(
39        "Hello, World! From Pygame Zero!",
40        (100, HEIGHT - 50),
41        fontsize=60,
42        color="orange",
43    )
44
45# Run the program
46pgzrun.go()
6 đối tượng và cập nhật trạng thái của tất cả các đối tượng trong trò chơi của bạn. Vị trí của người chơi
 1"""
 2Basic "Hello, World!" program in Pygame Zero
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame Zero. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10"""
11
12# Import pgzrun allows the program to run in Python IDLE
13import pgzrun
14
15# Set the width and height of your output window, in pixels
16WIDTH = 800
17HEIGHT = 600
18
19def draw():
20    """Draw is called once per frame to render everything on the screen"""
21
22    # Clear the screen first
23    screen.clear()
24
25    # Set the background color to white
26    screen.fill("white")
27
28    # Draw a blue circle with a radius of 50 in the center of the screen
29    screen.draw.filled_circle(
30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
31    )
32
33    # Draw a red-outlined square in the top-left corner of the screen
34    red_square = Rect((50, 50), (100, 100))
35    screen.draw.rect(red_square, (200, 0, 0))
36
37    # Draw an orange caption along the bottom in 60-point font
38    screen.draw.text(
39        "Hello, World! From Pygame Zero!",
40        (100, HEIGHT - 50),
41        fontsize=60,
42        color="orange",
43    )
44
45# Run the program
46pgzrun.go()
6 được cập nhật để theo dõi chuột ở dòng 98

Va chạm với tiền xu được xử lý trên các dòng 102 đến 113. Nếu người chơi đã va chạm với một đồng xu, thì đồng xu đó sẽ được thêm vào

 1alien = Actor("alien")
 2alien.pos = 100, 56
 3
 4WIDTH = 500
 5HEIGHT = alien.height + 20
 6
 7def draw():
 8    screen.clear()
 9    alien.draw()
9, điểm số sẽ tăng lên và một âm thanh sẽ phát ra. Khi tất cả các va chạm đã được xử lý, bạn loại bỏ các đồng xu đã được thêm vào
 1alien = Actor("alien")
 2alien.pos = 100, 56
 3
 4WIDTH = 500
 5HEIGHT = alien.height + 20
 6
 7def draw():
 8    screen.clear()
 9    alien.draw()
9 trên các dòng 112 đến 113

Sau khi xử lý va chạm xu, bạn kiểm tra xem còn quá nhiều xu trên màn hình ở dòng 116 không. Nếu vậy, trò chơi kết thúc, vì vậy bạn ngừng tạo tiền mới, in điểm số cuối cùng và kết thúc trò chơi ở các dòng 118 đến 122

Tất nhiên, tất cả cập nhật này cần được phản ánh trên màn hình. Hàm

 1"""
 2Basic "Hello, World!" program in Pygame Zero
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame Zero. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10"""
11
12# Import pgzrun allows the program to run in Python IDLE
13import pgzrun
14
15# Set the width and height of your output window, in pixels
16WIDTH = 800
17HEIGHT = 600
18
19def draw():
20    """Draw is called once per frame to render everything on the screen"""
21
22    # Clear the screen first
23    screen.clear()
24
25    # Set the background color to white
26    screen.fill("white")
27
28    # Draw a blue circle with a radius of 50 in the center of the screen
29    screen.draw.filled_circle(
30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
31    )
32
33    # Draw a red-outlined square in the top-left corner of the screen
34    red_square = Rect((50, 50), (100, 100))
35    screen.draw.rect(red_square, (200, 0, 0))
36
37    # Draw an orange caption along the bottom in 60-point font
38    screen.draw.text(
39        "Hello, World! From Pygame Zero!",
40        (100, HEIGHT - 50),
41        fontsize=60,
42        color="orange",
43    )
44
45# Run the program
46pgzrun.go()
5 trên các dòng 124 đến 146 được gọi sau
 1alien = Actor("alien")
 2alien.pos = 100, 56
 3
 4WIDTH = 500
 5HEIGHT = alien.height + 20
 6
 7def draw():
 8    screen.clear()
 9    alien.draw()
6 một lần trên mỗi khung. Sau khi xóa màn hình và tô màu nền ở các dòng 128 và 131, người chơi
 1"""
 2Basic "Hello, World!" program in Pygame Zero
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame Zero. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10"""
11
12# Import pgzrun allows the program to run in Python IDLE
13import pgzrun
14
15# Set the width and height of your output window, in pixels
16WIDTH = 800
17HEIGHT = 600
18
19def draw():
20    """Draw is called once per frame to render everything on the screen"""
21
22    # Clear the screen first
23    screen.clear()
24
25    # Set the background color to white
26    screen.fill("white")
27
28    # Draw a blue circle with a radius of 50 in the center of the screen
29    screen.draw.filled_circle(
30        (WIDTH // 2, HEIGHT // 2), 50, "blue"
31    )
32
33    # Draw a red-outlined square in the top-left corner of the screen
34    red_square = Rect((50, 50), (100, 100))
35    screen.draw.rect(red_square, (200, 0, 0))
36
37    # Draw an orange caption along the bottom in 60-point font
38    screen.draw.text(
39        "Hello, World! From Pygame Zero!",
40        (100, HEIGHT - 50),
41        fontsize=60,
42        color="orange",
43    )
44
45# Run the program
46pgzrun.go()
6 và tất cả các đồng xu được rút ở các dòng 134 đến 138. Tỷ số hiện tại là điều cuối cùng được vẽ trên các dòng 141 đến 146

Việc triển khai Pygame Zero đã sử dụng 152 dòng mã để phân phối trò chơi giống như 182 dòng mã Pygame. Mặc dù số lượng dòng này có thể so sánh được, nhưng phiên bản Pygame Zero được cho là sạch hơn, nhiều mô-đun hơn và có thể dễ hiểu và viết mã hơn phiên bản Pygame

Tất nhiên, luôn có một cách nữa để viết game

Giải trí

Arcade là một khung Python hiện đại để tạo trò chơi với đồ họa và âm thanh hấp dẫn. Hướng đối tượng theo thiết kế, Arcade cung cấp cho các tác giả trò chơi một bộ công cụ hiện đại để tạo ra trải nghiệm trò chơi Python tuyệt vời

Được thiết kế bởi Giáo sư Paul Craven từ Đại học Simpson ở Iowa, Hoa Kỳ, Arcade được xây dựng trên thư viện đa phương tiện và cửa sổ pyglet. Nó cung cấp một tập hợp các cải tiến, hiện đại hóa và cải tiến có thể so sánh thuận lợi với cả Pygame và Pygame Zero

  • Hỗ trợ đồ họa OpenGL hiện đại
  • Hỗ trợ Python3
  • Có hỗ trợ cho các họa tiết hoạt hình dựa trên khung
  • Kết hợp các tên lệnh, chức năng và tham số nhất quán
  • Khuyến khích tách logic trò chơi khỏi mã hiển thị
  • Yêu cầu ít mã soạn sẵn hơn
  • Cung cấp tài liệu được cập nhật và duy trì tốt, bao gồm một số hướng dẫn và các ví dụ hoàn chỉnh về trò chơi Python
  • Có các công cụ vật lý tích hợp cho các trò chơi nền tảng và từ trên xuống

Arcade đang được phát triển liên tục, được hỗ trợ tốt trong cộng đồng và có một tác giả rất nhạy bén với các vấn đề, báo cáo lỗi và các bản sửa lỗi tiềm năng

Remove ads

Cài đặt trò chơi điện tử

Để cài đặt Arcade và các phần phụ thuộc của nó, hãy sử dụng lệnh

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
7 thích hợp

(venv) $ python -m pygame.examples.aliens
0

Hướng dẫn cài đặt hoàn chỉnh dựa trên nền tảng của bạn có sẵn cho Windows, macOS và Linux. Bạn thậm chí có thể cài đặt

  1"""
  2Complete game in Pygame Zero
  3
  4This game demonstrates some of the more advanced features of
  5Pygame Zero, including:
  6- Using sprites to render complex graphics
  7- Handling user input
  8- Sound output
  9
 10"""
 11
 12# Import pgzrun allows the program to run in Python IDLE
 13import pgzrun
 14
 15# For type-hinting support
 16from typing import Tuple
 17
 18# To randomize coin placement
 19from random import randint
 20
 21# Set the width and height of your output window, in pixels
 22WIDTH = 800
 23HEIGHT = 600
 24
 25# Set up the player
 26player = Actor("alien_green_stand")
 27player_position = WIDTH // 2, HEIGHT // 2
 28player.center = player_position
 29
 30# Set up the coins to collect
 31COIN_COUNT = 10
 32coin_list = list()
 33
 34# Set up a timer to create new coins
 35coin_countdown = 2.5
 36coin_interval = 0.1
 37
 38# Score is initially zero
 39score = 0
 40
 41def add_coin():
 42    """Adds a new coin to playfield, then
 43    schedules the next coin to be added
 44    """
 45    global coin_countdown
 46
 47    # Create a new coin Actor at a random location
 48    new_coin = Actor(
 49        "coin_gold", (randint(10, WIDTH - 10), randint(10, HEIGHT - 10))
 50    )
 51
 52    # Add it to the global coin list
 53    coin_list.append(new_coin)
 54
 55    # Decrease the time between coin appearances if there are
 56    # fewer than three coins on the screen.
 57    if len(coin_list) < 3:
 58        coin_countdown -= coin_interval
 59
 60    # Make sure you don't go too quickly
 61    if coin_countdown < 0.1:
 62        coin_countdown = 0.1
 63
 64    # Schedule the next coin addition
 65    clock.schedule(add_coin, coin_countdown)
 66
 67def on_mouse_move(pos: Tuple):
 68    """Called whenever the mouse changes position
 69
 70    Arguments:
 71        pos {Tuple} -- The current position of the mouse
 72    """
 73    global player_position
 74
 75    # Set the player to the mouse position
 76    player_position = pos
 77
 78    # Ensure the player doesn't move off the screen
 79    if player_position[0] < 0:
 80        player_position[0] = 0
 81    if player_position[0] > WIDTH:
 82        player_position[0] = WIDTH
 83
 84    if player_position[1] < 0:
 85        player_position[1] = 0
 86    if player_position[1] > HEIGHT:
 87        player_position[1] = HEIGHT
 88
 89def update(delta_time: float):
 90    """Called every frame to update game objects
 91
 92    Arguments:
 93        delta_time {float} -- Time since the last frame
 94    """
 95    global score
 96
 97    # Update the player position
 98    player.center = player_position
 99
100    # Check if the player has collided with a coin
101    # First, set up a list of coins to remove
102    coin_remove_list = []
103
104    # Check each coin in the list for a collision
105    for coin in coin_list:
106        if player.colliderect(coin):
107            sounds.coin_pickup.play()
108            coin_remove_list.append(coin)
109            score += 10
110
111    # Remove any coins with which you collided
112    for coin in coin_remove_list:
113        coin_list.remove(coin)
114
115    # The game is over when there are too many coins on the screen
116    if len(coin_list) >= COIN_COUNT:
117        # Stop making new coins
118        clock.unschedule(add_coin)
119
120        # Print the final score and exit the game
121        print(f"Game over! Final score: {score}")
122        exit()
123
124def draw():
125    """Render everything on the screen once per frame"""
126
127    # Clear the screen first
128    screen.clear()
129
130    # Set the background color to pink
131    screen.fill("pink")
132
133    # Draw the remaining coins
134    for coin in coin_list:
135        coin.draw()
136
137    # Draw the player
138    player.draw()
139
140    # Draw the current score at the bottom
141    screen.draw.text(
142        f"Score: {score}",
143        (50, HEIGHT - 50),
144        fontsize=48,
145        color="black",
146    )
147
148# Schedule the first coin to appear
149clock.schedule(add_coin, coin_countdown)
150
151# Run the program
152pgzrun.go()
5 trực tiếp từ nguồn nếu muốn

Basic Concepts

Mọi thứ trong Arcade diễn ra trong một cửa sổ được tạo với kích thước do người dùng xác định. Hệ tọa độ giả định rằng gốc tọa độ

  1"""
  2Complete game in Pygame Zero
  3
  4This game demonstrates some of the more advanced features of
  5Pygame Zero, including:
  6- Using sprites to render complex graphics
  7- Handling user input
  8- Sound output
  9
 10"""
 11
 12# Import pgzrun allows the program to run in Python IDLE
 13import pgzrun
 14
 15# For type-hinting support
 16from typing import Tuple
 17
 18# To randomize coin placement
 19from random import randint
 20
 21# Set the width and height of your output window, in pixels
 22WIDTH = 800
 23HEIGHT = 600
 24
 25# Set up the player
 26player = Actor("alien_green_stand")
 27player_position = WIDTH // 2, HEIGHT // 2
 28player.center = player_position
 29
 30# Set up the coins to collect
 31COIN_COUNT = 10
 32coin_list = list()
 33
 34# Set up a timer to create new coins
 35coin_countdown = 2.5
 36coin_interval = 0.1
 37
 38# Score is initially zero
 39score = 0
 40
 41def add_coin():
 42    """Adds a new coin to playfield, then
 43    schedules the next coin to be added
 44    """
 45    global coin_countdown
 46
 47    # Create a new coin Actor at a random location
 48    new_coin = Actor(
 49        "coin_gold", (randint(10, WIDTH - 10), randint(10, HEIGHT - 10))
 50    )
 51
 52    # Add it to the global coin list
 53    coin_list.append(new_coin)
 54
 55    # Decrease the time between coin appearances if there are
 56    # fewer than three coins on the screen.
 57    if len(coin_list) < 3:
 58        coin_countdown -= coin_interval
 59
 60    # Make sure you don't go too quickly
 61    if coin_countdown < 0.1:
 62        coin_countdown = 0.1
 63
 64    # Schedule the next coin addition
 65    clock.schedule(add_coin, coin_countdown)
 66
 67def on_mouse_move(pos: Tuple):
 68    """Called whenever the mouse changes position
 69
 70    Arguments:
 71        pos {Tuple} -- The current position of the mouse
 72    """
 73    global player_position
 74
 75    # Set the player to the mouse position
 76    player_position = pos
 77
 78    # Ensure the player doesn't move off the screen
 79    if player_position[0] < 0:
 80        player_position[0] = 0
 81    if player_position[0] > WIDTH:
 82        player_position[0] = WIDTH
 83
 84    if player_position[1] < 0:
 85        player_position[1] = 0
 86    if player_position[1] > HEIGHT:
 87        player_position[1] = HEIGHT
 88
 89def update(delta_time: float):
 90    """Called every frame to update game objects
 91
 92    Arguments:
 93        delta_time {float} -- Time since the last frame
 94    """
 95    global score
 96
 97    # Update the player position
 98    player.center = player_position
 99
100    # Check if the player has collided with a coin
101    # First, set up a list of coins to remove
102    coin_remove_list = []
103
104    # Check each coin in the list for a collision
105    for coin in coin_list:
106        if player.colliderect(coin):
107            sounds.coin_pickup.play()
108            coin_remove_list.append(coin)
109            score += 10
110
111    # Remove any coins with which you collided
112    for coin in coin_remove_list:
113        coin_list.remove(coin)
114
115    # The game is over when there are too many coins on the screen
116    if len(coin_list) >= COIN_COUNT:
117        # Stop making new coins
118        clock.unschedule(add_coin)
119
120        # Print the final score and exit the game
121        print(f"Game over! Final score: {score}")
122        exit()
123
124def draw():
125    """Render everything on the screen once per frame"""
126
127    # Clear the screen first
128    screen.clear()
129
130    # Set the background color to pink
131    screen.fill("pink")
132
133    # Draw the remaining coins
134    for coin in coin_list:
135        coin.draw()
136
137    # Draw the player
138    player.draw()
139
140    # Draw the current score at the bottom
141    screen.draw.text(
142        f"Score: {score}",
143        (50, HEIGHT - 50),
144        fontsize=48,
145        color="black",
146    )
147
148# Schedule the first coin to appear
149clock.schedule(add_coin, coin_countdown)
150
151# Run the program
152pgzrun.go()
6 nằm ở góc dưới bên trái của màn hình, với tọa độ y tăng dần khi bạn di chuyển lên trên. Điều này khác với nhiều công cụ trò chơi khác, đặt
  1"""
  2Complete game in Pygame Zero
  3
  4This game demonstrates some of the more advanced features of
  5Pygame Zero, including:
  6- Using sprites to render complex graphics
  7- Handling user input
  8- Sound output
  9
 10"""
 11
 12# Import pgzrun allows the program to run in Python IDLE
 13import pgzrun
 14
 15# For type-hinting support
 16from typing import Tuple
 17
 18# To randomize coin placement
 19from random import randint
 20
 21# Set the width and height of your output window, in pixels
 22WIDTH = 800
 23HEIGHT = 600
 24
 25# Set up the player
 26player = Actor("alien_green_stand")
 27player_position = WIDTH // 2, HEIGHT // 2
 28player.center = player_position
 29
 30# Set up the coins to collect
 31COIN_COUNT = 10
 32coin_list = list()
 33
 34# Set up a timer to create new coins
 35coin_countdown = 2.5
 36coin_interval = 0.1
 37
 38# Score is initially zero
 39score = 0
 40
 41def add_coin():
 42    """Adds a new coin to playfield, then
 43    schedules the next coin to be added
 44    """
 45    global coin_countdown
 46
 47    # Create a new coin Actor at a random location
 48    new_coin = Actor(
 49        "coin_gold", (randint(10, WIDTH - 10), randint(10, HEIGHT - 10))
 50    )
 51
 52    # Add it to the global coin list
 53    coin_list.append(new_coin)
 54
 55    # Decrease the time between coin appearances if there are
 56    # fewer than three coins on the screen.
 57    if len(coin_list) < 3:
 58        coin_countdown -= coin_interval
 59
 60    # Make sure you don't go too quickly
 61    if coin_countdown < 0.1:
 62        coin_countdown = 0.1
 63
 64    # Schedule the next coin addition
 65    clock.schedule(add_coin, coin_countdown)
 66
 67def on_mouse_move(pos: Tuple):
 68    """Called whenever the mouse changes position
 69
 70    Arguments:
 71        pos {Tuple} -- The current position of the mouse
 72    """
 73    global player_position
 74
 75    # Set the player to the mouse position
 76    player_position = pos
 77
 78    # Ensure the player doesn't move off the screen
 79    if player_position[0] < 0:
 80        player_position[0] = 0
 81    if player_position[0] > WIDTH:
 82        player_position[0] = WIDTH
 83
 84    if player_position[1] < 0:
 85        player_position[1] = 0
 86    if player_position[1] > HEIGHT:
 87        player_position[1] = HEIGHT
 88
 89def update(delta_time: float):
 90    """Called every frame to update game objects
 91
 92    Arguments:
 93        delta_time {float} -- Time since the last frame
 94    """
 95    global score
 96
 97    # Update the player position
 98    player.center = player_position
 99
100    # Check if the player has collided with a coin
101    # First, set up a list of coins to remove
102    coin_remove_list = []
103
104    # Check each coin in the list for a collision
105    for coin in coin_list:
106        if player.colliderect(coin):
107            sounds.coin_pickup.play()
108            coin_remove_list.append(coin)
109            score += 10
110
111    # Remove any coins with which you collided
112    for coin in coin_remove_list:
113        coin_list.remove(coin)
114
115    # The game is over when there are too many coins on the screen
116    if len(coin_list) >= COIN_COUNT:
117        # Stop making new coins
118        clock.unschedule(add_coin)
119
120        # Print the final score and exit the game
121        print(f"Game over! Final score: {score}")
122        exit()
123
124def draw():
125    """Render everything on the screen once per frame"""
126
127    # Clear the screen first
128    screen.clear()
129
130    # Set the background color to pink
131    screen.fill("pink")
132
133    # Draw the remaining coins
134    for coin in coin_list:
135        coin.draw()
136
137    # Draw the player
138    player.draw()
139
140    # Draw the current score at the bottom
141    screen.draw.text(
142        f"Score: {score}",
143        (50, HEIGHT - 50),
144        fontsize=48,
145        color="black",
146    )
147
148# Schedule the first coin to appear
149clock.schedule(add_coin, coin_countdown)
150
151# Run the program
152pgzrun.go()
6 ở phía trên bên trái và tăng tọa độ y di chuyển xuống dưới

Về bản chất, Arcade là một thư viện hướng đối tượng. Mặc dù có thể viết các ứng dụng Arcade theo thủ tục, nhưng sức mạnh thực sự của nó được bộc lộ khi bạn tạo mã hướng đối tượng hoàn toàn

Arcade, giống như Pygame Zero, cung cấp một vòng lặp trò chơi tích hợp và một mô hình sự kiện được xác định rõ ràng, vì vậy bạn sẽ có được mã trò chơi rất rõ ràng và dễ đọc. Cũng giống như Pygame Zero, Arcade cung cấp một lớp sprite mạnh mẽ hỗ trợ kết xuất, định vị và phát hiện va chạm. Ngoài ra, các họa tiết Arcade có thể được làm động bằng cách cung cấp nhiều hình ảnh

Mã cho ứng dụng Arcade cơ bản được liệt kê bên dưới được cung cấp trong mã nguồn của hướng dẫn là

  1"""
  2Complete game in Pygame Zero
  3
  4This game demonstrates some of the more advanced features of
  5Pygame Zero, including:
  6- Using sprites to render complex graphics
  7- Handling user input
  8- Sound output
  9
 10"""
 11
 12# Import pgzrun allows the program to run in Python IDLE
 13import pgzrun
 14
 15# For type-hinting support
 16from typing import Tuple
 17
 18# To randomize coin placement
 19from random import randint
 20
 21# Set the width and height of your output window, in pixels
 22WIDTH = 800
 23HEIGHT = 600
 24
 25# Set up the player
 26player = Actor("alien_green_stand")
 27player_position = WIDTH // 2, HEIGHT // 2
 28player.center = player_position
 29
 30# Set up the coins to collect
 31COIN_COUNT = 10
 32coin_list = list()
 33
 34# Set up a timer to create new coins
 35coin_countdown = 2.5
 36coin_interval = 0.1
 37
 38# Score is initially zero
 39score = 0
 40
 41def add_coin():
 42    """Adds a new coin to playfield, then
 43    schedules the next coin to be added
 44    """
 45    global coin_countdown
 46
 47    # Create a new coin Actor at a random location
 48    new_coin = Actor(
 49        "coin_gold", (randint(10, WIDTH - 10), randint(10, HEIGHT - 10))
 50    )
 51
 52    # Add it to the global coin list
 53    coin_list.append(new_coin)
 54
 55    # Decrease the time between coin appearances if there are
 56    # fewer than three coins on the screen.
 57    if len(coin_list) < 3:
 58        coin_countdown -= coin_interval
 59
 60    # Make sure you don't go too quickly
 61    if coin_countdown < 0.1:
 62        coin_countdown = 0.1
 63
 64    # Schedule the next coin addition
 65    clock.schedule(add_coin, coin_countdown)
 66
 67def on_mouse_move(pos: Tuple):
 68    """Called whenever the mouse changes position
 69
 70    Arguments:
 71        pos {Tuple} -- The current position of the mouse
 72    """
 73    global player_position
 74
 75    # Set the player to the mouse position
 76    player_position = pos
 77
 78    # Ensure the player doesn't move off the screen
 79    if player_position[0] < 0:
 80        player_position[0] = 0
 81    if player_position[0] > WIDTH:
 82        player_position[0] = WIDTH
 83
 84    if player_position[1] < 0:
 85        player_position[1] = 0
 86    if player_position[1] > HEIGHT:
 87        player_position[1] = HEIGHT
 88
 89def update(delta_time: float):
 90    """Called every frame to update game objects
 91
 92    Arguments:
 93        delta_time {float} -- Time since the last frame
 94    """
 95    global score
 96
 97    # Update the player position
 98    player.center = player_position
 99
100    # Check if the player has collided with a coin
101    # First, set up a list of coins to remove
102    coin_remove_list = []
103
104    # Check each coin in the list for a collision
105    for coin in coin_list:
106        if player.colliderect(coin):
107            sounds.coin_pickup.play()
108            coin_remove_list.append(coin)
109            score += 10
110
111    # Remove any coins with which you collided
112    for coin in coin_remove_list:
113        coin_list.remove(coin)
114
115    # The game is over when there are too many coins on the screen
116    if len(coin_list) >= COIN_COUNT:
117        # Stop making new coins
118        clock.unschedule(add_coin)
119
120        # Print the final score and exit the game
121        print(f"Game over! Final score: {score}")
122        exit()
123
124def draw():
125    """Render everything on the screen once per frame"""
126
127    # Clear the screen first
128    screen.clear()
129
130    # Set the background color to pink
131    screen.fill("pink")
132
133    # Draw the remaining coins
134    for coin in coin_list:
135        coin.draw()
136
137    # Draw the player
138    player.draw()
139
140    # Draw the current score at the bottom
141    screen.draw.text(
142        f"Score: {score}",
143        (50, HEIGHT - 50),
144        fontsize=48,
145        color="black",
146    )
147
148# Schedule the first coin to appear
149clock.schedule(add_coin, coin_countdown)
150
151# Run the program
152pgzrun.go()
8

Nguồn cho

  1"""
  2Complete game in Pygame Zero
  3
  4This game demonstrates some of the more advanced features of
  5Pygame Zero, including:
  6- Using sprites to render complex graphics
  7- Handling user input
  8- Sound output
  9
 10"""
 11
 12# Import pgzrun allows the program to run in Python IDLE
 13import pgzrun
 14
 15# For type-hinting support
 16from typing import Tuple
 17
 18# To randomize coin placement
 19from random import randint
 20
 21# Set the width and height of your output window, in pixels
 22WIDTH = 800
 23HEIGHT = 600
 24
 25# Set up the player
 26player = Actor("alien_green_stand")
 27player_position = WIDTH // 2, HEIGHT // 2
 28player.center = player_position
 29
 30# Set up the coins to collect
 31COIN_COUNT = 10
 32coin_list = list()
 33
 34# Set up a timer to create new coins
 35coin_countdown = 2.5
 36coin_interval = 0.1
 37
 38# Score is initially zero
 39score = 0
 40
 41def add_coin():
 42    """Adds a new coin to playfield, then
 43    schedules the next coin to be added
 44    """
 45    global coin_countdown
 46
 47    # Create a new coin Actor at a random location
 48    new_coin = Actor(
 49        "coin_gold", (randint(10, WIDTH - 10), randint(10, HEIGHT - 10))
 50    )
 51
 52    # Add it to the global coin list
 53    coin_list.append(new_coin)
 54
 55    # Decrease the time between coin appearances if there are
 56    # fewer than three coins on the screen.
 57    if len(coin_list) < 3:
 58        coin_countdown -= coin_interval
 59
 60    # Make sure you don't go too quickly
 61    if coin_countdown < 0.1:
 62        coin_countdown = 0.1
 63
 64    # Schedule the next coin addition
 65    clock.schedule(add_coin, coin_countdown)
 66
 67def on_mouse_move(pos: Tuple):
 68    """Called whenever the mouse changes position
 69
 70    Arguments:
 71        pos {Tuple} -- The current position of the mouse
 72    """
 73    global player_position
 74
 75    # Set the player to the mouse position
 76    player_position = pos
 77
 78    # Ensure the player doesn't move off the screen
 79    if player_position[0] < 0:
 80        player_position[0] = 0
 81    if player_position[0] > WIDTH:
 82        player_position[0] = WIDTH
 83
 84    if player_position[1] < 0:
 85        player_position[1] = 0
 86    if player_position[1] > HEIGHT:
 87        player_position[1] = HEIGHT
 88
 89def update(delta_time: float):
 90    """Called every frame to update game objects
 91
 92    Arguments:
 93        delta_time {float} -- Time since the last frame
 94    """
 95    global score
 96
 97    # Update the player position
 98    player.center = player_position
 99
100    # Check if the player has collided with a coin
101    # First, set up a list of coins to remove
102    coin_remove_list = []
103
104    # Check each coin in the list for a collision
105    for coin in coin_list:
106        if player.colliderect(coin):
107            sounds.coin_pickup.play()
108            coin_remove_list.append(coin)
109            score += 10
110
111    # Remove any coins with which you collided
112    for coin in coin_remove_list:
113        coin_list.remove(coin)
114
115    # The game is over when there are too many coins on the screen
116    if len(coin_list) >= COIN_COUNT:
117        # Stop making new coins
118        clock.unschedule(add_coin)
119
120        # Print the final score and exit the game
121        print(f"Game over! Final score: {score}")
122        exit()
123
124def draw():
125    """Render everything on the screen once per frame"""
126
127    # Clear the screen first
128    screen.clear()
129
130    # Set the background color to pink
131    screen.fill("pink")
132
133    # Draw the remaining coins
134    for coin in coin_list:
135        coin.draw()
136
137    # Draw the player
138    player.draw()
139
140    # Draw the current score at the bottom
141    screen.draw.text(
142        f"Score: {score}",
143        (50, HEIGHT - 50),
144        fontsize=48,
145        color="black",
146    )
147
148# Schedule the first coin to appear
149clock.schedule(add_coin, coin_countdown)
150
151# Run the program
152pgzrun.go()
8Hiển thị/Ẩn

(venv) $ python -m pygame.examples.aliens
1

Để chạy mã này, hãy sử dụng lệnh sau

(venv) $ python -m pygame.examples.aliens
2

Chương trình này vẽ một vài hình dạng và một số văn bản trên màn hình, như trong các ví dụ cơ bản đã trình bày trước đây

Công cụ trò chơi dựa trên văn bản Python

Như đã đề cập ở trên, các chương trình Arcade có thể được viết dưới dạng mã hướng đối tượng hoàn toàn. Lớp

(venv) $ python -m pygame.examples.aliens
00 được thiết kế để phân lớp theo các trò chơi của bạn, như được hiển thị trên dòng 20. Gọi
(venv) $ python -m pygame.examples.aliens
01 trên dòng 33 để đảm bảo cửa sổ trò chơi được thiết lập đúng cách

Arcade gọi trình xử lý sự kiện

(venv) $ python -m pygame.examples.aliens
02 được xác định trên các dòng 38 đến 70 một lần trên mỗi khung hình để hiển thị mọi thứ lên màn hình. Phương pháp này bắt đầu bằng một cuộc gọi đến
(venv) $ python -m pygame.examples.aliens
03, yêu cầu Arcade chuẩn bị cửa sổ để vẽ. Điều này có thể so sánh với cuộc gọi
(venv) $ python -m pygame.examples.aliens
04 được yêu cầu ở cuối bước vẽ Pygame

Mỗi phương pháp vẽ hình cơ bản trong Arcade bắt đầu bằng

(venv) $ python -m pygame.examples.aliens
05 và yêu cầu một dòng duy nhất để hoàn thành. Arcade có hỗ trợ vẽ tích hợp cho nhiều hình dạng

Arcade được tải với hàng trăm màu được đặt tên trong gói

(venv) $ python -m pygame.examples.aliens
06, nhưng bạn cũng có thể tự do chọn màu của riêng mình bằng cách sử dụng bộ dữ liệu RGB hoặc RGBA

Ứng dụng nâng cao

Để cho biết Arcade khác với các công cụ trò chơi khác như thế nào, bạn sẽ thấy cùng một trò chơi trước đây, hiện đã được triển khai trong Arcade. Xin nhắc lại, đây là những chi tiết chính của trò chơi

  • Người chơi là một nhân vật duy nhất trên màn hình, được điều khiển bằng cách di chuyển chuột
  • Theo các khoảng thời gian đều đặn, từng đồng xu xuất hiện trên màn hình
  • Khi người chơi di chuyển qua từng đồng xu, nó sẽ biến mất và người chơi được thưởng mười điểm
  • Khi trò chơi tiến triển, tiền xu được thêm vào nhanh hơn
  • Trò chơi kết thúc khi có hơn mười đồng xu hiển thị trên màn hình

Một lần nữa, trò chơi sẽ hoạt động giống như các ví dụ trước

Công cụ trò chơi dựa trên văn bản Python

Mã cho toàn bộ trò chơi Arcade được liệt kê bên dưới được cung cấp trong các tài liệu có thể tải xuống dưới dạng

(venv) $ python -m pygame.examples.aliens
07

Nguồn cho

(venv) $ python -m pygame.examples.aliens
07Hiển thị/Ẩn

(venv) $ python -m pygame.examples.aliens
3

Bản chất hướng đối tượng của Arcade cho phép bạn nhanh chóng triển khai các cấp độ khác nhau bằng cách tách riêng phần khởi tạo trò chơi khỏi phần khởi tạo của từng cấp độ khác nhau. Trò chơi được bắt đầu theo phương pháp

(venv) $ python -m pygame.examples.aliens
09 trên các dòng từ 40 đến 63, trong khi các cấp độ được thiết lập và có thể bắt đầu lại bằng cách sử dụng phương thức
(venv) $ python -m pygame.examples.aliens
10 riêng biệt trên các dòng từ 65 đến 85. Đây là một mẫu tuyệt vời để sử dụng ngay cả đối với các trò chơi có một cấp độ, như cấp độ này

Các họa tiết được xác định bằng cách tạo một đối tượng thuộc lớp

(venv) $ python -m pygame.examples.aliens
11 và cung cấp đường dẫn đến một hình ảnh. Arcade hỗ trợ các đường dẫn pathlib, giúp dễ dàng tạo sprite của người chơi trên các dòng 72 đến 75

Việc tạo tiền mới được xử lý trên các dòng 78 đến 80, gọi phương thức

(venv) $ python -m pygame.examples.aliens
12 để gọi phương thức
(venv) $ python -m pygame.examples.aliens
13 theo định kỳ

Phương thức

(venv) $ python -m pygame.examples.aliens
14 được xác định trên các dòng 87 đến 120 tạo ra một sprite đồng xu mới tại một vị trí ngẫu nhiên và thêm nó vào danh sách để đơn giản hóa việc vẽ cũng như xử lý va chạm sau này

Để di chuyển trình phát bằng chuột, bạn thực hiện phương pháp

(venv) $ python -m pygame.examples.aliens
15 trên các dòng 122 đến 134. Phương pháp
(venv) $ python -m pygame.examples.aliens
16 đảm bảo tọa độ trung tâm của người chơi không bao giờ tắt trên màn hình

Việc kiểm tra va chạm giữa người chơi và đồng xu được xử lý theo phương pháp

(venv) $ python -m pygame.examples.aliens
17 trên các dòng 144 đến 156. Phương thức
(venv) $ python -m pygame.examples.aliens
18 trả về danh sách tất cả các sprite trong danh sách đã xung đột với sprite được chỉ định. Mã đi qua danh sách đó, tăng điểm và phát hiệu ứng âm thanh trước khi loại bỏ từng đồng xu khỏi trò chơi

Phương pháp

(venv) $ python -m pygame.examples.aliens
17 cũng kiểm tra xem có quá nhiều đồng xu trên màn hình ở các dòng 159 đến 168 không. Nếu vậy, nó kết thúc trò chơi

Việc triển khai Arcade này dễ đọc và có cấu trúc tốt như mã Pygame Zero, mặc dù nó chiếm nhiều mã hơn 27%, với 194 dòng được viết. Mã dài hơn có thể đáng giá, vì Arcade cung cấp nhiều tính năng hơn không được trình bày ở đây, chẳng hạn như

  • nhân vật hoạt hình
  • Một số động cơ vật lý tích hợp
  • Hỗ trợ cho bản đồ trò chơi của bên thứ ba
  • Cập nhật hệ thống hạt và đổ bóng

Các tác giả trò chơi mới đến từ Python Zero sẽ thấy Arcade có cấu trúc tương tự trong khi cung cấp các tính năng mở rộng và mạnh mẽ hơn

Remove ads

cuộc phiêu lưu

Tất nhiên, không phải trò chơi nào cũng yêu cầu một người chơi đầy màu sắc di chuyển trên màn hình, tránh chướng ngại vật và tiêu diệt kẻ xấu. Các trò chơi máy tính cổ điển như Zork đã thể hiện sức mạnh của cách kể chuyện hay trong khi vẫn mang lại trải nghiệm chơi trò chơi tuyệt vời. Chế tạo các trò chơi dựa trên văn bản này, còn được gọi là tiểu thuyết tương tác, có thể khó bằng bất kỳ ngôn ngữ nào. May mắn cho lập trình viên Python là có adventurelib

adventurelib cung cấp chức năng cơ bản để viết các trò chơi phiêu lưu dựa trên văn bản, với mục đích giúp thanh thiếu niên dễ dàng thực hiện. (Nguồn)

Nó không chỉ dành cho thanh thiếu niên, mặc dù. adventurelib rất phù hợp cho những ai muốn viết một trò chơi dựa trên văn bản mà không cần phải viết một trình phân tích cú pháp ngôn ngữ tự nhiên để làm như vậy

adventurelib được tạo ra bởi những người đứng sau Pygame Zero, và nó xử lý các chủ đề khoa học máy tính nâng cao hơn như quản lý trạng thái, logic nghiệp vụ, đặt tên và tham chiếu cũng như thao tác thiết lập, v.v. Điều này làm cho nó trở thành một bước tiếp theo tuyệt vời cho các nhà giáo dục, phụ huynh và người cố vấn giúp những người trẻ tuổi học khoa học máy tính thông qua việc tạo ra các trò chơi. Nó cũng tuyệt vời để mở rộng kỹ năng viết mã trò chơi của riêng bạn

cài đặt phiêu lưulib

adventurelib có sẵn trên PyPI và có thể được cài đặt bằng lệnh

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
7 thích hợp

(venv) $ python -m pygame.examples.aliens
4

phiêu lưulib là một tệp duy nhất, do đó, nó cũng có thể được tải xuống từ repo GitHub, được lưu trong cùng thư mục với trò chơi của bạn và được sử dụng trực tiếp

Basic Concepts

Để tìm hiểu kiến ​​thức cơ bản về adventurelib, bạn sẽ thấy một trò chơi nhỏ có ba phòng và chìa khóa để mở cánh cửa đến căn phòng cuối cùng bên dưới. Mã cho trò chơi mẫu này được cung cấp trong các tài liệu có thể tải xuống trong

(venv) $ python -m pygame.examples.aliens
21

Nguồn cho

(venv) $ python -m pygame.examples.aliens
21Hiển thị/Ẩn

(venv) $ python -m pygame.examples.aliens
5

Để chạy mã này, hãy sử dụng lệnh sau

(venv) $ python -m pygame.examples.aliens
6

Các trò chơi dựa trên văn bản chủ yếu dựa vào việc phân tích cú pháp đầu vào của người dùng để thúc đẩy trò chơi tiến lên. adventurelib xác định văn bản mà người chơi nhập dưới dạng lệnh và cung cấp trình trang trí

(venv) $ python -m pygame.examples.aliens
23 để xác định lệnh

Một ví dụ điển hình về lệnh là lệnh

(venv) $ python -m pygame.examples.aliens
24 được định nghĩa trên các dòng 113 đến 125. Trình trang trí
(venv) $ python -m pygame.examples.aliens
25 thêm văn bản
(venv) $ python -m pygame.examples.aliens
24 vào danh sách các lệnh hợp lệ và kết nối nó với hàm
(venv) $ python -m pygame.examples.aliens
27. Bất cứ khi nào người chơi gõ
(venv) $ python -m pygame.examples.aliens
24, adventurelib sẽ gọi hàm
(venv) $ python -m pygame.examples.aliens
27

Các lệnh không phân biệt chữ hoa chữ thường khi người chơi nhập. Người chơi có thể gõ

(venv) $ python -m pygame.examples.aliens
24,
(venv) $ python -m pygame.examples.aliens
31,
(venv) $ python -m pygame.examples.aliens
32, hoặc thậm chí là
(venv) $ python -m pygame.examples.aliens
33, và adventurelib sẽ tìm đúng lệnh

Nhiều lệnh đều có thể sử dụng cùng một hàm, như đã thấy với hàm

(venv) $ python -m pygame.examples.aliens
34 trên các dòng 78 đến 110. Chức năng này được trang trí bằng chín lệnh riêng biệt, cho phép người chơi di chuyển theo nhiều cách khác nhau trong thế giới trò chơi. Trong ví dụ chơi trò chơi bên dưới, các lệnh
(venv) $ python -m pygame.examples.aliens
35,
(venv) $ python -m pygame.examples.aliens
36 và
(venv) $ python -m pygame.examples.aliens
37 đều được sử dụng, nhưng mỗi lệnh đều dẫn đến cùng một chức năng được gọi

Công cụ trò chơi dựa trên văn bản Python

Đôi khi các lệnh mà người chơi nhập được hướng đến một mục cụ thể. Ví dụ: người chơi có thể muốn nhìn vào một thứ cụ thể hoặc đi theo một hướng cụ thể. Nhà thiết kế trò chơi có thể nắm bắt ngữ cảnh lệnh bổ sung bằng cách chỉ định các từ viết hoa trong trình trang trí

(venv) $ python -m pygame.examples.aliens
23. Chúng được coi là tên biến và văn bản mà người chơi nhập vào vị trí của chúng là các giá trị

Điều này có thể được nhìn thấy trong hàm

(venv) $ python -m pygame.examples.aliens
39 trên các dòng 128 đến 137. Hàm này xác định một tham số chuỗi đơn có tên là
(venv) $ python -m pygame.examples.aliens
40. Trong các bộ trang trí
(venv) $ python -m pygame.examples.aliens
23 xác định các lệnh
(venv) $ python -m pygame.examples.aliens
42 và
(venv) $ python -m pygame.examples.aliens
43, từ
(venv) $ python -m pygame.examples.aliens
44 hoạt động như một trình giữ chỗ cho bất kỳ văn bản nào sau lệnh. Văn bản này sau đó được chuyển đến hàm
(venv) $ python -m pygame.examples.aliens
39 dưới dạng tham số
(venv) $ python -m pygame.examples.aliens
40. Ví dụ người chơi gõ
(venv) $ python -m pygame.examples.aliens
47 thì tham số
(venv) $ python -m pygame.examples.aliens
40 sẽ nhận giá trị là
(venv) $ python -m pygame.examples.aliens
49

Sức mạnh của một trò chơi dựa trên văn bản phụ thuộc vào tính mô tả của văn bản của nó. Mặc dù bạn có thể và chắc chắn nên sử dụng các hàm

(venv) $ python -m pygame.examples.aliens
50, nhưng việc in nhiều dòng văn bản để đáp ứng các lệnh của người dùng có thể gây khó khăn khi kéo dài văn bản trên nhiều dòng và xác định ngắt dòng. adventurelib giảm bớt gánh nặng này với chức năng
(venv) $ python -m pygame.examples.aliens
51, hoạt động tốt với

Bạn có thể thấy hàm

(venv) $ python -m pygame.examples.aliens
51 đang hoạt động trên dòng 118 trong hàm
(venv) $ python -m pygame.examples.aliens
27. Bất cứ khi nào người chơi gõ
(venv) $ python -m pygame.examples.aliens
24, chức năng
(venv) $ python -m pygame.examples.aliens
51 sẽ xuất mô tả của căn phòng hiện tại ra bảng điều khiển

Tất nhiên, các lệnh của bạn cần những nơi xảy ra. adventurelib cung cấp lớp

(venv) $ python -m pygame.examples.aliens
56 để xác định các khu vực khác nhau trong thế giới trò chơi của bạn. Các phòng được tạo bằng cách cung cấp mô tả về phòng và chúng có thể được kết nối với các phòng khác bằng cách sử dụng các thuộc tính
(venv) $ python -m pygame.examples.aliens
57,
(venv) $ python -m pygame.examples.aliens
58,
(venv) $ python -m pygame.examples.aliens
59 và
(venv) $ python -m pygame.examples.aliens
60. Bạn cũng có thể xác định các thuộc tính tùy chỉnh áp dụng cho toàn bộ lớp
(venv) $ python -m pygame.examples.aliens
56 hoặc các đối tượng riêng lẻ

Ba phòng trong trò chơi này được tạo trên các dòng 15 đến 35. Hàm tạo

(venv) $ python -m pygame.examples.aliens
62 chấp nhận mô tả dưới dạng chuỗi hoặc trong trường hợp này là chuỗi nhiều dòng. Khi bạn đã tạo các phòng, sau đó bạn kết nối chúng trên các dòng 38 đến 39. Đặt
(venv) $ python -m pygame.examples.aliens
63 thành
(venv) $ python -m pygame.examples.aliens
64 ngụ ý rằng
(venv) $ python -m pygame.examples.aliens
65 sẽ là
(venv) $ python -m pygame.examples.aliens
66. adventurelib đủ thông minh để tạo kết nối này tự động

Bạn cũng tạo một ràng buộc trên dòng 44 để chỉ ra một cánh cửa bị khóa giữa phòng khách và hiên trước. Mở khóa cánh cửa này sẽ yêu cầu người chơi xác định vị trí vật phẩm

Trò chơi dựa trên văn bản thường có các vật phẩm phải được thu thập để mở các khu vực mới của trò chơi hoặc để giải một số câu đố. Các vật phẩm cũng có thể đại diện cho các nhân vật không phải người chơi mà người chơi có thể tương tác. adventurelib cung cấp lớp

(venv) $ python -m pygame.examples.aliens
67 để xác định cả vật phẩm có thể sưu tập và nhân vật không phải người chơi theo tên và bí danh của họ. Ví dụ: bí danh
(venv) $ python -m pygame.examples.aliens
68 đề cập đến chìa khóa cửa trước

Công cụ trò chơi dựa trên văn bản Python

Ở dòng 63, bạn xác định

(venv) $ python -m pygame.examples.aliens
68 dùng để mở khóa cửa giữa phòng khách và hiên trước. Hàm tạo
(venv) $ python -m pygame.examples.aliens
70 nhận một hoặc nhiều chuỗi. Đầu tiên là tên đầy đủ hoặc mặc định của mục và nó được sử dụng khi in tên của mục. Tất cả các tên khác được sử dụng làm bí danh để người chơi không phải nhập tên đầy đủ của vật phẩm

(venv) $ python -m pygame.examples.aliens
68 không chỉ có tên và bí danh. Nó cũng có mục đích sử dụng, được định nghĩa ở dòng 64.
(venv) $ python -m pygame.examples.aliens
72 đề cập đến một chức năng sẽ được gọi khi người chơi cố gắng sử dụng vật phẩm bằng cách gõ
(venv) $ python -m pygame.examples.aliens
73. Hàm này được gọi trong trình xử lý lệnh
(venv) $ python -m pygame.examples.aliens
74 được xác định trên các dòng 159 đến 175

Bộ sưu tập vật phẩm, chẳng hạn như hành trang của người chơi hoặc vật phẩm trên mặt đất trong phòng, có thể được lưu trữ trong một đồ vật

(venv) $ python -m pygame.examples.aliens
75. Bạn có thể thêm đồ vào túi, lấy đồ ra khỏi túi và kiểm tra bên trong túi.
(venv) $ python -m pygame.examples.aliens
75 đối tượng có thể lặp lại trong Python, vì vậy bạn cũng có thể sử dụng
(venv) $ python -m pygame.examples.aliens
77 để kiểm tra xem có thứ gì trong túi hay không và lặp qua nội dung của túi trong vòng lặp
(venv) $ python -m pygame.examples.aliens
78

Bốn đối tượng

(venv) $ python -m pygame.examples.aliens
75 khác nhau được định nghĩa trên các dòng 67 đến 75. Mỗi phòng trong số ba phòng có một
(venv) $ python -m pygame.examples.aliens
75 để chứa các vật phẩm trong phòng và người chơi cũng có một
(venv) $ python -m pygame.examples.aliens
75 để giữ
(venv) $ python -m pygame.examples.aliens
82 vật phẩm mà họ nhặt được. Mục
(venv) $ python -m pygame.examples.aliens
68 được đặt ở vị trí bắt đầu của nó trong
(venv) $ python -m pygame.examples.aliens
66

Các vật phẩm được thêm vào kho của người chơi bằng hàm

(venv) $ python -m pygame.examples.aliens
85 được xác định trên các dòng 140 đến 156. Khi người chơi gõ
(venv) $ python -m pygame.examples.aliens
86, bạn cố gắng lấy
(venv) $ python -m pygame.examples.aliens
87 vật phẩm từ túi
(venv) $ python -m pygame.examples.aliens
88 của phòng trên dòng 151. Nếu
(venv) $ python -m pygame.examples.aliens
68 được trả lại, nó cũng bị xóa khỏi phòng
(venv) $ python -m pygame.examples.aliens
88. Sau đó, bạn thêm
(venv) $ python -m pygame.examples.aliens
68 vào số
(venv) $ python -m pygame.examples.aliens
82 của người chơi trên dòng 156

Remove ads

Ứng dụng nâng cao

Tất nhiên, có nhiều hơn nữa để phiêu lưulib. Để thể hiện các khả năng khác của nó, bạn sẽ tạo ra một cuộc phiêu lưu văn bản hấp dẫn hơn với cốt truyện sau

  • Bạn sống trong một xóm nhỏ yên tĩnh
  • Gần đây, những người hàng xóm của bạn đã bắt đầu phàn nàn về việc gia súc bị mất tích
  • Là một thành viên của đội tuần tra ban đêm, bạn nhận thấy một hàng rào bị gãy và một con đường mòn dẫn ra khỏi đó
  • Bạn quyết định điều tra, chỉ được trang bị một thanh kiếm luyện tập bằng gỗ

Trò chơi có một số khu vực để mô tả và xác định

  • Xóm nhỏ yên tĩnh của bạn
  • Con đường mòn dẫn ra khỏi cánh đồng
  • Một ngôi làng gần đó, nơi bạn có thể mua vũ khí tốt hơn
  • Một con đường phụ dẫn đến một thuật sĩ có thể mê hoặc vũ khí của bạn
  • Một hang động chứa người khổng lồ đã bắt gia súc của bạn

Có một số vật phẩm để thu thập, chẳng hạn như vũ khí và thức ăn, và các nhân vật để tương tác. Bạn cũng cần một hệ thống chiến đấu cơ bản để cho phép bạn chiến đấu với người khổng lồ và giành chiến thắng trong trò chơi

Tất cả mã cho trò chơi này được liệt kê bên dưới và có thể tìm thấy trong các tài liệu đã tải xuống

Get Source Code. Click here to get the source code you’ll use to try out Python game engines

Để giữ mọi thứ ngăn nắp, bạn chia trò chơi của mình thành các tệp khác nhau

  • (venv) $ python -m pygame.examples.aliens
    
    93 xác định các phòng và khu vực
  • (venv) $ python -m pygame.examples.aliens
    
    94 định nghĩa các mục và thuộc tính của chúng
  • (venv) $ python -m pygame.examples.aliens
    
    95 xác định các ký tự mà bạn có thể tương tác
  • (venv) $ python -m pygame.examples.aliens
    
    96 kéo mọi thứ lại với nhau, thêm lệnh và bắt đầu trò chơi

Nguồn cho

(venv) $ python -m pygame.examples.aliens
96Hiển thị/Ẩn

(venv) $ python -m pygame.examples.aliens
7

Nguồn cho

(venv) $ python -m pygame.examples.aliens
93Hiển thị/Ẩn

(venv) $ python -m pygame.examples.aliens
8

Nguồn cho

(venv) $ python -m pygame.examples.aliens
94Hiển thị/Ẩn

(venv) $ python -m pygame.examples.aliens
9

Nguồn cho

(venv) $ python -m pygame.examples.aliens
95Hiển thị/Ẩn

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
0

Bạn có thể bắt đầu trò chơi này bằng lệnh sau

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
1

Sau khi xác định cốt truyện, bạn đã vạch ra các khu vực trò chơi khác nhau và các con đường mà người chơi sử dụng để di chuyển giữa chúng

Công cụ trò chơi dựa trên văn bản Python

Mỗi khu vực có các thuộc tính khác nhau được liên kết với nó, bao gồm

  • Các vật phẩm và nhân vật trong khu vực đó
  • Một số lối ra đã bị khóa
  • Tiêu đề, mô tả ngắn và mô tả dài hơn
  • Một dấu hiệu cho biết người chơi đã ở trong khu vực này hay chưa

Để đảm bảo rằng mỗi khu vực có phiên bản riêng của từng thuộc tính này, bạn tạo một lớp con của

(venv) $ python -m pygame.examples.aliens
56 được gọi là
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
02 trong
(venv) $ python -m pygame.examples.aliens
93 trên các dòng từ 15 đến 41. Các mục trong mỗi phòng được lưu trữ trong một đối tượng
(venv) $ python -m pygame.examples.aliens
75 được gọi là
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
05, trong khi các ký tự được lưu trữ trong
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
06, được xác định trên các dòng 28 và 31. Giờ đây, bạn có thể tạo
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
02 đối tượng, mô tả chúng và điền vào chúng các mục và ký tự duy nhất, tất cả đều được nhập vào dòng 9 và 12

Một số vật phẩm trò chơi được yêu cầu để hoàn thành trò chơi, trong khi những vật phẩm khác chỉ ở đó để tạo hương vị và thêm hứng thú. Các mục hương vị được xác định và đặt trên các dòng 192 đến 194, theo sau là các ký tự trên các dòng 197 đến 200

Tất cả các vật phẩm trò chơi của bạn được định nghĩa trong

(venv) $ python -m pygame.examples.aliens
94 là đối tượng thuộc loại
(venv) $ python -m pygame.examples.aliens
70. Các vật phẩm trò chơi có các thuộc tính xác định chúng, nhưng vì bạn đã sử dụng lớp cơ sở
(venv) $ python -m pygame.examples.aliens
67 nên một số thuộc tính phổ quát cơ bản được thêm vào lớp trên các dòng từ 9 đến 12. Các thuộc tính này được sử dụng khi mục được tạo. Ví dụ: đối tượng
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
11 được tạo từ dòng 15 đến dòng 19 và xác định từng thuộc tính chung khi nó được tạo

Tuy nhiên, một số mặt hàng có các thuộc tính cụ thể dành riêng cho mặt hàng đó. Ví dụ: các vật phẩm

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
12 và
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
13 cần có thuộc tính để theo dõi thiệt hại mà chúng gây ra và mọi phần thưởng ma thuật mà chúng mang theo. Chúng được thêm vào các dòng 43 đến 44 và 53 đến 54

Tương tác với các nhân vật giúp thúc đẩy câu chuyện trò chơi tiến lên và thường mang lại cho người chơi lý do để khám phá. Các nhân vật trong adventurelib được tạo dưới dạng đối tượng

(venv) $ python -m pygame.examples.aliens
67 và đối với trò chơi này được xác định trong
(venv) $ python -m pygame.examples.aliens
95

Mỗi nhân vật, giống như mỗi vật phẩm, có các thuộc tính phổ biến liên quan đến nó, chẳng hạn như mô tả dài và lời chào được sử dụng khi người chơi gặp lần đầu tiên. Các thuộc tính này được khai báo trên dòng 9 và 10 và chúng được xác định cho từng ký tự khi ký tự được tạo

Tất nhiên, nếu bạn có các nhân vật, thì người chơi sẽ nói chuyện và tương tác với họ. Bạn nên biết khi nào bạn đang tương tác với một nhân vật và khi nào bạn chỉ ở trong cùng một khu vực trò chơi với một nhân vật.

Điều này được thực hiện bằng cách sử dụng một khái niệm phiêu lưu được gọi là bối cảnh. Bối cảnh cho phép bạn bật các lệnh khác nhau cho các tình huống khác nhau. Chúng cũng cho phép một số lệnh nhất định hoạt động khác đi và chúng theo dõi thông tin bổ sung về các hành động mà người chơi có thể đã thực hiện

Khi trò chơi bắt đầu, không có bối cảnh nào được đặt. Khi người chơi tiến bộ, lần đầu tiên họ chạm trán với Elder Barron. Khi người chơi gõ

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
16, bối cảnh được đặt thành
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
17, trong trường hợp này là
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
18

Lời chào của Elder Barron kết thúc bằng câu hỏi có hoặc không cho người chơi. Nếu người chơi gõ

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
19, thì trình xử lý lệnh trên dòng 173 trong
(venv) $ python -m pygame.examples.aliens
96 được kích hoạt, được xác định là
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
21, như hình bên dưới

Công cụ trò chơi dựa trên văn bản Python

Sau đó, khi người chơi nói chuyện với thợ rèn, bối cảnh ở cấp độ thứ hai sẽ được thêm vào để phản ánh rằng họ đang tham gia vào một giao dịch vũ khí có thể xảy ra. Dòng 203 đến 233 xác định cuộc thảo luận với người thợ rèn, trong đó bao gồm đề nghị mua bán vũ khí. Một bối cảnh mới được xác định trên dòng 222, cho phép cùng một lệnh

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
19 được sử dụng một cách tao nhã theo nhiều cách

Bạn cũng có thể kiểm tra ngữ cảnh trong trình xử lý lệnh. Ví dụ: người chơi không thể rời khỏi cuộc chiến với người khổng lồ bằng cách kết thúc cuộc trò chuyện. Trình xử lý lệnh

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
23 được xác định trên các dòng 389 đến 403 kiểm tra xem người chơi có ở trong ngữ cảnh
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
24 hay không, được nhập vào khi họ bắt đầu chiến đấu với người khổng lồ. Nếu vậy, họ không được phép dừng cuộc trò chuyện - đó là một cuộc chiến sinh tử

Bạn cũng có thể đặt câu hỏi cho người chơi yêu cầu câu trả lời cụ thể. Khi người chơi nói chuyện với thuật sĩ Trent, họ được yêu cầu giải một câu đố. Trả lời sai sẽ kết thúc tương tác. Mặc dù câu trả lời đúng được xử lý bằng trình xử lý lệnh trên các dòng từ 252 đến 262, một trong những câu trả lời sai gần như vô hạn sẽ không khớp với bất kỳ trình xử lý nào

Các lệnh không khớp được xử lý bởi hàm

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
25 trên các dòng 497 đến 503. Bạn tận dụng điều này để xử lý các câu trả lời sai cho câu đố của thuật sĩ bằng cách kiểm tra ngữ cảnh
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
26 trên dòng 498. Bất kỳ câu trả lời sai nào cho câu đố sẽ dẫn đến việc thuật sĩ kết thúc cuộc trò chuyện. Bạn kết nối điều này với adventurelib trên dòng 523 bằng cách đặt
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
27 thành chức năng mới của bạn

Bạn có thể tùy chỉnh lời nhắc hiển thị cho trình phát bằng cách viết một hàm trả về lời nhắc mới. Lời nhắc mới của bạn được xác định trên các dòng 483 đến 495 và được kết nối với adventurelib trên dòng 520

Tất nhiên, luôn có nhiều thứ mà bạn có thể thêm vào. Tạo một trò chơi phiêu lưu văn bản hoàn chỉnh là một thách thức và adventurelib đảm bảo rằng thách thức chính nằm ở việc vẽ một bức tranh bằng từ ngữ

Remove ads

Ren'Py

Hậu duệ hiện đại của cuộc phiêu lưu văn bản thuần túy là tiểu thuyết trực quan, làm nổi bật khía cạnh kể chuyện của trò chơi, hạn chế tương tác của người chơi trong khi thêm hình ảnh và âm thanh để nâng cao trải nghiệm. Tiểu thuyết hình ảnh là tiểu thuyết đồ họa của thế giới trò chơi — hiện đại, đổi mới và cực kỳ hấp dẫn để tạo và tiêu thụ

Ren'Py là một công cụ dựa trên Pygame và được thiết kế đặc biệt để tạo tiểu thuyết trực quan. Ren'Py lấy tên từ tiếng Nhật có nghĩa là tình yêu lãng mạn và cung cấp các công cụ cũng như khuôn khổ để tạo ra các tiểu thuyết trực quan hấp dẫn

Công bằng mà nói, Ren’Py không hoàn toàn là một thư viện Python mà bạn có thể

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
28 và sử dụng. Các trò chơi Ren'Py được tạo bằng Trình khởi chạy Ren'Py, đi kèm với SDK Ren'Py đầy đủ. Trình khởi chạy này cũng có trình chỉnh sửa trò chơi, mặc dù bạn có thể chỉnh sửa trò chơi của mình trong trình chỉnh sửa bạn chọn. Ren'Py cũng có ngôn ngữ kịch bản riêng để tạo trò chơi. Tuy nhiên, Ren'Py dựa trên Pygame và có thể mở rộng bằng Python, điều này đảm bảo sự xuất hiện của nó tại đây

Cài đặt Ren'Py

Như đã đề cập, Ren'Py không chỉ yêu cầu SDK mà còn cả Trình khởi chạy Ren'Py. Chúng được đóng gói cùng nhau trong một đơn vị duy nhất mà bạn cần tải xuống

Biết gói nào cần tải xuống và cách cài đặt tùy thuộc vào nền tảng của bạn. Ren’Py cung cấp trình cài đặt và hướng dẫn cho người dùng Windows, macOS và Linux

Người dùng Windows nên tải xuống tệp thực thi được cung cấp, sau đó chạy nó để cài đặt SDK và Trình khởi chạy Ren'Py

Người dùng Linux nên tải xuống tarball được cung cấp ở một vị trí thuận tiện, sau đó mở rộng nó bằng cách sử dụng

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
29

Người dùng macOS nên tải xuống tệp DMG được cung cấp, nhấp đúp vào tệp để mở và sao chép nội dung vào một vị trí thuận tiện

Sau khi gói được cài đặt, bạn có thể điều hướng đến thư mục chứa SDK rồi chạy Trình khởi chạy Ren'Py. Người dùng Windows nên sử dụng

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
30, trong khi người dùng macOS và Linux nên chạy
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
31. Thao tác này sẽ khởi động Trình khởi chạy Ren'Py lần đầu tiên

Công cụ trò chơi dựa trên văn bản Python

Đây là nơi bạn sẽ bắt đầu các dự án Ren'Py mới, làm việc trên các dự án hiện có và đặt các tùy chọn tổng thể cho Ren'Py

Basic Concepts

Trò chơi Ren'Py bắt đầu dưới dạng dự án mới trong Trình khởi chạy Ren'Py. Tạo một cái sẽ thiết lập cấu trúc tệp và thư mục thích hợp cho trò chơi Ren'Py. Sau khi dự án được thiết lập, bạn có thể sử dụng trình chỉnh sửa của riêng mình để viết trò chơi của mình, mặc dù cần phải có Trình khởi chạy Ren'Py để chạy trò chơi

Công cụ trò chơi dựa trên văn bản Python

Các trò chơi Ren'Py được chứa trong các tệp có tên là tập lệnh. Đừng nghĩ về các tập lệnh Ren'Py như cách bạn nghĩ về các tập lệnh shell. Chúng tương tự như kịch bản cho các vở kịch hoặc chương trình truyền hình. Chữ viết Ren’Py có phần mở rộng là

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
32 và được viết bằng ngôn ngữ Ren’Py. Trò chơi của bạn có thể bao gồm bao nhiêu kịch bản tùy thích, tất cả đều được lưu trữ trong thư mục con
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
33 của thư mục dự án của bạn

Khi bạn tạo một dự án Ren’Py mới, các tập lệnh sau sẽ được tạo để bạn sử dụng và cập nhật

  •  1"""
     2Basic "Hello, World!" program in Pygame
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10- Allow you to close the window
    11"""
    12
    13# Import and initialize the pygame library
    14import pygame
    15
    16pygame.init()
    17
    18# Set the width and height of the output window, in pixels
    19WIDTH = 800
    20HEIGHT = 600
    21
    22# Set up the drawing window
    23screen = pygame.display.set_mode([WIDTH, HEIGHT])
    24
    25# Run until the user asks to quit
    26running = True
    27while running:
    28
    29    # Did the user click the window close button?
    30    for event in pygame.event.get():
    31        if event.type == pygame.QUIT:
    32            running = False
    33
    34    # Fill the background with white
    35    screen.fill((255, 255, 255))
    36
    37    # Draw a blue circle with a radius of 50 in the center of the screen
    38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
    39
    40    # Draw a red-outlined square in the top-left corner of the screen
    41    red_square = pygame.Rect((50, 50), (100, 100))
    42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
    43
    44    # Draw an orange caption along the bottom in 60-point font
    45    text_font = pygame.font.SysFont("any_font", 60)
    46    text_block = text_font.render(
    47        "Hello, World! From Pygame", False, (200, 100, 0)
    48    )
    49    screen.blit(text_block, (50, HEIGHT - 50))
    50
    51    # Flip the display
    52    pygame.display.flip()
    53
    54# Done! Time to quit.
    55pygame.quit()
    
    34, xác định giao diện của tất cả các thành phần giao diện người dùng được sử dụng trong trò chơi của bạn
  •  1"""
     2Basic "Hello, World!" program in Pygame
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10- Allow you to close the window
    11"""
    12
    13# Import and initialize the pygame library
    14import pygame
    15
    16pygame.init()
    17
    18# Set the width and height of the output window, in pixels
    19WIDTH = 800
    20HEIGHT = 600
    21
    22# Set up the drawing window
    23screen = pygame.display.set_mode([WIDTH, HEIGHT])
    24
    25# Run until the user asks to quit
    26running = True
    27while running:
    28
    29    # Did the user click the window close button?
    30    for event in pygame.event.get():
    31        if event.type == pygame.QUIT:
    32            running = False
    33
    34    # Fill the background with white
    35    screen.fill((255, 255, 255))
    36
    37    # Draw a blue circle with a radius of 50 in the center of the screen
    38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
    39
    40    # Draw a red-outlined square in the top-left corner of the screen
    41    red_square = pygame.Rect((50, 50), (100, 100))
    42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
    43
    44    # Draw an orange caption along the bottom in 60-point font
    45    text_font = pygame.font.SysFont("any_font", 60)
    46    text_block = text_font.render(
    47        "Hello, World! From Pygame", False, (200, 100, 0)
    48    )
    49    screen.blit(text_block, (50, HEIGHT - 50))
    50
    51    # Flip the display
    52    pygame.display.flip()
    53
    54# Done! Time to quit.
    55pygame.quit()
    
    35, xác định các tùy chọn có thể thay đổi để tùy chỉnh trò chơi của bạn
  •  1"""
     2Basic "Hello, World!" program in Pygame
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10- Allow you to close the window
    11"""
    12
    13# Import and initialize the pygame library
    14import pygame
    15
    16pygame.init()
    17
    18# Set the width and height of the output window, in pixels
    19WIDTH = 800
    20HEIGHT = 600
    21
    22# Set up the drawing window
    23screen = pygame.display.set_mode([WIDTH, HEIGHT])
    24
    25# Run until the user asks to quit
    26running = True
    27while running:
    28
    29    # Did the user click the window close button?
    30    for event in pygame.event.get():
    31        if event.type == pygame.QUIT:
    32            running = False
    33
    34    # Fill the background with white
    35    screen.fill((255, 255, 255))
    36
    37    # Draw a blue circle with a radius of 50 in the center of the screen
    38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
    39
    40    # Draw a red-outlined square in the top-left corner of the screen
    41    red_square = pygame.Rect((50, 50), (100, 100))
    42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
    43
    44    # Draw an orange caption along the bottom in 60-point font
    45    text_font = pygame.font.SysFont("any_font", 60)
    46    text_block = text_font.render(
    47        "Hello, World! From Pygame", False, (200, 100, 0)
    48    )
    49    screen.blit(text_block, (50, HEIGHT - 50))
    50
    51    # Flip the display
    52    pygame.display.flip()
    53
    54# Done! Time to quit.
    55pygame.quit()
    
    36, xác định các kiểu được sử dụng cho hội thoại, menu và đầu ra trò chơi khác
  •  1"""
     2Basic "Hello, World!" program in Pygame
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10- Allow you to close the window
    11"""
    12
    13# Import and initialize the pygame library
    14import pygame
    15
    16pygame.init()
    17
    18# Set the width and height of the output window, in pixels
    19WIDTH = 800
    20HEIGHT = 600
    21
    22# Set up the drawing window
    23screen = pygame.display.set_mode([WIDTH, HEIGHT])
    24
    25# Run until the user asks to quit
    26running = True
    27while running:
    28
    29    # Did the user click the window close button?
    30    for event in pygame.event.get():
    31        if event.type == pygame.QUIT:
    32            running = False
    33
    34    # Fill the background with white
    35    screen.fill((255, 255, 255))
    36
    37    # Draw a blue circle with a radius of 50 in the center of the screen
    38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
    39
    40    # Draw a red-outlined square in the top-left corner of the screen
    41    red_square = pygame.Rect((50, 50), (100, 100))
    42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
    43
    44    # Draw an orange caption along the bottom in 60-point font
    45    text_font = pygame.font.SysFont("any_font", 60)
    46    text_block = text_font.render(
    47        "Hello, World! From Pygame", False, (200, 100, 0)
    48    )
    49    screen.blit(text_block, (50, HEIGHT - 50))
    50
    51    # Flip the display
    52    pygame.display.flip()
    53
    54# Done! Time to quit.
    55pygame.quit()
    
    37, đó là nơi bạn bắt đầu viết trò chơi của mình

Để chạy các trò chơi mẫu từ các tài liệu đã tải xuống cho hướng dẫn này, bạn sẽ sử dụng quy trình sau

  1. Khởi động Trình khởi chạy Ren'Py
  2. Nhấp vào Tùy chọn, sau đó nhấp vào Thư mục dự án
  3. Thay đổi Thư mục Dự án thành thư mục
     1"""
     2Basic "Hello, World!" program in Pygame
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10- Allow you to close the window
    11"""
    12
    13# Import and initialize the pygame library
    14import pygame
    15
    16pygame.init()
    17
    18# Set the width and height of the output window, in pixels
    19WIDTH = 800
    20HEIGHT = 600
    21
    22# Set up the drawing window
    23screen = pygame.display.set_mode([WIDTH, HEIGHT])
    24
    25# Run until the user asks to quit
    26running = True
    27while running:
    28
    29    # Did the user click the window close button?
    30    for event in pygame.event.get():
    31        if event.type == pygame.QUIT:
    32            running = False
    33
    34    # Fill the background with white
    35    screen.fill((255, 255, 255))
    36
    37    # Draw a blue circle with a radius of 50 in the center of the screen
    38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
    39
    40    # Draw a red-outlined square in the top-left corner of the screen
    41    red_square = pygame.Rect((50, 50), (100, 100))
    42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
    43
    44    # Draw an orange caption along the bottom in 60-point font
    45    text_font = pygame.font.SysFont("any_font", 60)
    46    text_block = text_font.render(
    47        "Hello, World! From Pygame", False, (200, 100, 0)
    48    )
    49    screen.blit(text_block, (50, HEIGHT - 50))
    50
    51    # Flip the display
    52    pygame.display.flip()
    53
    54# Done! Time to quit.
    55pygame.quit()
    
    38 trong kho lưu trữ mà bạn đã tải xuống
  4. Nhấp vào Quay lại để quay lại trang Trình khởi chạy Ren'Py chính

Bạn sẽ thấy

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
39 và
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
40 trong danh sách Dự án ở bên trái. Chọn cái mà bạn muốn chạy, sau đó nhấp vào Launch Project

Đối với ví dụ này, bạn sẽ chỉ sửa đổi tệp

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
37 cho
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
39. Bạn có thể tìm thấy mã hoàn chỉnh cho trò chơi này trong các tài liệu đã tải xuống, cũng như bên dưới

Nguồn cho

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
37Hiển thị/Ẩn

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
2

Nhãn xác định các điểm vào câu chuyện của bạn và thường được sử dụng để bắt đầu các cảnh mới và cung cấp các đường dẫn thay thế xuyên suốt câu chuyện. Tất cả các trò chơi Ren'Py bắt đầu chạy ở dòng

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
44, có thể xuất hiện trong bất kỳ tập lệnh nào bạn chọn. Bạn có thể thấy điều này trên dòng 12 của
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
37

Bạn cũng có thể sử dụng nhãn để xác định hình nền, thiết lập chuyển tiếp giữa các cảnh và kiểm soát sự xuất hiện của các ký tự. Trong mẫu, cảnh thứ hai bắt đầu ở dòng 54 với dòng

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
46

Văn bản đặt trong dấu ngoặc kép trên một dòng được gọi là câu lệnh say. Một chuỗi trên một dòng được coi là tường thuật. Hai chuỗi được coi là đối thoại, trước tiên xác định một ký tự và sau đó cung cấp dòng mà chúng đang nói

Khi bắt đầu trò chơi, tường thuật được nhìn thấy ở dòng 16, tạo bối cảnh. Đối thoại được cung cấp trên dòng 18, khi mẹ bạn gọi cho bạn

Bạn có thể xác định các nhân vật bằng cách đặt tên cho họ trong câu chuyện. Tuy nhiên, bạn cũng có thể xác định các ký tự ở đầu tập lệnh của mình. Bạn có thể thấy điều này trên dòng 6 đến 8, nơi bạn, anh trai Kevin và mẹ của bạn được xác định. Câu lệnh

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
47 khởi tạo ba biến là
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
48, đặt cho chúng một tên hiển thị, theo sau là màu văn bản được sử dụng để hiển thị tên

Tất nhiên, đây là visual novel nên Ren’Py sẽ có cách xử lý hình ảnh. Giống như Pygame Zero, Ren'Py yêu cầu tất cả hình ảnh và âm thanh được sử dụng trong trò chơi phải nằm trong các thư mục cụ thể. Hình ảnh nằm trong thư mục

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
49 và âm thanh nằm trong thư mục
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
50. Trong kịch bản trò chơi, bạn gọi chúng bằng tên tệp mà không có bất kỳ phần mở rộng tệp nào

Dòng 25 thể hiện điều này bằng hành động, khi bạn mở mắt và nhìn thấy phòng ngủ của mình lần đầu tiên. Từ khóa

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
51 xóa màn hình, sau đó hiển thị hình ảnh
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
52. Ren'Py hỗ trợ các định dạng hình ảnh JPG, WEBP và PNG

Bạn cũng có thể hiển thị các ký tự trên màn hình bằng cách sử dụng từ khóa

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
53 và cùng một quy ước đặt tên cho hình ảnh. Dòng 41 hiển thị hình ảnh của anh trai Kevin của bạn, được lưu dưới dạng
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
54

Tất nhiên, đó không phải là một trò chơi nếu bạn không thể đưa ra quyết định ảnh hưởng đến kết quả. Trong Ren’Py, người chơi đưa ra các lựa chọn từ menu được hiển thị cho họ trong quá trình chơi trò chơi. Trò chơi phản ứng bằng cách chuyển đến các nhãn được xác định trước, thay đổi hình ảnh nhân vật, phát âm thanh hoặc thực hiện các hành động khác khi cần thiết

Một lựa chọn cơ bản trong mẫu này được hiển thị trên các dòng 47 đến 52, nơi bạn nhận ra mình đã quên điện thoại. Trong một câu chuyện đầy đủ hơn, sự lựa chọn này có thể dẫn đến hậu quả sau này

Tất nhiên, bạn có thể làm được nhiều hơn thế với Ren’Py. Bạn có thể kiểm soát quá trình chuyển đổi giữa các cảnh, yêu cầu nhân vật vào và rời khỏi cảnh theo những cách cụ thể, đồng thời bao gồm âm thanh và nhạc cho trò chơi của bạn. Ren'Py cũng hỗ trợ viết mã Python phức tạp hơn, bao gồm sử dụng các kiểu dữ liệu Python và thực hiện các lệnh gọi hàm Python trực tiếp. Bây giờ hãy xem xét kỹ hơn các khả năng này trong một ứng dụng nâng cao hơn

Remove ads

Ứng dụng nâng cao

Để thể hiện chiều sâu của Ren'Py, bạn sẽ triển khai trò chơi tương tự như bạn đã làm với adventurelib. Xin nhắc lại, đây là thiết kế cơ bản của trò chơi đó

  • Bạn sống trong một xóm nhỏ yên tĩnh
  • Gần đây, những người hàng xóm của bạn đã bắt đầu phàn nàn về việc gia súc bị mất tích
  • Là một thành viên của đội tuần tra ban đêm, bạn nhận thấy một hàng rào bị gãy và một con đường mòn dẫn ra khỏi đó
  • Bạn quyết định điều tra, chỉ được trang bị một thanh kiếm luyện tập bằng gỗ

Trò chơi có một số khu vực để xác định và cung cấp hình ảnh cho. Ví dụ: bạn sẽ cần hình ảnh và định nghĩa cho ngôi làng nhỏ, yên tĩnh của mình, con đường mòn dẫn ra khỏi cánh đồng, ngôi làng gần đó nơi bạn có thể mua vũ khí tốt hơn, con đường phụ dẫn đến một phù thủy có thể yểm bùa cho vũ khí của bạn và

Ngoài ra còn có một vài ký tự để xác định và cung cấp hình ảnh cho. Bạn cần một thợ rèn có thể cung cấp cho bạn vũ khí tốt hơn, một phù thủy có thể phù phép vũ khí của bạn và tên khổng lồ mà bạn cần đánh bại

Đối với ví dụ này, bạn sẽ tạo bốn tập lệnh riêng biệt

  •  1"""
     2Basic "Hello, World!" program in Pygame
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10- Allow you to close the window
    11"""
    12
    13# Import and initialize the pygame library
    14import pygame
    15
    16pygame.init()
    17
    18# Set the width and height of the output window, in pixels
    19WIDTH = 800
    20HEIGHT = 600
    21
    22# Set up the drawing window
    23screen = pygame.display.set_mode([WIDTH, HEIGHT])
    24
    25# Run until the user asks to quit
    26running = True
    27while running:
    28
    29    # Did the user click the window close button?
    30    for event in pygame.event.get():
    31        if event.type == pygame.QUIT:
    32            running = False
    33
    34    # Fill the background with white
    35    screen.fill((255, 255, 255))
    36
    37    # Draw a blue circle with a radius of 50 in the center of the screen
    38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
    39
    40    # Draw a red-outlined square in the top-left corner of the screen
    41    red_square = pygame.Rect((50, 50), (100, 100))
    42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
    43
    44    # Draw an orange caption along the bottom in 60-point font
    45    text_font = pygame.font.SysFont("any_font", 60)
    46    text_block = text_font.render(
    47        "Hello, World! From Pygame", False, (200, 100, 0)
    48    )
    49    screen.blit(text_block, (50, HEIGHT - 50))
    50
    51    # Flip the display
    52    pygame.display.flip()
    53
    54# Done! Time to quit.
    55pygame.quit()
    
    37, đó là nơi trò chơi bắt đầu
  •  1"""
     2Basic "Hello, World!" program in Pygame
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10- Allow you to close the window
    11"""
    12
    13# Import and initialize the pygame library
    14import pygame
    15
    16pygame.init()
    17
    18# Set the width and height of the output window, in pixels
    19WIDTH = 800
    20HEIGHT = 600
    21
    22# Set up the drawing window
    23screen = pygame.display.set_mode([WIDTH, HEIGHT])
    24
    25# Run until the user asks to quit
    26running = True
    27while running:
    28
    29    # Did the user click the window close button?
    30    for event in pygame.event.get():
    31        if event.type == pygame.QUIT:
    32            running = False
    33
    34    # Fill the background with white
    35    screen.fill((255, 255, 255))
    36
    37    # Draw a blue circle with a radius of 50 in the center of the screen
    38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
    39
    40    # Draw a red-outlined square in the top-left corner of the screen
    41    red_square = pygame.Rect((50, 50), (100, 100))
    42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
    43
    44    # Draw an orange caption along the bottom in 60-point font
    45    text_font = pygame.font.SysFont("any_font", 60)
    46    text_block = text_font.render(
    47        "Hello, World! From Pygame", False, (200, 100, 0)
    48    )
    49    screen.blit(text_block, (50, HEIGHT - 50))
    50
    51    # Flip the display
    52    pygame.display.flip()
    53
    54# Done! Time to quit.
    55pygame.quit()
    
    56, trong đó có câu chuyện về ngôi làng gần đó
  •  1"""
     2Basic "Hello, World!" program in Pygame
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10- Allow you to close the window
    11"""
    12
    13# Import and initialize the pygame library
    14import pygame
    15
    16pygame.init()
    17
    18# Set the width and height of the output window, in pixels
    19WIDTH = 800
    20HEIGHT = 600
    21
    22# Set up the drawing window
    23screen = pygame.display.set_mode([WIDTH, HEIGHT])
    24
    25# Run until the user asks to quit
    26running = True
    27while running:
    28
    29    # Did the user click the window close button?
    30    for event in pygame.event.get():
    31        if event.type == pygame.QUIT:
    32            running = False
    33
    34    # Fill the background with white
    35    screen.fill((255, 255, 255))
    36
    37    # Draw a blue circle with a radius of 50 in the center of the screen
    38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
    39
    40    # Draw a red-outlined square in the top-left corner of the screen
    41    red_square = pygame.Rect((50, 50), (100, 100))
    42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
    43
    44    # Draw an orange caption along the bottom in 60-point font
    45    text_font = pygame.font.SysFont("any_font", 60)
    46    text_block = text_font.render(
    47        "Hello, World! From Pygame", False, (200, 100, 0)
    48    )
    49    screen.blit(text_block, (50, HEIGHT - 50))
    50
    51    # Flip the display
    52    pygame.display.flip()
    53
    54# Done! Time to quit.
    55pygame.quit()
    
    57, trong đó có con đường giữa các làng
  •  1"""
     2Basic "Hello, World!" program in Pygame
     3
     4This program is designed to demonstrate the basic capabilities
     5of Pygame. It will:
     6- Create a game window
     7- Fill the background with white
     8- Draw some basic shapes in different colors
     9- Draw some text in a specified size and color
    10- Allow you to close the window
    11"""
    12
    13# Import and initialize the pygame library
    14import pygame
    15
    16pygame.init()
    17
    18# Set the width and height of the output window, in pixels
    19WIDTH = 800
    20HEIGHT = 600
    21
    22# Set up the drawing window
    23screen = pygame.display.set_mode([WIDTH, HEIGHT])
    24
    25# Run until the user asks to quit
    26running = True
    27while running:
    28
    29    # Did the user click the window close button?
    30    for event in pygame.event.get():
    31        if event.type == pygame.QUIT:
    32            running = False
    33
    34    # Fill the background with white
    35    screen.fill((255, 255, 255))
    36
    37    # Draw a blue circle with a radius of 50 in the center of the screen
    38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
    39
    40    # Draw a red-outlined square in the top-left corner of the screen
    41    red_square = pygame.Rect((50, 50), (100, 100))
    42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
    43
    44    # Draw an orange caption along the bottom in 60-point font
    45    text_font = pygame.font.SysFont("any_font", 60)
    46    text_block = text_font.render(
    47        "Hello, World! From Pygame", False, (200, 100, 0)
    48    )
    49    screen.blit(text_block, (50, HEIGHT - 50))
    50
    51    # Flip the display
    52    pygame.display.flip()
    53
    54# Done! Time to quit.
    55pygame.quit()
    
    58, chứa logic của trận chiến khổng lồ

Bạn có thể tạo cuộc gặp gỡ thuật sĩ như một bài tập độc lập

Bạn có thể tìm thấy mã hoàn chỉnh cho trò chơi này trong các tài liệu đã tải xuống tại

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
59 và cũng có sẵn bên dưới

Nguồn cho

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
37Hiển thị/Ẩn

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
3

Nguồn cho

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
56Hiển thị/Ẩn

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
4

Nguồn cho

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
57Hiển thị/Ẩn

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
5

Nguồn cho

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
58Hiển thị/Ẩn

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
6

Như trong ví dụ trước, bạn xác định đối tượng

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
64 trước khi tập lệnh bắt đầu từ dòng 14 đến 17 của
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
37

Bạn cũng có thể xác định các đối tượng nền hoặc ký tự

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
66 để sử dụng sau này. Các dòng 21 đến 27 xác định một số hình ảnh mà bạn tham khảo sau, cả để sử dụng làm hình nền và để hiển thị dưới dạng mục. Sử dụng cú pháp này cho phép bạn gán tên nội bộ ngắn hơn và mang tính mô tả hơn cho hình ảnh. Sau đó, bạn sẽ thấy chúng được hiển thị như thế nào

Bạn cũng cần theo dõi khả năng của vũ khí được trang bị. Điều này được thực hiện trên các dòng 31 đến 37, sử dụng các giá trị biến

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
67 mà bạn sẽ sử dụng trong trận chiến khổng lồ sau này

Để cho biết vũ khí nào được bật, bạn hiển thị hình ảnh dưới dạng biểu thức. Biểu cảm của Ren'Py là những hình ảnh nhỏ hiển thị ở các góc của cửa sổ trò chơi và được sử dụng để hiển thị nhiều thông tin khác nhau. Đối với trò chơi này, bạn sử dụng một biểu thức để chỉ vũ khí bằng cách sử dụng

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
68 đầu tiên ở dòng 67 và 68

Lệnh

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
53 có một số công cụ sửa đổi được ghi lại. Công cụ sửa đổi
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
70 làm cho hình ảnh
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
71 trượt trên màn hình từ bên trái. Ngoài ra, điều quan trọng cần nhớ là mỗi khi
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
51 thay đổi, toàn bộ màn hình sẽ bị xóa, yêu cầu bạn hiển thị lại vũ khí hiện tại. Bạn có thể thấy điều đó trên các dòng 75 đến 78

Khi bạn vào thị trấn vào năm

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
56, bạn gặp người thợ rèn, người này chào đón bạn

Công cụ trò chơi dựa trên văn bản Python

Thợ rèn mang đến cho bạn cơ hội nâng cấp vũ khí của mình. Nếu bạn chọn làm như vậy, thì bạn cập nhật các giá trị cho

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
71 và chỉ số vũ khí. Điều này được thực hiện trên các dòng 93 đến 98

Các dòng bắt đầu bằng ký tự

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
75 được Ren'Py hiểu là các câu lệnh Python, cho phép bạn viết mã Python tùy ý khi cần. Việc cập nhật số liệu thống kê về
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
71 và vũ khí được thực hiện bằng cách sử dụng ba câu lệnh Python từ dòng 96 đến 98, thay đổi giá trị của các biến số
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
67 mà bạn đã xác định ở đầu trang
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
37

Bạn cũng có thể xác định một khối mã Python lớn bằng cách sử dụng phần

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
79, như được hiển thị trong
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
58 bắt đầu từ dòng 41

Các dòng 43 đến 61 chứa chức năng trợ giúp để hiển thị tình trạng của người khổng lồ, dựa trên các điểm đánh còn lại của người khổng lồ. Nó sử dụng phương pháp

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
81 để xuất tường thuật trở lại cửa sổ Ren'Py chính. Một chức năng trợ giúp tương tự để hiển thị tình trạng của người chơi được nhìn thấy trên các dòng 63 đến 85

Trận chiến được điều khiển bởi

 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
82 trên các dòng 87 đến 159. Vòng lặp trò chơi được triển khai trên dòng 98 và được điều khiển bởi biến
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
83. Các lựa chọn chiến đấu hoặc chạy trốn của người chơi được hiển thị bằng phương pháp
 1"""
 2Basic "Hello, World!" program in Pygame
 3
 4This program is designed to demonstrate the basic capabilities
 5of Pygame. It will:
 6- Create a game window
 7- Fill the background with white
 8- Draw some basic shapes in different colors
 9- Draw some text in a specified size and color
10- Allow you to close the window
11"""
12
13# Import and initialize the pygame library
14import pygame
15
16pygame.init()
17
18# Set the width and height of the output window, in pixels
19WIDTH = 800
20HEIGHT = 600
21
22# Set up the drawing window
23screen = pygame.display.set_mode([WIDTH, HEIGHT])
24
25# Run until the user asks to quit
26running = True
27while running:
28
29    # Did the user click the window close button?
30    for event in pygame.event.get():
31        if event.type == pygame.QUIT:
32            running = False
33
34    # Fill the background with white
35    screen.fill((255, 255, 255))
36
37    # Draw a blue circle with a radius of 50 in the center of the screen
38    pygame.draw.circle(screen, (0, 0, 255), (WIDTH // 2, HEIGHT // 2), 50)
39
40    # Draw a red-outlined square in the top-left corner of the screen
41    red_square = pygame.Rect((50, 50), (100, 100))
42    pygame.draw.rect(screen, (200, 0, 0), red_square, 1)
43
44    # Draw an orange caption along the bottom in 60-point font
45    text_font = pygame.font.SysFont("any_font", 60)
46    text_block = text_font.render(
47        "Hello, World! From Pygame", False, (200, 100, 0)
48    )
49    screen.blit(text_block, (50, HEIGHT - 50))
50
51    # Flip the display
52    pygame.display.flip()
53
54# Done! Time to quit.
55pygame.quit()
84

Nếu người chơi chiến đấu, thì một lượng sát thương ngẫu nhiên sẽ được thực hiện trên các dòng 116 đến 118 và điểm đánh của người khổng lồ được điều chỉnh. Nếu người khổng lồ vẫn còn sống, thì họ sẽ tấn công theo cách tương tự ở các dòng 136 đến 149. Lưu ý rằng người khổng lồ có cơ hội bỏ lỡ, trong khi người chơi luôn đánh. Cuộc chiến tiếp tục cho đến khi người chơi hoặc người khổng lồ không có điểm trúng đích hoặc cho đến khi người chơi bỏ chạy

Công cụ trò chơi dựa trên văn bản Python

Điều quan trọng cần lưu ý là mã này rất giống với mã mà bạn đã sử dụng trong trận chiến adventurelib. Điều này cho thấy cách bạn có thể thả mã Python đầy đủ vào các trò chơi Ren'Py của mình mà không cần dịch nó sang tập lệnh Ren'Py

Ren'Py còn nhiều thứ hơn những gì bạn đã thử ở đây. Tham khảo tài liệu Ren'Py để biết thêm chi tiết đầy đủ

Remove ads

Các công cụ trò chơi Python đáng chú ý khác

Năm công cụ này chỉ là một mẫu nhỏ trong số nhiều công cụ trò chơi Python khác nhau hiện có. Có hàng chục người khác có sẵn, và một số đáng chú ý ở đây

  • Wasabi 2D được phát triển bởi nhóm đằng sau Pygame Zero. Đó là một khung hiện đại được xây dựng trên Moderngl để tự động hóa kết xuất, cung cấp coroutine cho các hiệu ứng hoạt hình, có các hiệu ứng hạt tích hợp và sử dụng mô hình hướng sự kiện để chơi trò chơi

  • cocos2d là một khung được thiết kế để mã hóa các trò chơi đa nền tảng. Rất tiếc, cocos2d-python đã không được cập nhật từ năm 2017

  • Panda 3D là một khung nguồn mở để tạo trò chơi 3D và kết xuất 3D. Panda 3D có thể di động trên các nền tảng, hỗ trợ nhiều loại nội dung, kết nối vượt trội với nhiều thư viện của bên thứ ba và cung cấp hồ sơ đường ống tích hợp sẵn

  • Ursina được xây dựng dựa trên Panda 3D và cung cấp một công cụ phát triển trò chơi chuyên dụng giúp đơn giản hóa nhiều khía cạnh của Panda 3D. Được hỗ trợ tốt và có nhiều tài liệu, Ursina đang được phát triển tích cực tại thời điểm viết bài này

  • PursuedPyBear được lập hóa đơn như một thư viện giáo dục. Nó tự hào có một hệ thống quản lý cảnh, các họa tiết hoạt hình dựa trên khung có thể tạm dừng và rào cản gia nhập thấp. Tài liệu còn thưa thớt, nhưng trợ giúp chỉ là một cuộc thảo luận trên GitHub

Công cụ trò chơi Python mới được tạo ra mỗi ngày. Nếu bạn tìm thấy một cái phù hợp với nhu cầu của mình và không được đề cập ở đây, hãy khen ngợi nó trong phần bình luận

Nguồn cho nội dung trò chơi

Thông thường, tạo nội dung trò chơi là vấn đề lớn nhất mà các tác giả trò chơi phải đối mặt. Các công ty trò chơi điện tử lớn tuyển dụng các nhóm nghệ sĩ, họa sĩ hoạt hình và nhạc sĩ để thiết kế giao diện và âm thanh cho trò chơi của họ. Các nhà phát triển trò chơi đơn lẻ có nền tảng về lập trình có thể thấy khó khăn trong khía cạnh phát triển trò chơi này. May mắn thay, có rất nhiều nguồn khác nhau cho nội dung trò chơi. Dưới đây là một số điều quan trọng trong việc định vị nội dung cho trò chơi trong hướng dẫn này

  • OpenGameArt. org lưu trữ nhiều loại nghệ thuật trò chơi, âm nhạc, hình nền, biểu tượng và các nội dung khác cho cả trò chơi 2D và 3D. Các nghệ sĩ và nhạc sĩ liệt kê nội dung của họ để tải xuống, bạn có thể tải xuống và sử dụng nội dung này trong trò chơi của mình. Hầu hết nội dung đều có sẵn miễn phí và các điều khoản cấp phép có thể áp dụng cho nhiều nội dung

  • Kenney. nl lưu trữ một bộ nội dung miễn phí và trả phí, nhiều nội dung trong số đó không thể tìm thấy ở nơi nào khác. Đóng góp luôn được chào đón để hỗ trợ các nội dung miễn phí, tất cả đều được cấp phép sử dụng trong các trò chơi thương mại

  • ngứa. io là thị trường dành cho những người sáng tạo kỹ thuật số tập trung vào phát triển trò chơi độc lập. Tại đây, bạn có thể tìm thấy nội dung kỹ thuật số cho bất kỳ mục đích nào, cả miễn phí và trả phí, cùng với các trò chơi hoàn chỉnh. Những người sáng tạo cá nhân kiểm soát nội dung của riêng họ tại đây, vì vậy bạn luôn làm việc trực tiếp với những cá nhân tài năng

Hầu hết các nội dung có sẵn từ bên thứ ba đều có các điều khoản cấp phép quy định việc sử dụng nội dung phù hợp và được phép. Là người dùng những nội dung này, bạn có trách nhiệm đọc, hiểu và tuân thủ các điều khoản cấp phép do chủ sở hữu nội dung xác định. Nếu bạn có câu hỏi hoặc thắc mắc về các điều khoản đó, vui lòng tham khảo ý kiến ​​chuyên gia pháp lý để được hỗ trợ

Tất cả nội dung được sử dụng trong các trò chơi được đề cập trong bài viết này đều tuân thủ các yêu cầu cấp phép tương ứng của chúng

Phần kết luận

Xin chúc mừng, thiết kế trò chơi tuyệt vời hiện đang trong tầm tay của bạn. Nhờ Python và một loạt các công cụ trò chơi Python có khả năng cao, bạn có thể tạo các trò chơi máy tính chất lượng dễ dàng hơn nhiều so với trước đây. Trong hướng dẫn này, bạn đã khám phá một số công cụ trò chơi như vậy, tìm hiểu thông tin mà bạn cần để bắt đầu tạo trò chơi điện tử Python của riêng mình

Đến bây giờ, bạn đã thấy một số công cụ trò chơi Python hàng đầu đang hoạt động và bạn đã

  • Khám phá những ưu và nhược điểm của một số công cụ trò chơi Python phổ biến
  • Trải nghiệm cách họ so sánh với các công cụ trò chơi độc lập
  • Đã tìm hiểu về các công cụ trò chơi Python khác có sẵn

Nếu bạn muốn xem lại mã cho các trò chơi trong hướng dẫn này, bạn có thể làm như vậy bằng cách nhấp vào liên kết bên dưới

Get Source Code. Click here to get the source code you’ll use to try out Python game engines

Bây giờ bạn có thể chọn công cụ trò chơi Python tốt nhất cho mục đích của mình. Bạn đang chờ đợi điều gì?

Đánh dấu là đã hoàn thành

🐍 Thủ thuật Python 💌

Nhận một Thủ thuật Python ngắn và hấp dẫn được gửi đến hộp thư đến của bạn vài ngày một lần. Không có thư rác bao giờ. Hủy đăng ký bất cứ lúc nào. Được quản lý bởi nhóm Real Python

Công cụ trò chơi dựa trên văn bản Python

Gửi cho tôi thủ thuật Python »

Giới thiệu về Jon Fincher

Công cụ trò chơi dựa trên văn bản Python
Công cụ trò chơi dựa trên văn bản Python

Jon đã dạy Python và Java tại hai trường trung học ở Bang Washington. Trước đây, ông là Giám đốc Chương trình tại Microsoft

» Thông tin thêm về Jon


Mỗi hướng dẫn tại Real Python được tạo bởi một nhóm các nhà phát triển để nó đáp ứng các tiêu chuẩn chất lượng cao của chúng tôi. Các thành viên trong nhóm đã làm việc trong hướng dẫn này là

Công cụ trò chơi dựa trên văn bản Python

Aldren

Công cụ trò chơi dựa trên văn bản Python

David

Công cụ trò chơi dựa trên văn bản Python

Geir Arne

Công cụ trò chơi dựa trên văn bản Python

kate

Công cụ trò chơi dựa trên văn bản Python

Philipp

Bậc thầy Kỹ năng Python trong thế giới thực Với quyền truy cập không giới hạn vào Python thực

Tham gia với chúng tôi và có quyền truy cập vào hàng nghìn hướng dẫn, khóa học video thực hành và cộng đồng các Pythonistas chuyên gia

Nâng cao kỹ năng Python của bạn »

Chuyên gia Kỹ năng Python trong thế giới thực
Với quyền truy cập không giới hạn vào Python thực

Tham gia với chúng tôi và có quyền truy cập vào hàng ngàn hướng dẫn, khóa học video thực hành và cộng đồng Pythonistas chuyên gia

Nâng cao kỹ năng Python của bạn »

Bạn nghĩ sao?

Đánh giá bài viết này

Tweet Chia sẻ Chia sẻ Email

Bài học số 1 hoặc điều yêu thích mà bạn đã học được là gì?

Mẹo bình luận. Những nhận xét hữu ích nhất là những nhận xét được viết với mục đích học hỏi hoặc giúp đỡ các sinh viên khác. và nhận câu trả lời cho các câu hỏi phổ biến trong cổng thông tin hỗ trợ của chúng tôi

Tôi có thể tạo trò chơi dựa trên văn bản bằng Python không?

Bạn có thể tạo trò chơi phiêu lưu văn bản bằng cách sử dụng tập lệnh Python và chạy trò chơi đó trong thiết bị đầu cuối hoặc dòng lệnh . Bên trong tệp Python, bạn có thể hiển thị cho người chơi một thông báo chào mừng và câu chuyện ban đầu. Sau đó, người chơi có thể nhập hành động của họ dựa trên các tùy chọn bạn đưa ra.

Có công cụ trò chơi nào sử dụng Python không?

Trò chơi ghép hình. Pygame là một trong những framework Python hàng đầu dành cho nhà phát triển trò chơi vào năm 2022 . Nó là một thư viện ngôn ngữ lập trình nguồn mở và miễn phí cho mục đích chơi game. Ngôn ngữ lập trình trò chơi này bao gồm hơn 30 dự án trò chơi với các khái niệm mới và trò chơi sáng tạo.

Python có phải là một công cụ trò chơi tốt không?

Mặc dù các studio trò chơi lớn sử dụng các ngôn ngữ mang lại tốc độ cao hơn và cho phép đồ họa tốt hơn, nhưng Python có rất nhiều lợi ích khiến nó trở thành ngôn ngữ đặc biệt hữu ích để phát triển trò chơi.

Mã hóa dựa trên văn bản Python phải không?

Tất cả các ví dụ về ngôn ngữ lập trình dựa trên văn bản là gì? . Some of the popular text-based programming languages are Python, Java, and JavaScript.