Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng python?

Giống như nhiều người, có thể bạn muốn viết trò chơi video khi bạn mới học viết mã. Nhưng đó có phải là những trò chơi như các trò chơi bạn đã chơi không? Có lẽ không có Python khi bạn bắt đầu, không có trò chơi Python nào để bạn nghiên cứu và không có động cơ trò chơi nào để nói đến. 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.

Bây giờ, có Python, và một loạt cá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 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ố động cơ trò chơi này, tìm hiểu những gì bạn cần để bắt đầu chế tạo các trò chơi video Python của riêng bạn!

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

  • Hiểu những ưu và nhược điểm của một số động cơ trò chơi Python phổ biếnpros and cons of several popular Python game engines
  • Xem các động cơ trò chơi này trong hành độngin action
  • Hiểu cách họ so sánh với các công cụ trò chơi độc lậpcompare to stand-alone game engines
  • Tìm hiểu về các công cụ trò chơi Python khác có sẵnother Python game engines available

Để tận dụng tối đa hướng dẫn này, bạn nên được thành thạo trong chương trình Python, bao gồm cả lập trình hướng đối tượng. Một 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.

Sẵn sàng để lặn vào? Nhấp vào liên kết bên dưới để tải xuống mã nguồn cho tất cả các trò chơi mà bạn sẽ tạo:

Tổng quan về động cơ trò chơi Python

Động cơ trò chơi cho Python thường có dạng thư viện Python, có thể được cài đặt theo nhiều cách khác nhau. Hầu hết đều có sẵn trên PYPI và có thể được cài đặt vớ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()
7. Tuy nhiên, một số chỉ có sẵn trên GitHub, Gitlab hoặc các vị trí chia sẻ mã khác và họ có thể yêu cầu các bước cài đặt khác. Bài viết này sẽ bao gồm các phương thức cài đặt cho tất cả các công cụ được thảo luận.

Python là một ngôn ngữ lập trình mục đích chung và nó được sử dụng cho nhiều nhiệm vụ khác ngoài việc viết trò chơi máy tính. Ngược lại, có nhiều động cơ trò chơi độc lập khác nhau được thiết kế riêng để viết các trò chơi. Một số trong số này bao gồm:

  • Động cơ không thực
  • Đoàn kết
  • Godot

Các động cơ trò chơi độc lập này khác với các động cơ trò chơi Python trong một số khía cạnh chính:

  • Hỗ trợ ngôn ngữ: Các ngôn ngữ như C ++, C#và JavaScript phổ biến cho các trò chơi được viết trong các công cụ trò chơi độc lập, vì bản thân các động cơ thường được viết bằng các ngôn ngữ này. Rất ít động cơ độc lập hỗ trợ Python. 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.
  • Hỗ trợ kịch bản độc quyền: Ngoài ra, nhiều công cụ trò chơi độc lập duy trì và hỗ trợ các ngôn ngữ kịch bản của riêng họ, có thể không giống Python. Ví dụ, Unity sử dụng C# nguyên bản, trong khi Unreal hoạt động tốt nhất với C ++. 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++.
  • Hỗ trợ nền tảng: Nhiều động cơ trò chơi độc lập hiện đại có thể sản xuất các trò chơi cho nhiều nền tảng khác nhau, bao gồm các hệ thống trò chơi di động và chuyên dụng, với rất ít nỗ lực. Ngược lại, việc chuyển một trò chơi Python trên các nền tảng khác nhau, đặc biệt là các nền tảng di động, có thể là một công việc chính. 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.
  • Tùy chọn cấp phép: Các trò chơi được viết bằng công cụ trò chơi độc lập có thể có các tùy chọn và hạn chế cấp phép khác nhau, dựa trên động cơ được sử dụng. Games written using a stand-alone game engine may have different licensing options and restrictions, based on the engine used.

Vậy tại sao sử dụng Python để viết trò chơi? Trong một từ, Python. Sử dụng một công cụ trò chơi độc lập thường yêu cầu bạn học một ngôn ngữ lập trình hoặc kịch bản mới. Động cơ trò chơi Python tận dụng kiến ​​thức hiện tại của bạn về Python, giảm đường cong học tập và giúp bạn tiến lên nhanh chóng.

Có nhiều động cơ trò chơi có sẵn cho môi trường Python. Các công cụ mà bạn sẽ tìm hiểu ở đây tất cả đều chia sẻ các tiêu chí sau:

  • Họ là những động cơ tương đối phổ biến, hoặc chúng bao gồm các khía cạnh của trò chơi mà aren thường được bảo hiểm.
  • Họ hiện đang duy trì.
  • Họ có sẵn tài liệu tốt.

Đối với mỗi động cơ, bạn sẽ tìm hiểu về:

  • Phương pháp cài đặt
  • Các khái niệm cơ bản, cũng như các giả định rằng động cơ tạo ra
  • Các tính năng và khả năng chính
  • Hai triển khai trò chơi, để cho phép so sánh

Khi thích hợp, bạn nên cài đặt các động cơ trò chơi này trong môi trường ảo. Mã nguồn đầy đủ cho các trò chơi trong hướng dẫn này có sẵn để tải xuống tại liên kết bên dưới và sẽ được tham chiếu trong suốt bài viết:

Với mã nguồn được tải xuống, bạn đã sẵn sàng để bắt đầu.

Pygame

Khi mọi người nghĩ về động cơ trò chơi Python, suy nghĩ đầu tiên mà nhiều người có là pygame. Trên thực tế, đã có một đoạn mồi tuyệt vời trên pygame có sẵn tại Real Python.

Được viết để thay thế cho thư viện PYSDL bị đình trệ, kết thúc tốt đẹp và mở rộng thư viện SDL, viết tắt của lớp DirectMedia đơn giản. SDL cung cấp quyền truy cập đa nền tảng cho hệ thống của bạn, các thành phần phần cứng đa phương tiện cơ bản của bạn, chẳng hạn như âm thanh, video, chuột, bàn phím và cần điều khiển. Bản chất đa nền tảng của cả SDL và pygame có nghĩa là bạn có thể viết các trò chơi và các chương trình Python đa phương tiện phong phú cho mọi nền tảng hỗ trợ chúng!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!

Cài đặt pygame

Pygame có sẵn trên PYPI, vì vậy sau khi tạo và kích hoạt môi trường ảo, bạn có thể cài đặt nó 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 pip install pygame

Sau khi hoàn thành, bạn có thể xác minh cài đặt bằng cách chạy một ví dụ đi kèm với thư viện:

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

Bây giờ bạn đã cài đặt pygame, bạn có thể bắt đầu sử dụng nó ngay lập tức. Nếu bạn gặp vấn đề trong quá trình cài đặt, thì Hướng dẫn bắt đầu phác thảo một số vấn đề đã biết và các giải pháp khả thi cho tất cả các nền tảng.

Các khái niệm cơ bản

Pygame được tổ chức thành một số mô -đun khác nhau, cung cấp quyền truy cập trừu tượng vào đồ họa, âm thanh và phần cứng đầu vào của bạn. Pygame cũng xác định nhiều lớp, đóng gói các khái niệm phụ thuộc vào phần cứng. Ví dụ, bản vẽ được thực hiện trên các đố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, có giới hạn hình chữ nhật được xác định bởi đối tượng
(venv) $ python pygame/pygame_basic.py
0 của chúng.

Mỗi trò chơi sử dụng một vòng lặp trò chơi để kiểm soát trò chơi chơi. Vòng lặp này lặp lại liên tục khi trò chơi tiến triển. Pygame cung cấp các phương thức và chức năng để thực hiện một vòng lặp trò chơi, nhưng nó không cung cấp một cách tự động. Tác giả trò chơi dự kiến ​​sẽ thực hiện chức năng của một vòng lặp trò chơi.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.

Mỗi lần lặp của vòng lặp trò chơi được gọi là một khung. Mỗi khung hình, trò chơi thực hiện bốn hành động quan trọng:frame. Every frame, the game performs four vital actions:

  1. Xử lý đầu vào người dùng. Đầu vào của người dùng trong pygame được xử lý bằng mô hình sự kiện. Đầu vào chuột và bàn phím tạo ra các sự kiện, có thể được đọc và xử lý, hoặc bỏ qua khi bạn thấy phù hợp. Bản thân Pygame không cung cấp bất kỳ trình xử lý sự kiện nào. User input in Pygame is handled using an event model. 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. Cập nhật trạng thái của các đối tượng trò chơi. Các đối tượng trò chơi có thể được biểu diễn bằng cách sử dụng bất kỳ cấu trúc dữ liệu pygame hoặc lớp pygame đặc biệt nào. Các đối tượng như sprites, hình ảnh, phông chữ và màu sắc có thể được tạo và mở rộng trong Python để cung cấp càng nhiều thông tin trạng thái cần thiết. Game objects can be represented using any Pygame data structure or special Pygame class. Objects such as sprites, images, fonts, and colors can be created and extended in Python to provide as much state information as necessary.

  3. Cập nhật màn hình và đầu ra âm thanh. Pygame cung cấp quyền truy cập trừu tượng để hiển thị và phần cứng âm thanh. Các mô -đun

    (venv) $ python pygame/pygame_basic.py
    
    1,
    (venv) $ python pygame/pygame_basic.py
    
    2 và
    (venv) $ python pygame/pygame_basic.py
    
    3 cho phép các tác giả trò chơi linh hoạt trong thiết kế và triển khai trò chơi.
    Pygame provides abstract access to display and sound hardware. 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. Duy trì tốc độ của trò chơi. Mô -đun Pygame từ

    (venv) $ python pygame/pygame_basic.py
    
    4 cho phép các tác giả trò chơi kiểm soát tốc độ trò chơi. Bằng cách đảm bảo mỗi khung hoàn thành trong một giới hạn thời gian xác định, các tác giả trò chơi có thể đảm bảo trò chơi chạy tương tự trên phần cứng khác nhau. Pygame’s
    (venv) $ python pygame/pygame_basic.py
    
    4 module allows game authors to control the game speed. By ensuring each frame completes within a specified time limit, game authors can ensure the game runs similarly on different hardware.

Bạn có thể thấy những khái niệm này kết hợp với nhau trong một ví dụ cơ bản.

Ứng dụng cơ bản

Chương trình Pygame cơ bản 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:

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng python?

Mã cho mẫu này có thể được tìm thấy bên dưới và trong các tài liệu có thể tải xuố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()

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

(venv) $ python pygame/pygame_basic.py
5. Đặt biến này thành
(venv) $ python pygame/pygame_basic.py
6 sẽ kết thúc chương trình.line 27 and is controlled by the
(venv) $ python pygame/pygame_basic.py
5 variable. Setting this variable to
(venv) $ python pygame/pygame_basic.py
6 will end the program.

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

(venv) $ python pygame/pygame_basic.py
7 và được xử lý tại một thời điểm trong mỗi lần lặp lại. 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
8, đượ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
(venv) $ python pygame/pygame_basic.py
9, cuối cùng sẽ kết thúc vòng lặp trò chơi và chương trình.line 30 with an event loop. Events are retrieved from a queue using
(venv) $ python pygame/pygame_basic.py
7 and are processed one at a time during every loop iteration. In this case, the only event being handled is the
(venv) $ python pygame/pygame_basic.py
8 event, which is generated when the user closes the game window. When this event is processed, you set
(venv) $ python pygame/pygame_basic.py
9, which will eventually end the game loop and the program.

Pygame cung cấp các phương pháp khác nhau để vẽ các hình dạng cơ bản, chẳng hạn như vòng 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 phải tạo đối tượng

(venv) $ python pygame/pygame_basic.py
0 trước.line 38, and a red square is drawn on lines 41 and 42. Note that drawing a rectangle requires you to create a
(venv) $ python pygame/pygame_basic.py
0 object first.

Vẽ văn bản trên màn hình có liên quan nhiều hơn một chút. Đầu tiên, trên dòng 45, bạn chọn một phông chữ và tạo đố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()
1. 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()
2. Điều này tạo ra một đố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ị trong phông chữ và màu đượ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 vào màn hình bằ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()
5 trên dòng 49.line 45, you select a font and create a
  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()
1 object. Using that font on lines 46 to 48, you call the
  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 method. This creates 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()
9 object containing the text rendered in the specified font and color. Finally, you copy
 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 to the screen using the
  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()
5 method on line 49.

Phần cuối của vòng lặp trò chơi xảy ra trên dòng 52, khi mọi thứ được vẽ trước đó được hiển thị trên màn hình. Nếu không có dòng này, sẽ không có gì được hiển thị.line 52, when everything that was previously drawn is shown on the display. Without this line, nothing would be displayed.

Để 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 được 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 bạn!

Ứng dụng nâng cao

Tất nhiên, Pygame được thiết kế để viết các trò chơi 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 sprite duy nhất trên màn hình, được điều khiển bằng cách di chuyển chuột.
  • Trong các khoảng thời gian đều đặn, các đồng tiền xuất hiện trên màn hình từng cái một.
  • Khi người chơi di chuyển qua mỗi đồng xu, nó biến mất và người chơi được trao mười điểm.
  • Khi trò chơi tiến triển, tiền được thêm nhanh hơn.
  • Trò chơi kết thúc khi có hơn mười đồng xu có thể nhìn thấy trên màn hình.

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

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng python?

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

  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ế để được phân lớp thay vì tự sử dụng. Pygame Sprites don lồng có hình ảnh liên quan đến chúng theo mặc định và họ có thể tự mình định vị.

Để vẽ đúng và quản lý người chơi và đồng xu trên màn hình, 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()
6 đượ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()
7 trên các dòng 58 đến 75. Khi mỗi đối tượng sprite được tạo, trước tiên nó lại định vị và tải hình ảnh nó 'LL hiển thị, lưu nó trong
  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ác vị trí thuộc tính
  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 và di chuyển sprite trên màn hình.lines 35 to 55, and a
  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()
7 class on lines 58 to 75. When each sprite object is created, it first locates and loads the image it’ll display, saving it in
  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. The
  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 property positions and moves the sprite on the screen.

Thêm tiền vào màn hình đều đặn được thực hiện với bộ hẹn giờ. Trong pygame, các sự kiện được bắn bất cứ khi nào một bộ đếm thời gian hết hạn và người tạo trò chơi có thể xác định các sự kiện của riêng họ là hằng số nguyên. Sự kiện

(venv) $ python -m pip install pgzero
0 được xác định trên dòng 90 và bộ hẹn giờ bắn sự kiện sau
(venv) $ python -m pip install pgzero
1 mili giây trên dòng 91.line 90, and the timer fires the event after
(venv) $ python -m pip install pgzero
1 milliseconds on line 91.

(venv) $ python -m pip install pgzero
0 là một sự kiện, nó cần được xử lý trong một vòng lặp sự kiện, xảy ra trên các dòng 118 đến 134. Sự kiện tạo ra 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()
7 mới và thêm nó vào
(venv) $ python -m pip install pgzero
4 hiện có. Số lượng tiền trên màn hình được kiểm tra. Nếu có ít hơn ba, thì
(venv) $ python -m pip install pgzero
1 sẽ giảm. Cuối cùng, bộ đếm thời gian trước đó được dừng lại và một bộ mới bắt đầu.lines 118 to 134. The event creates a new
  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()
7 object and adds it to the existing
(venv) $ python -m pip install pgzero
4. The number of coins on-screen is checked. If there are fewer than three, then
(venv) $ python -m pip install pgzero
1 is reduced. Finally, the previous timer is stopped, and a new one starts.

Khi người chơi di chuyển, họ va chạm với tiền xu, thu thập chúng như họ làm. Điều này loại bỏ mỗi đồng tiền thu được từ

(venv) $ python -m pip install pgzero
4 tự động. Điều này cũng cập nhật điểm số và phát mộ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 các đồng tiền 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
7 sẽ tự động loại bỏ đồng tiền khỏi
(venv) $ python -m pip install pgzero
4. Cuối cùng, các dòng 143 đến 147 cập nhật điểm số và phát âm thanh cho mỗi đồng xu được thu thập.line 137. Collisions with coins on the screen are checked on lines 140 to 142. The
(venv) $ python -m pip install pgzero
7 parameter removes the coin from the
(venv) $ python -m pip install pgzero
4 automatically. Finally, lines 143 to 147 update the score and play the sound for each coin collected.

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 tiền trên màn hình. Kiểm tra hơn mười đồng xu được thực hiện trên các dòng 150 đến 152.lines 150 to 152.

Bởi vì pygame sprites 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ẽ 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 sprites theo đúng thứ tự, rút ​​điểm trên màn hình, sau đó

(venv) $ python -m pip install pgzero
9 màn hình để làm cho mọi thứ xuất hiện. Tất cả xảy ra trên các dòng 155 đến 170.lines 155 to 170.

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

Pygame không

Có rất 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 người mới bắt đầu viết trò chơi, một tùy chọn tốt hơn có thể được tìm thấy 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 hoàn hảo cho các lập trình viên trẻ và bắt đầu:

  • Làm cho nó có thể truy cập: Mọi thứ được thiết kế cho các lập trình viên bắt đầu. Everything is designed for beginning programmers.
  • Hãy bảo thủ: Hỗ trợ nền tảng chung và tránh các tính năng thử nghiệm. Support the common platform and avoid experimental features.
  • Chỉ cần làm việc: Hãy chắc chắn rằng mọi thứ hoạt động mà không có nhiều phiền phức. Make sure everything works without a lot of fuss.
  • Giảm thiểu chi phí thời gian chạy: Nếu có điều gì đó có thể thất bại, thất bại sớm. If something might fail, fail early.
  • Lỗi rõ ràng: Không có gì tệ hơn là không biết tại sao có điều gì đó không ổn. Nothing’s worse than not knowing why something went wrong.
  • Tài liệu tốt: Một khung chỉ tốt như tài liệu của nó. A framework is only as good as its docs.
  • Giảm thiểu các thay đổi phá vỡ: Nâng cấp nên không yêu cầu viết lại trò chơi của bạn. Upgrading shouldn’t require rewriting your game.

Tài liệu cho Pygame Zero rất dễ truy cập đối với các lập trình viên bắt đầu 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 bắt đầu bắt đầu mã hóa bằng Scratch, vì vậy họ cung cấp một hướng dẫn trình bày cách di chuyển một chương trình cào sang pygame 0.

Cài đặt pygame bằng không

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, như tên của nó cho thấy, được xây dựng trên pygame, vì vậy 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 phát hành sau.

Các khái niệm cơ bản

Pygame Zero tự động hóa nhiều thứ mà các lập trình viên phải làm thủ công trong pygame. Theo mặc định, Pygame Zero cung cấp Trình 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
  • Một mô hình sự kiện để xử lý bản vẽ, cập nhật và xử lý đầu vào
  • Hình ảnh đồng nhất, văn bản và xử lý âm thanh
  • Một lớp sprite có thể sử dụng và các phương thức hoạt hình hữu ích cho người dùng sprites

Do các điều khoản này, một chương trình Pygame Zero cơ bản có thể rất ngắ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()
0 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()
1 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 nó. Thêm vào đó, Pygame Zero cung cấp một 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()
2 đượ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.lines 16 and 17 refer to the size of the window and automatically uses those dimensions to create it. Plus, Pygame Zero provides a built-in game loop and calls the
 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()
2 function defined on lines 19 to 43 once per frame to render the screen.

Vì pygame Zero dựa trên pygame, một số mã vẽ hình dạng được kế thừa. Bạn có thể thấy những điểm tương đồng trong việc vẽ vòng tròn trên dòng 29 và hình vuông trên các dòng 34 đến 35:line 29 and the square on lines 34 to 35:

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng python?

Tuy nhiên, bản vẽ văn bản bây giờ là một cuộc gọi chức năng duy nhất trên các dòng 38 đến 43, thay vì ba hàm riêng biệt.lines 38 to 43, rather than three separate functions.

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 cần xử lý sự kiện.

Bạn có thể tìm thấy 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:

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 của bạn.

Sprites và hình ảnh

Sprites được gọi là diễn viên trong Pygame Zero và chúng có một vài đặc điểm đòi hỏi một số lời 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()
    
    3. 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()
    
    3 có, tối thiểu, một hình ảnh và một vị trí.
  2. Tất cả các hình ảnh được sử dụng trong chương trình Pygame Zero phải được đặt trong một thư mục con có tê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()
    
    5 và chỉ được đặt tên bằng cách sử dụng các chữ cái, số và chỉ nhấn mạnh.
  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 gọi 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()
    
    6, bạn tham khảo nó trong chương trình của bạ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()
    
    7.

Do các tính năng tích hợp của Pygame Zero, việc vẽ các sprites trên màn hình đòi hỏi 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ẽ phá vỡ mẫu nhỏ này theo 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()
    
    3 mới, cho nó tên của hình ảnh để vẽ.
    creates the new
     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 object, giving it the name of the image to draw.
  • 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()
    
    3.
    sets the initial x and y position of the
     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.
  • Dòng 4 và 5 Đặt kích thước của cửa sổ Zero Pygame. 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()
    
    1 dựa trên thuộc tính
    (venv) $ python pygame_zero/pygame_zero_basic.py
    
    1 của sprite. Giá trị này đến từ độ cao của hình ảnh được sử dụng để tạo ra sprite.
    set the size of the Pygame Zero window. Notice that
     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 is based on the
    (venv) $ python pygame_zero/pygame_zero_basic.py
    
    1 attribute of the sprite. This value comes from the height of the image used to create the sprite.
  • Dòng 9 vẽ sprite bằng cách gọi
    (venv) $ python pygame_zero/pygame_zero_basic.py
    
    2 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()
    
    3. Đ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
    
    4.
    draws the sprite by calling
    (venv) $ python pygame_zero/pygame_zero_basic.py
    
    2 on the
     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 object. This draws the sprite image on the screen at the location provided by
    (venv) $ python pygame_zero/pygame_zero_basic.py
    
    4.

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

Ứ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. Một lời nhắc nhở, các chi tiết chính của trò chơi đó là:

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

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

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng 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:

  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()
3 được thực hiện trên các dòng 26 đến 28. Vị trí ban đầu là trung tâm của màn hình.lines 26 to 28. The initial position is the center of the screen.

Phương pháp

(venv) $ python pygame_zero/pygame_zero_basic.py
6 xử lý việc tạo tiền đồng đều đặn. Phương thức này cần một hàm để gọi và số giây để trì hoãn trước khi gọi hàm đó.

Các dòng 41 đến 65 Xác định hàm

(venv) $ python pygame_zero/pygame_zero_basic.py
7 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()
3 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 các đồng tiền có thể nhìn thấy.
define the
(venv) $ python pygame_zero/pygame_zero_basic.py
7 function that will be scheduled. It creates a new coin
 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 at a random location on lines 48 to 50 and adds it to a global list of visible coins.

Khi trò chơi tiến triển, tiền xu sẽ xuất hiện ngày càng nhanh hơn, 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. Vì

(venv) $ python pygame_zero/pygame_zero_basic.py
6 sẽ chỉ bắn một lần, bạn lên lịch cho một cuộc gọi khác trên dòng 65.lines 57 to 62. Because
(venv) $ python pygame_zero/pygame_zero_basic.py
6 will only fire a single time, you schedule another call on line 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()
0 trên các dòng 67 đến 87. Vị trí chuột được ghi lại 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ờ ra khỏi màn hình.lines 67 to 87. The mouse position is captured and stored in a global variable on line 76. Lines 79 to 87 ensure this position is never off the screen.

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 đượ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 0. Bạn sử dụng điều này để di chuyển các đố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()
3 và cập nhật trạng thái của tất cả các đối tượng 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()
3 được cập nhật để theo dõi chuột trên dòng 98.lines 89 to 122 is called once per frame by Pygame Zero. You use this to move
 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 objects and update the state of all your game objects. The position of the player
 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 is updated to track the mouse on line 98.

Các va chạm với tiền đượ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 tiền đượ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()
4, điểm số được tăng lên và phát ra âm thanh. Khi tất cả các va chạm đã được xử lý, bạn sẽ loại bỏ các đồng tiền đượ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()
4 trên các dòng 112 đến 113.lines 102 to 113. If the player has collided with a coin, then the coin is added to
 1alien = Actor("alien")
 2alien.pos = 100, 56
 3
 4WIDTH = 500
 5HEIGHT = alien.height + 20
 6
 7def draw():
 8    screen.clear()
 9    alien.draw()
4, the score is incremented, and a sound is played. When all the collisions have been processed, you remove the coins which were added to
 1alien = Actor("alien")
 2alien.pos = 100, 56
 3
 4WIDTH = 500
 5HEIGHT = alien.height + 20
 6
 7def draw():
 8    screen.clear()
 9    alien.draw()
4 on lines 112 to 113.

Sau khi xử lý va chạm bằng tiền xu, bạn kiểm tra xem liệu vẫn còn quá nhiều đồng xu trên màn hình trên dòng 116. Nếu vậy, trò chơi đã kết thúc, vì vậy bạn ngừng tạo tiền xu mới, in điểm cuối cùng và kết thúc trò chơi trên các dòng 118 đến 122.line 116. If so, the game is over, so you stop creating new coins, print the final score, and end the game on lines 118 to 122.

Tất nhiên, tất cả việc cập nhật này cần phải đượ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()
2 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()
1 một lần cho mỗi khung hình. Sau khi xóa màn hình và điền vào màu nền trê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()
3 và tất cả các đồng xu được vẽ trên các dòng 134 đến 138. Điểm hiện tại là thứ cuối cùng được rút ra trên các dòng 141 đến 146.lines 124 to 146 is called after
 1alien = Actor("alien")
 2alien.pos = 100, 56
 3
 4WIDTH = 500
 5HEIGHT = alien.height + 20
 6
 7def draw():
 8    screen.clear()
 9    alien.draw()
1 once per frame. After clearing the screen and filling it with a background color on lines 128 and 131, the player
 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 and all the coins are drawn on lines 134 to 138. The current score is the last thing drawn on lines 141 to 146.

Việc triển khai Zero không sử dụng 152 dòng mã để cung cấp cùng một trò chơi với 182 dòng mã pygame. Mặc dù số lượng dòng này có thể so sánh được, phiên bản pygame Zero được cho là sạch hơn, mô -đun hơn và có thể dễ hiểu và mã hơn so với phiên bản pygame.

Tất nhiên, có một cách luôn luôn là một cách để viết một trò chơi.

Giải trí

Arcade là một khung Python hiện đại để chế tạo các trò chơi với đồ họa và âm thanh hấp dẫn. Theo hướng đối tượng bởi 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 để chế tạo các trải nghiệm trò chơi Python tuyệt vời.

Được thiết kế bởi Giáo sư Paul Craven từ Simpson College ở Iowa, Hoa Kỳ, Arcade được xây dựng trên đỉnh của thư viện Pyglet Windowing và Multimedia. Nó cung cấp một tập hợp các cải tiến, hiện đại hóa và các cải tiến so sánh thuận lợi với cả pygame và pygame Zero:

  • Hỗ trợ đồ họa OpenGL hiện đại
  • Hỗ trợ gợi ý loại Python 3
  • Có hỗ trợ cho các sprites 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 phân tách logic trò chơi với mã hiển thị
  • Yêu cầu mã dễ nồi hơi ít hơn
  • Cung cấp tài liệu được bảo trì tốt và cập nhật, bao gồm một số hướng dẫn và các ví dụ về trò chơi Python hoàn chỉnh
  • Có động cơ vật lý tích hợp cho các trò chơi từ trên xuống và nền tả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ả, người 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.

Cài đặt arcade

Để cài đặt Arcade và các 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

Hoàn thành hướng dẫn cài đặt 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()
0 trực tiếp từ nguồn nếu bạn thích.

Các khái niệm cơ bản

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

  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()
1 nằm ở góc dưới bên trái của màn hình, với các tọa độ y tăng khi bạn di chuyển lên. Điều này khác với nhiều độ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()
1 ở phía trên bên trái và tăng tọa độ Y di chuyển xuống.

Tại trung tâm của nó, 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 của nó được tiết lộ khi bạn tạo mã hướng hoàn toàn đối tượng.

Arcade, như Pygame Zero, cung cấp một vòng lặp trò chơi tích hợp và mô hình sự kiện được xác định rõ, vì vậy bạn kết thúc với mã trò chơi rất sạch sẽ 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, Arcade Sprites có thể được hoạt hình bằng cách cung cấp nhiều hình ảnh.

Mã cho một ứng dụng arcade cơ bản được liệt kê dưới đây được cung cấp trong mã nguồn 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()
3:

(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 đã hiển thị trước đây:

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng 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 đầy đủ. Lớp

  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()
4 được thiết kế để được 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
  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ên dòng 33 đảm bảo cửa sổ trò chơi được thiết lập đúng.line 20. Calling
  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 on line 33 ensures the game window is set up properly.

Arcade gọi trình xử lý sự kiệ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()
6 được xác định trên các dòng 38 đến 70 một lần cho 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
  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()
7, nói với Arcade để chuẩn bị cửa sổ để vẽ. Điều này có thể so sánh với cuộc gọi
  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 được yêu cầu ở cuối bước vẽ pygame.lines 38 to 70 once per frame to render everything to the screen. This method starts with a call to
  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()
7, which tells Arcade to prepare the window for drawing. This is comparable to the
  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 call required at the end of the Pygame drawing step.

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

  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()
9 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
00, nhưng bạn cũng có thể tự do chọn màu của riêng mình bằng các bộ dữ liệu RGB hoặc RGBA.

Ứng dụng nâng cao

Để cho thấy 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 từ trước, hiện được triển khai trong Arcade. Một lời nhắc nhở, đây là các chi tiết chính của trò chơi:

  • Người chơi là một sprite duy nhất trên màn hình, được điều khiển bằng cách di chuyển chuột.
  • Trong các khoảng thời gian đều đặn, các đồng tiền xuất hiện trên màn hình từng cái một.
  • Khi người chơi di chuyển qua mỗi đồng xu, nó biến mất và người chơi được trao mười điểm.
  • Khi trò chơi tiến triển, tiền được thêm nhanh hơn.
  • Trò chơi kết thúc khi có hơn mười đồng xu có thể nhìn thấy 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:

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng python?

Mã cho trò chơi arcade đầy đủ được liệt kê dưới đây được cung cấp trong các tài liệu có thể tải xuống là

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

(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 thực hiện các cấp độ khác nhau bằng cách tách khởi tạo trò chơi khỏi việc khởi tạo từng cấp độ khác nhau. Trò chơi được khởi tạo theo phương thức

(venv) $ python -m pygame.examples.aliens
02 trên các dòng 40 đến 63, trong khi các mức được thiết lập và có thể được khởi động lại bằng phương pháp
(venv) $ python -m pygame.examples.aliens
03 riêng biệt trên các dòng 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 độ duy nhất, Giống như cái này.lines 40 to 63, while levels are set up and can be restarted using the separate
(venv) $ python -m pygame.examples.aliens
03 method on lines 65 to 85. This is a great pattern to use even for games that have a single level, like this one.

Sprites được xác định bằng cách tạo một đối tượng của lớp

(venv) $ python -m pygame.examples.aliens
04 và cung cấp đường dẫn đến một hình ảnh. Arcade hỗ trợ các đường dẫn đường dẫn, giúp giảm bớt việc tạo ra người chơi sprite trên các dòng 72 đến 75.lines 72 to 75.

Tạo các đồng tiền mới được xử lý trên các dòng 78 đến 80, gọi

(venv) $ python -m pygame.examples.aliens
05 để gọi phương thức
(venv) $ python -m pygame.examples.aliens
06 theo các khoảng thời gian đều đặn.lines 78 to 80, which call
(venv) $ python -m pygame.examples.aliens
05 to call the
(venv) $ python -m pygame.examples.aliens
06 method at regular intervals.

Phương pháp

(venv) $ python -m pygame.examples.aliens
07 được xác định trên các dòng 87 đến 120 tạo ra một sprite xu mới tại một vị trí ngẫu nhiên và thêm nó vào một danh sách để đơn giản hóa bản vẽ cũng như xử lý va chạm sau này.lines 87 to 120 creates a new coin sprite at a random location and adds it to a list to simplify drawing as well as collision handling later.

Để di chuyển người chơi bằng cách sử dụng chuột, bạn thực hiện phương thức

(venv) $ python -m pygame.examples.aliens
08 trên các dòng 122 đến 134. Phương thức
(venv) $ python -m pygame.examples.aliens
09 đảm bảo tọa độ trung tâm của người chơi không bao giờ ra khỏi màn hình.lines 122 to 134. The
(venv) $ python -m pygame.examples.aliens
09 method ensures the player’s center coordinates are never off the screen.

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

(venv) $ python -m pygame.examples.aliens
10 trên các dòng 144 đến 156. Phương thức
(venv) $ python -m pygame.examples.aliens
11 trả về danh sách tất cả các sprites trong danh sách đã va chạm 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 tiền khỏi chơi.lines 144 to 156. The
(venv) $ python -m pygame.examples.aliens
11 method returns a list of all the sprites in the list that have collided with the specified sprite. The code walks through that list, incrementing the score and playing a sound effect before removing each coin from play.

Phương pháp

(venv) $ python -m pygame.examples.aliens
10 cũng kiểm tra xem có quá nhiều đồng tiền trên màn hình trên các dòng 159 đến 168. Nếu vậy, nó kết thúc trò chơi.lines 159 to 168. If so, it ends the game.

Việc triển khai arcade này cũng có thể đọc được và được cấu trúc tốt như mã số không pygame, mặc dù phải mất hơn 27% mã, với 194 dòng được viết. Mã dài hơn có thể có giá trị, vì Arcade cung cấp nhiều tính năng khác không được chứng minh ở đây, chẳng hạn như:

  • Hoạt hình Sprites
  • 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ác hệ thống hạt và shader được cập nhật

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

Adventurelib

Tất nhiên, không phải mọi trò chơi đều 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à giết chế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 tốt trong khi vẫn cung cấp trải nghiệm chơi game tuyệt vời. Việc 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ó khăn trong bất kỳ ngôn ngữ nào. May mắn cho các lập trình viên Python, 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 làm cho nó đủ dễ dàng để thanh thiếu niên làm. (Nguồn)

Nó không chỉ dành cho thanh thiếu niên, mặc dù! Adventurelib là tuyệt vời cho bất cứ ai muốn viết một trò chơi dựa trên văn bản mà không phải viết một trình phân tích cú pháp ngôn ngữ tự nhiên để làm điều đó.

Adventurelib được tạo ra bởi những người đứng sau Pygame Zero, và nó đã giải quyết các chủ đề khoa học máy tính tiên tiến hơn như quản lý nhà nước, logic kinh doanh, đặt tên và tài liệu tham khảo, và thiết lập thao tác, để đặt tên cho một số. Đ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à 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 các kỹ năng mã hóa trò chơi của riêng bạn.

Cài đặt phiêu lưu

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

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

Các khái niệm cơ bản

Để tìm hiểu những điều cơ bản của Adventurelib, bạn sẽ thấy một trò chơi nhỏ với ba phòng và chìa khóa để mở khóa một cánh cửa cho 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
14:

(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 phụ thuộc rất nhiều vào đầu vào của người dùng phân tích cú pháp để thúc đẩy trò chơi tiến lên. Adventurelib định nghĩa văn bản rằng người chơi gõ là một lệnh và cung cấp trình trang trí

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

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

(venv) $ python -m pygame.examples.aliens
16 được xác định trên các dòng 113 đến 125. Trình trang trí
(venv) $ python -m pygame.examples.aliens
17 thêm văn bản
(venv) $ python -m pygame.examples.aliens
16 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
19. Bất cứ khi nào người chơi loại
(venv) $ python -m pygame.examples.aliens
16, Adventurelib sẽ gọi hàm
(venv) $ python -m pygame.examples.aliens
19.lines 113 to 125. The
(venv) $ python -m pygame.examples.aliens
17 decorator adds the text
(venv) $ python -m pygame.examples.aliens
16 to a list of valid commands and connects it to the
(venv) $ python -m pygame.examples.aliens
19 function. Whenever the player types
(venv) $ python -m pygame.examples.aliens
16, adventurelib will call the
(venv) $ python -m pygame.examples.aliens
19 function.

Các lệnh không nhạy cảm với trường hợp khi được gõ bởi người chơi. Người chơi có thể nhập

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

Tất cả nhiều lệnh đều có thể sử dụng cùng một chức năng, như đã thấy với hàm

(venv) $ python -m pygame.examples.aliens
26 trên các dòng 78 đến 110. Hàm này được trang trí với chín lệnh riêng biệt, cho phép người chơi một số cách khác nhau để di chuyển xung quanh thế giới trò chơi. Trong ví dụ chơi trò chơi dưới đây, các lệnh
(venv) $ python -m pygame.examples.aliens
27,
(venv) $ python -m pygame.examples.aliens
28 và
(venv) $ python -m pygame.examples.aliens
29 đều được sử dụng, nhưng mỗi kết quả trong cùng một chức năng được gọi là:lines 78 to 110. This function is decorated with nine separate commands, allowing the player several different ways to move around the game world. In the game play example below, the commands
(venv) $ python -m pygame.examples.aliens
27,
(venv) $ python -m pygame.examples.aliens
28, and
(venv) $ python -m pygame.examples.aliens
29 are all used, but each results in the same function being called:

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng python?

Đôi khi các lệnh mà một loại người chơi được hướng vào một mục cụ thể. Ví dụ, người chơi có thể muốn xem xét một điều 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 bối cảnh lệnh bổ sung bằng cách chỉ định các từ được viết hoa trong trình trang trí

(venv) $ python -m pygame.examples.aliens
15. Chúng được coi là tên biến và văn bản mà người chơi nhập vị trí của họ là các giá trị.command context by specifying capitalized words in the
(venv) $ python -m pygame.examples.aliens
15 decorator. These are treated as variable names, and the text that the player types in their place are the values.

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

(venv) $ python -m pygame.examples.aliens
31 trên các dòng 128 đến 137. Hàm này xác định một tham số chuỗi đơn gọi là
(venv) $ python -m pygame.examples.aliens
32. Trong các nhà trang trí
(venv) $ python -m pygame.examples.aliens
15 xác định các lệnh
(venv) $ python -m pygame.examples.aliens
34 và
(venv) $ python -m pygame.examples.aliens
35, từ
(venv) $ python -m pygame.examples.aliens
36 hoạt động như một trình giữ chỗ cho bất kỳ văn bản nào theo lệnh. Văn bản này sau đó được chuyển đến hàm
(venv) $ python -m pygame.examples.aliens
31 dưới dạng tham số
(venv) $ python -m pygame.examples.aliens
32. Ví dụ: nếu người chơi loại
(venv) $ python -m pygame.examples.aliens
39, thì tham số
(venv) $ python -m pygame.examples.aliens
32 sẽ nhận được giá trị
(venv) $ python -m pygame.examples.aliens
41.lines 128 to 137. This function defines a single string parameter called
(venv) $ python -m pygame.examples.aliens
32. In the
(venv) $ python -m pygame.examples.aliens
15 decorators defining the
(venv) $ python -m pygame.examples.aliens
34 and
(venv) $ python -m pygame.examples.aliens
35 commands, the word
(venv) $ python -m pygame.examples.aliens
36 acts as a placeholder for any text following the command. This text is then passed to the
(venv) $ python -m pygame.examples.aliens
31 function as the
(venv) $ python -m pygame.examples.aliens
32 parameter. For example, if the player types
(venv) $ python -m pygame.examples.aliens
39, then the parameter
(venv) $ python -m pygame.examples.aliens
32 will get the value
(venv) $ python -m pygame.examples.aliens
41.

Sức mạnh của một trò chơi dựa trên văn bản dựa trên 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 chức năng

(venv) $ python -m pygame.examples.aliens
42, nhưng in nhiều dòng văn bản để đáp ứng với các lệnh của người dùng có thể gây khó khăn cho văn bản qua nhiều dòng và xác định lỗi dòng. Adventurelib làm giảm gánh nặng này với chức năng
(venv) $ python -m pygame.examples.aliens
43, hoạt động tốt với các chuỗi đa dòng được trích xuất ba.

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

(venv) $ python -m pygame.examples.aliens
43 trong hành động trên dòng 118 trong hàm
(venv) $ python -m pygame.examples.aliens
19. Bất cứ khi nào người chơi loại
(venv) $ python -m pygame.examples.aliens
16, chức năng
(venv) $ python -m pygame.examples.aliens
43 sẽ đưa ra mô tả của phòng hiện tại vào bảng điều khiển.line 118 in the
(venv) $ python -m pygame.examples.aliens
19 function. Whenever the player types
(venv) $ python -m pygame.examples.aliens
16, the
(venv) $ python -m pygame.examples.aliens
43 function outputs the description of the current room to the console.

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

(venv) $ python -m pygame.examples.aliens
48 để xác định các lĩnh vực khác nhau trong thế giới trò chơi của bạn. Các phòng được tạo ra bằng cách cung cấp một mô tả về căn 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
49,
(venv) $ python -m pygame.examples.aliens
50,
(venv) $ python -m pygame.examples.aliens
51 và
(venv) $ python -m pygame.examples.aliens
52. 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
48 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. Trình xây dựng

(venv) $ python -m pygame.examples.aliens
54 chấp nhận một mô tả dưới dạng chuỗi hoặc trong trường hợp này, dưới dạng chuỗi đa 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. Cài đặt
(venv) $ python -m pygame.examples.aliens
55 với
(venv) $ python -m pygame.examples.aliens
56 ngụ ý rằng
(venv) $ python -m pygame.examples.aliens
57 sẽ là
(venv) $ python -m pygame.examples.aliens
58. Adventurelib đủ thông minh để tự động kết nối này.lines 15 to 35. The
(venv) $ python -m pygame.examples.aliens
54 constructor accepts a description as a string, or in this case, as a multiline string. Once you’ve created the rooms, then you connect them on lines 38 to 39. Setting
(venv) $ python -m pygame.examples.aliens
55 to
(venv) $ python -m pygame.examples.aliens
56 implies that
(venv) $ python -m pygame.examples.aliens
57 will be
(venv) $ python -m pygame.examples.aliens
58. adventurelib is smart enough to make this connection automatically.

Bạn cũng tạo ra 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ửa này sẽ yêu cầu người chơi xác định vị trí một vật phẩm.line 44 to indicate a locked door between the living room and the front porch. Unlocking this door will require the player to locate an item.

Các trò chơi dựa trên văn bản thường có các mục phải được thu thập để mở các khu vực mới của trò chơi hoặc để giải các câu đố nhất định. Các mục 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
59 để xác định cả các mục có thể thu thập và các ký tự không chơi bằng tên và bí danh của họ. Ví dụ: bí danh
(venv) $ python -m pygame.examples.aliens
60 đề cập đến phím cửa trước:

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng python?

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

(venv) $ python -m pygame.examples.aliens
60 được sử dụng để mở khóa cửa giữa phòng khách và hiên trước. Chất xây dựng
(venv) $ python -m pygame.examples.aliens
62 có một hoặc nhiều chuỗi. Đầu tiên là tên mặc định hoặc đầy đủ của mục và nó được sử dụng khi in tên của mặt hàng. 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 mục.line 63, you define the
(venv) $ python -m pygame.examples.aliens
60 used to unlock the door between the living room and the front porch. The
(venv) $ python -m pygame.examples.aliens
62 constructor takes one or more strings. The first is the default or full name of the item, and it’s used when printing the name of the item. All other names are used as aliases so the player doesn’t have to type the full name of the item.

(venv) $ python -m pygame.examples.aliens
60 không có tên và bí danh. Nó cũng có mục đích sử dụng, được xác định trên dòng 64.
(venv) $ python -m pygame.examples.aliens
64 đề 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 nhập
(venv) $ python -m pygame.examples.aliens
65. Hàm này được gọi trong bộ xử lý lệnh
(venv) $ python -m pygame.examples.aliens
66 được xác định trên các dòng 159 đến 175.line 64.
(venv) $ python -m pygame.examples.aliens
64 refers to a function that will be called when a player tries to use the item by typing
(venv) $ python -m pygame.examples.aliens
65. This function is called in the
(venv) $ python -m pygame.examples.aliens
66 command handler defined on lines 159 to 175.

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

(venv) $ python -m pygame.examples.aliens
67. Bạn có thể thêm các vật phẩm vào túi, loại bỏ các vật phẩm khỏi túi và kiểm tra nội dung túi.
(venv) $ python -m pygame.examples.aliens
67 Các đối tượng có thể sử dụng được trong Python, vì vậy bạn cũng có thể sử dụng
(venv) $ python -m pygame.examples.aliens
69 để kiểm tra xem có gì đó trong túi và lặp qua nội dung túi trong vòng lặp
(venv) $ python -m pygame.examples.aliens
70 không.

Bốn đối tượng

(venv) $ python -m pygame.examples.aliens
67 khác nhau được xác định trên các dòng 67 đến 75. Mục
(venv) $ python -m pygame.examples.aliens
60 được đặt ở vị trí bắt đầu của nó trong
(venv) $ python -m pygame.examples.aliens
58.lines 67 to 75. Each of the three rooms has a
(venv) $ python -m pygame.examples.aliens
67 to hold items in the room, and the player also has a
(venv) $ python -m pygame.examples.aliens
67 to hold their
(venv) $ python -m pygame.examples.aliens
74 of items they pick up. The
(venv) $ python -m pygame.examples.aliens
60 item is placed in its starting location in the
(venv) $ python -m pygame.examples.aliens
58.

Các mục được thêm vào hàng tồn kho của người chơi bởi hàm

(venv) $ python -m pygame.examples.aliens
77 được xác định trên các dòng 140 đến 156. Khi người chơi nhập
(venv) $ python -m pygame.examples.aliens
78, bạn sẽ cố phòng của
(venv) $ python -m pygame.examples.aliens
80. Sau đó, bạn thêm
(venv) $ python -m pygame.examples.aliens
60 vào người chơi
(venv) $ python -m pygame.examples.aliens
74 trên dòng 156.lines 140 to 156. When the player types
(venv) $ python -m pygame.examples.aliens
78, you attempt to
(venv) $ python -m pygame.examples.aliens
79 the item from the room’s
(venv) $ python -m pygame.examples.aliens
80 bag on line 151. If the
(venv) $ python -m pygame.examples.aliens
60 is returned, it’s also removed from the room’s
(venv) $ python -m pygame.examples.aliens
80. You then add the
(venv) $ python -m pygame.examples.aliens
60 to the player’s
(venv) $ python -m pygame.examples.aliens
74 on line 156.

Ứng dụng nâng cao

Tất nhiên, có nhiều hơn nữa cho Adventurelib. Để 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 liên quan hơn với câu chuyện hậu trường sau:

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

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

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

Có một số mặt hàng để thu thập, chẳng hạn như vũ khí và thực phẩm, 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ả các mã cho trò chơi này được liệt kê dưới đây và có thể được tìm thấy trong các tài liệu đã tải xuống:

Để giữ mọi thứ được tổ chức, 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
    
    85 Xác định các phòng và khu vực.
  • (venv) $ python -m pygame.examples.aliens
    
    86 Xác định các mục và thuộc tính của chúng.
  • (venv) $ python -m pygame.examples.aliens
    
    87 Xác định các ký tự mà bạn có thể tương tác.
  • (venv) $ python -m pygame.examples.aliens
    
    88 kéo mọi thứ lại với nhau, thêm các lệnh và bắt đầu trò chơi.

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

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

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

 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 với 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âu chuyện hậu trường, bạn đã vạch ra các khu vực trò chơi khác nhau và các đường dẫn mà người chơi sử dụng di chuyển giữa chúng:

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng python?

Mỗi khu vực có nhiều thuộc tính khác nhau liên quan đến nó, bao gồm:

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

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

(venv) $ python -m pygame.examples.aliens
48 được gọi là
(venv) $ python -m pygame.examples.aliens
90 trong
(venv) $ python -m pygame.examples.aliens
85 trên các dòng 15 đến 41. Các mục trong mỗi phòng được giữ trong một đối tượng
(venv) $ python -m pygame.examples.aliens
67 được gọi là
(venv) $ python -m pygame.examples.aliens
93 , được xác định trên các dòng 28 và 31. Bây giờ bạn có thể tạo các đối tượng
(venv) $ python -m pygame.examples.aliens
90, mô tả chúng và điền chúng với các mục và ký tự độc đáo, tất cả đều được nhập trên dòng 9 và 12.lines 15 to 41. Items in each room are held in a
(venv) $ python -m pygame.examples.aliens
67 object called
(venv) $ python -m pygame.examples.aliens
93, while characters are stored in
(venv) $ python -m pygame.examples.aliens
94, defined on lines 28 and 31. Now you can create
(venv) $ python -m pygame.examples.aliens
90 objects, describe them, and populate them with unique items and characters, which are all imported on lines 9 and 12.

Một số mục trò chơi được yêu cầu để hoàn thành trò chơi, trong khi những mục khác chỉ ở đó để có hương vị và thêm sự quan tâm. Các mặt hàng hương vị được xác định và đặt trên các dòng 192 đến 194, tiếp theo là các ký tự trên các dòng 197 đến 200.lines 192 to 194, followed by characters on lines 197 to 200.

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

(venv) $ python -m pygame.examples.aliens
86 là đối tượng loại
(venv) $ python -m pygame.examples.aliens
62. Các mục 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
59, một số thuộc tính phổ biến cơ bản được thêm vào lớp trên các dòng 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
(venv) $ python -m pygame.examples.aliens
99 được tạo trên các dòng 15 đến 19 và xác định từng thuộc tính phổ quát khi nó được tạo.lines 9 to 12. These properties are used when the item is created. For example, the
(venv) $ python -m pygame.examples.aliens
99 object is created on lines 15 to 19 and defines each of the universal properties when it is created.

Một số mục, tuy nhiên, có các thuộc tính cụ thể duy nhất cho các mặt hàng. Ví dụ, các mặt hà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()
00 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()
01 cần các thuộc tính để theo dõi thiệt hại mà họ gây ra và bất kỳ phần thưởng ma thuật nào họ mang theo. Chúng được thêm vào các dòng 43 đến 44 và 53 đến 54.lines 43 to 44 and 53 to 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 về phía trước và thường cung cấp cho người chơi một lý do để khám phá. Các nhân vật trong Adventurelib được tạo thành các đối tượng

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

Mỗi nhân vật, giống như mỗi mục, có các thuộc tính phổ quát được liên kết với nó, chẳng hạn như một mô tả dài và lời chào được sử dụng khi người chơi gặp nó lần đầu tiên. Các thuộc tính này được khai báo trên các dòng 9 và 10 và chúng được xác định cho từng ký tự khi nhân vật được tạo.lines 9 and 10, and they’re defined for each character when the character is created.

Tất nhiên, nếu bạn có nhân vật, thì người chơi nói chuyện và tương tác với họ rất hợp lý. Nó thường là một ý tưởng tốt để biết khi bạn tương tác với một nhân vật và khi bạn chỉ ở cùng một khu vực trò chơi với mộ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 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 các lệnh nhất định hoạt động khác nhau và họ 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.context. Contexts allow you to turn on different commands for different situations. They also allow certain commands to behave differently, and they track additional information about actions that the player may have taken.

Khi trò chơi bắt đầu, không có bối cảnh nào được thiết lập. Khi người chơi tiến triển, lần đầu tiên họ bắt gặp Elder Barron. Khi người chơi loạ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()
04, 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()
05, 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()
06.

Lời chào của Elder Barron, kết thúc với một câu hỏi có hoặc không có câu hỏi cho người chơi. Nếu người chơi loạ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()
07, thì bộ xử lý lệnh trên dòng 173 trong
(venv) $ python -m pygame.examples.aliens
88 được kích hoạt, được định nghĩa 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()
09, như được hiển thị bên dưới:line 173 in
(venv) $ python -m pygame.examples.aliens
88 is triggered, which is defined as
 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()
09, as shown below:

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng python?

Sau đó, khi người chơi đang nói chuyện với thợ rèn, một cấp độ thứ hai của bối cảnh được thêm vào để phản ánh rằng họ đã tham gia vào một giao dịch vũ khí có thể. Các dòng 203 đến 233 Xác định cuộc thảo luận với thợ rèn, bao gồm việc cung cấp một giao dịch 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()
07 được sử dụng thanh lịch theo nhiều cách.Lines 203 to 233 define the discussion with the blacksmith, which includes the offer of a weapons trade. A new context is defined on line 222, which allows the same
 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()
07 command to be used elegantly in multiple ways.

Bạn cũng có thể kiểm tra bối cảnh trong một trình xử lý lệnh. Ví dụ, người chơi không thể đơn giản 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()
11 được xác định trên các dòng 389 đến 403 kiểm tra xem người chơi có ở trong bối 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()
12, được nhập 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 ngăn chặn cuộc trò chuyện - đó là một cuộc chiến đến chết!lines 389 to 403 checks if the player is in the
 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 context, which is entered when they start fighting the giant. If so, they’re not allowed to stop the conversation — it’s a fight to the death!

Bạn cũng có thể đặt câu hỏi của người chơi yêu cầu một câu trả lời cụ thể. Khi người chơi nói chuyện với Wizard Trent, họ đã yêu cầu giải quyết một câu đố. Một câu trả lời không chính xác sẽ kết thúc sự tương tác. Mặc dù câu trả lời chính xác được xử lý với trình xử lý lệnh trên các dòng 252 đến 262, một trong những câu trả lời sai gần như vô hạn đã giành được phù hợp với bất kỳ trình xử lý nào.lines 252 to 262, one of the nearly infinite wrong answers won’t match any handler.

Các lệnh không có 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()
13 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 không chính xác cho câu đố của Wizard bằng cách kiểm tra bối 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()
14 trên dòng 498. cuộc hội thoại. 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()
15 với chức năng mới của bạn.lines 497 to 503. You leverage this to handle incorrect answers to the wizard’s riddle by checking for the
 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()
14 context on line 498. Any incorrect answer to the riddle will result in the wizard ending the conversation. You connect this to adventurelib on line 523 by setting
 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()
15 to your new function.

Bạn có thể tùy chỉnh lời nhắc đượ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.lines 483 to 495 and connected to adventurelib on line 520.

Tất nhiên, ở đó, luôn luôn có nhiều hơn bạn có thể thêm. Tạo ra 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 thách thức chính nằm ở việc vẽ một bức tranh bằng lời nói.

Ren

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, trong đó làm nổi bật khía cạnh kể chuyện của trò chơi, hạn chế các 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 thị giác là tiểu thuyết đồ họa của thế giới trò chơi - hiện đại, sáng tạo và cực kỳ hấp dẫn để tạo và tiêu thụ.

Ren KhănPy là một công cụ dựa trên pygame và được thiết kế đặc biệt để tạo ra tiểu thuyết trực quan. Ren hèpy lấy tên của nó từ từ tiếng Nhật cho tình yêu lãng mạn và cung cấp các công cụ và một khung để chế tạo các tiểu thuyết hình ảnh hấp dẫn.

Công bằng mà nói, Ren hè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()
16 và sử dụng. Các trò chơi Ren KhănPy được tạo ra bằng cách sử dụng trình khởi chạy Ren hèpy, đi kèm với toàn bộ SDK của Ren. Trình khởi chạy này cũng có trình soạn thảo trò chơi, mặc dù bạn có thể chỉnh sửa trò chơi của mình trong trình soạn thảo lựa chọn. Ren KhănPy cũng có ngôn ngữ kịch bản của riêng mình để tạo trò chơi. Tuy nhiên, Ren hèpy dựa trên pygame, và nó có thể mở rộng bằng cách sử dụng Python, đảm bảo sự xuất hiện của nó ở đây.

Cài đặt ren

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

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

  • các cửa sổ
  • Linux
  • hệ điều hành Mac

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

Người dùng Linux nên tải tarball được cung cấp vào một vị trí thuận tiện, sau đó mở rộng nó bằ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()
17.

Người dùng MacOS nên tải xuống tệp DMG được cung cấp, bấm đúp vào tệp để mở và sao chép nội dung vào 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 có chứa SDK sau đó chạy trình khởi chạy REN MạnhPy. 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()
18, 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()
19. Điều này sẽ bắt đầu trình khởi chạy Ren hèPy lần đầu tiên:

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng python?

Đây là nơi bạn sẽ bắt đầu các dự án mới của ren, 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 Muffpy.

Các khái niệm cơ bản

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

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng python?

Các trò chơi Ren KhănPy được chứa trong các tệp được gọi là tập lệnh. Don Tiết nghĩ về các kịch bản Ren hèpy khi bạn sẽ phát hiện các tập lệnh. Họ tương tự hơn với các kịch bản cho các vở kịch hoặc chương trình truyền hình. Các tập lệnh Ren hèpy có phần mở rộ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()
20 và được viết bằng ngôn ngữ Ren hèPy. Trò chơi của bạn có thể bao gồm nhiều tập lệnh 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()
21 của thư mục dự án của bạn.scripts. Don’t think of Ren’Py scripts as you would shell scripts. They’re more analogous to scripts for plays or television shows. Ren’Py scripts have the extension
 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()
20 and are written in the Ren’Py language. Your game can consist of as many scripts as you like, which are all stored in the
 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 subfolder of your project folder.

Khi bạn tạo một dự án ren mới, các tập lệnh sau đượ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()
    
    22, xác định giao diện của tất cả các yếu tố UI đượ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()
    
    23, 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()
    
    24, xác định các kiểu được sử dụng cho đố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()
    
    25, đó 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. Bắt đầu trình khởi chạy ren.
  2. Nhấp vào Tùy chọn, sau đó 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()
    
    26 trong kho lưu trữ mà bạn đã tải xuống.
  4. Nhấp vào Quay lại để quay lại trang Launcher Ren hè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()
27 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()
28 trong danh sách các dự án ở bên trái. Chọn một cái mà bạn muốn chạy, sau đó nhấp vào Dự án Khởi chạy.

Đố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()
25 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()
27. Mã hoàn chỉnh cho trò chơi này có thể được tìm thấy trong các tài liệu đã tải xuống, cũng như dưới đâ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()
2

Nhãn xác định các điểm nhập cảnh 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ế thông qua câu chuyện. Tất cả các trò chơi Ren KhănPy 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()
31, 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()
25.line 12 of
 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.

Bạn cũng có thể sử dụng nhãn để xác định hình ảnh nền, thiết lập chuyển đổi 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 trên 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()
33.line 54 with the line
 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.

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

Khi bắt đầu trò chơi, tường thuật được nhìn thấy trên dòng 16, đặt 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.line 16, which sets the scene. Dialogue is provided on line 18, when your mom calls to you.

Bạn có thể xác định các ký tự bằng cách đặt tên cho chúng 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 bạn. Bạn có thể thấy điều này trên các dòng 6 đến 8, nơi bạn, anh trai Kevin và mẹ 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()
34 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()
35, 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.lines 6 to 8, where you, your brother Kevin, and your mom are defined. The
 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 statement initializes the three variables as
 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, giving them a display name, followed by a text color used to display the name.

Tất nhiên, đây là một cuốn tiểu thuyết trực quan, vì vậy nó có ý nghĩa rằng Ren hèpy sẽ có cách để xử lý hình ảnh. Giống như Pygame Zero, Ren hèPy yêu cầu tất cả các hình ảnh và âm thanh được sử dụng trong trò chơi nằm trong các thư mục cụ thể. Hình ảnh được tìm thấy 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()
36 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()
37. Trong tập lệnh trò chơi, bạn tham khảo 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 cho thấy điều này trong hành động, khi bạn mở mắt và nhìn thấy phòng ngủ của bạn 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()
38 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()
39. Ren MạnhPy hỗ trợ các định dạng hình ảnh JPG, Webp và PNG.
shows this in action, when you open your eyes and see your bedroom for the first time. The
 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 keyword clears the screen, then displays the
 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 image. Ren’Py supports the JPG, WEBP, and PNG image formats.

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()
40 và cùng một quy ước đặt tên cho hình ảnh. Dòng 41 cho thấy hình ảnh của anh trai Kevin của bạn, được lưu trữ 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()
41.Line 41 shows a picture of your brother Kevin, stored as
 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()
41.

Tất nhiên, nó không phải là một trò chơi nếu bạn có thể đưa ra quyết định ảnh hưởng đến kết quả. Trong Ren KhănPy, người chơi đưa ra các lựa chọn từ một thực đơn được trình bày cho họ trong quá trình của trò chơi. Trò chơi phản ứng bằng cách nhảy vào 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, trong đó bạn nhận ra rằng bạn đã quên điện thoại của mình. Trong một câu chuyện đầy đủ hơn, sự lựa chọn này có thể có hậu quả sau này.lines 47 to 52, where you realize you’ve forgotten your phone. In a more complete story, this choice may have consequences later.

Tất nhiên, bạn có thể làm nhiều hơn nữa với Ren hèpy. Bạn có thể kiểm soát chuyển đổi giữa các cảnh, để các nhân vật nhập và để lại cảnh theo những cách cụ thể, và bao gồm âm thanh và âm nhạc cho trò chơi của bạn. Ren KhănPy cũng hỗ trợ viết mã Python phức tạp hơn, bao gồm sử dụng các loại dữ liệu Python và thực hiện các cuộc gọi chức năng 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.

Ứng dụng nâng cao

Để hiển thị độ sâu của Ren hèPy, bạn sẽ thực hiện trò chơi tương tự như bạn đã làm cho Adventurelib. Như một lời nhắc nhở, ở đây, thiết kế cơ bản của trò chơi đó:

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

Trò chơi có một số lĩnh 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 bạn, con đường dẫn ra khỏi cánh đồng, một ngôi làng gần đó, nơi bạn có thể mua một vũ khí tốt hơn, một con đường phụ dẫn đến một phù thủy có thể mê hoặc vũ khí của bạn và Hang động chứa người khổng lồ đã lấy vật nuôi của bạn.

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 một vũ khí tốt hơn, một phù thủy có thể mê hoặc vũ khí của bạn và người khổng lồ mà bạn cần để đánh bại.

Trong 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()
    
    25, đó 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()
    
    43, 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()
    
    44, chứa 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()
    
    45, chứa logic cho trận chiến khổng lồ

Bạn có thể tạo cuộc gặp gỡ của Wizard như một bài tập độc lập.

Mã hoàn chỉnh cho trò chơi này có thể được tìm thấ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()
46 và cũng có sẵn dưới đâ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()
3

 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

 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

 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 các đố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()
47 trước khi tập lệnh bắt đầu trên các 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()
25.lines 14 to 17 of
 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.

Bạn cũng có thể xác định 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()
49 đối tượng để sử dụng sau. Các dòng 21 đến 27 Xác định một số hình ảnh mà bạn đề cập sau này, cả hai đều sử dụng làm nền và hiển thị dưới dạng các mục. Sử dụng cú pháp này cho phép bạn gán tên bên trong ngắn hơn và mô tả hơn cho hình ảnh. Sau đó, bạn sẽ thấy cách họ hiển thị.Lines 21 to 27 define several images which you refer to later, both to use as backgrounds and to display as items. Using this syntax allows you to assign shorter and more descriptive internal names for images. Later, you’ll see how they’re displayed.

Bạn cũng cần theo dõi các 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()
50 mà bạn sẽ sử dụng trong trận chiến khổng lồ sau đó.lines 31 to 37, using
 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 variable values, which you’ll use during the giant battle later.

Để chỉ ra vũ khí nào được bật, bạn hiển thị hình ảnh dưới dạng biểu thức. Các biểu thức Ren KhănPy là những hình ảnh nhỏ được 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 để hiển thị 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()
51 đầu tiên trên các dòng 67 và 68.expression. Ren’Py expressions are small images displayed in the corners of the game window and are used to show a wide variety of information. For this game, you use an expression to show the weapon using
 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 first on lines 67 and 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()
40 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()
53 khiến 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()
54 trượt lên màn hình từ bên trái. Ngoài ra, điều quan trọng cần nhớ là mỗi lầ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()
38 thay đổi, toàn bộ màn hình được 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 rằng trên các dòng 75 đến 78.lines 75 to 78.

Khi bạn vào thị trấn và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()
43, bạn gặp thợ rèn, người chào đón bạn:

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng python?

Người thợ rèn cung cấp cho bạn cơ hội để nâng cấp vũ khí của bạn. Nếu bạn chọn làm như vậy, thì bạn sẽ 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()
54 và số liệu thống kê vũ khí. Điều này được thực hiện trên các dòng 93 đến 98.lines 93 to 98.

Các dòng bắt đầu với 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()
58 được Ren hè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 thiết. Cập nhật các chỉ 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()
54 và vũ khí được thực hiện bằng cách sử dụng ba câu lệnh Python trên các dòng 96 đến 98, thay đổi các giá trị của các 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()
50 mà bạn xác định ở đầ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()
25.lines 96 to 98, which change the values of the the
 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 variables that you defined at the top of
 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.

Bạn cũng có thể xác định một khối lớn mã Python bằ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()
62, 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()
45 bắt đầu trên dòng 41.line 41.

Các dòng 43 đến 61 chứa một hàm 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 hit khổng lồ còn lại. Nó sử dụng phương thứ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()
64 để đầu ra tường thuật trở lại cửa sổ Ren Muffpy chính. Một chức năng trợ giúp tương tự để hiển thị điều kiện của người chơi được nhìn thấy trên các dòng 63 đến 85. contain a helper function to show the condition of the giant, based on the giant’s remaining hit points. It uses the
 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 method to output narration back to the main Ren’Py window. A similar helper function to show the player’s condition is seen on lines 63 to 85.

Trận chiến được kiểm soát 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()
65 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()
66. Lựa chọn của người chơi về chiến đấu hoặc chạy trốn đượ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()
67.lines 87 to 159. The game loop is implemented on line 98 and is controlled by the
 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 variable. Player choices of fight or flee are displayed using the
 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 method.

Nếu người chơi chiến đấu, thì một lượng sát thương ngẫu nhiên được thực hiện trên các dòng 116 đến 118 và các điểm nhấn 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ự trên 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 nào hoặc cho đến khi người chơi chạy trốn:lines 116 to 118, and the giant’s hit points are adjusted. If the giant is still alive, then they get to attack in a similar fashion on lines 136 to 149. Note that the giant has a chance to miss, while the player always hits. The fight continues either until the player or the giant has zero hit points or until the player flees:

Hướng dẫn what 3d game engines use python? - những gì công cụ trò chơi 3d sử dụng python?

Nó lưu ý rất quan trọng rằng 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 của mình mà không cần dịch nó thành tập lệnh Ren.

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

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

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

  • Wasabi 2D được phát triển bởi nhóm đằng sau Pygame Zero. Nó có 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 các hiệu ứng hoạt hình, 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. Đáng buồn thay, Cocos2D-Python đã được cập nhật từ năm 2017.

  • Panda 3D là một khung công tác nguồn mở để tạo các 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 tài sản, kết nối ra khỏi hộp 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.

  • Ursina được xây dựng trên đỉnh 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 ghi chép tốt, Ursina đang được phát triển tích cực tại thời điểm viết bài này.

  • Theo đuổiPybear đượ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 sprites hoạt hình dựa trên khung có thể bị tạm dừng và một rào cản thấp để nhập cảnh. Tài liệu rất thưa thớt, nhưng sự giúp đỡ chỉ là một cuộc thảo luận của GitHub.

Độ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 thứ phù hợp với nhu cầu của bạn và đã được đề cập ở đây, xin vui lòng hát những lời khen ngợi của nó trong các bình luận!

Nguồn cho tài sản trò chơi

Thông thường, tạo tài sản 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 video lớn sử dụng các nhóm nghệ sĩ, nhà làm phim hoạt hình và nhạc sĩ để thiết kế vẻ ngoài và âm thanh của các trò chơi của họ. Các nhà phát triển trò chơi solo có nền tảng về mã hóa có thể tìm thấy khía cạnh này của sự phát triển trò chơi khó khăn. May mắn thay, có nhiều nguồn khác nhau cho tài sản trò chơi có sẵn. Dưới đây là một số người rất quan trọng trong việc định vị tài sản cho các trò chơi trong hướng dẫn này:

  • OpenGameart.org tổ chức nhiều loại nghệ thuật trò chơi, âm nhạc, nền tảng, biểu tượng và các tài sản khác cho cả trò chơi 2D và 3D. Các nghệ sĩ và nhạc sĩ liệt kê tài sản của họ để tải xuống, bạn có thể tải xuống và sử dụng trong các trò chơi của mình. Hầu hết các tài sản đề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 trong số chúng.

  • Kenney.nl lưu trữ một bộ tài sản miễn phí và được trả tiền, nhiều 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 tài sản 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.

  • Itch.io là một thị trường cho các nhà sáng tạo kỹ thuật số tập trung vào phát triển trò chơi độc lập. Ở đây bạn có thể tìm thấy tài sản kỹ thuật số cho bất kỳ mục đích nào, cả miễn phí và được trả tiền, 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 chính họ ở đây, vì vậy bạn luôn làm việc trực tiếp với các cá nhân tài năng.

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

Tất cả các tài sản được sử dụng trong các trò chơi được tham chiếu trong bài viết này phù hợp với các yêu cầu cấp phép tương ứng của họ.

Sự kết luận

Xin chúc mừng, thiết kế trò chơi tuyệt vời hiện đang nằm trong tầm tay của bạn! Nhờ Python và một bữa tiệc buffet của các công cụ trò chơi Python có khả năng cao, bạn có thể tạo ra 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 chế tạo các trò chơi video Python của riêng bạn!

Đến bây giờ, bạn đã thấy một số động cơ trò chơi Python hàng đầu trong hành động và bạn đã làm việc:

  • Khám phá những ưu và nhược điểm của một số động cơ trò chơi Python nổi tiếngpros and cons of several popular Python game engines
  • Trải nghiệm cách họ so sánh với các công cụ trò chơi độc lậpcompare to stand-alone game engines
  • Đã tìm hiểu về các động cơ trò chơi Python khác có sẵnother Python game engines available

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:

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 bạn. Bạn đang chờ đợi điều gì? Ra khỏi đó và viết một số trò chơi!

Động cơ trò chơi nào sử dụng Python?

Pygame.Khi mọi người nghĩ về động cơ trò chơi Python, suy nghĩ đầu tiên mà nhiều người có là pygame.Trên thực tế, đã có một đoạn mồi tuyệt vời trên pygame có sẵn tại Real Python.Được viết để thay thế cho thư viện PYSDL bị đình trệ, kết thúc tốt đẹp và mở rộng thư viện SDL, viết tắt của lớp DirectMedia đơn giản.. 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.

Python sử dụng động cơ 3D nào?

Pyxel, một công cụ trò chơi retro cho Python, đạt 300.000 lượt tải xuống!, a retro game engine for Python, reaches 300,000 downloads!

Động cơ trò chơi 3D nào hỗ trợ các trò chơi dựa trên Python?

Câu trả lời.Giải thích: Pysoy - Pysoy là một công cụ trò chơi 3D hỗ trợ các trò chơi dựa trên Python.PySoy is a 3D game engine that supports Python based games.

Bạn có thể sử dụng Python cho các trò chơi 3D không?

Nếu bạn quan tâm đến việc học cách sử dụng pygame để tạo trò chơi 3D, hai trang web dành riêng cho 3D Python là Python 3D (py3d.org) và phần mềm Python 3D.Bạn có thể tìm thấy một số dự án trò chơi 3D có sẵn ở đây.Pyweek là một trang web thử thách lập trình hai năm một lần sản xuất một số trò chơi tuyệt vời.two sites that are dedicated to 3D Python are Python 3D(py3d.org) and Python 3D Software. You can find several 3D game projects available here. PyWeek is a bi-annual programming challenge site that produces several great games.