Rumah >pembangunan bahagian belakang >Tutorial Python >Bagaimana untuk Mengesan Perlanggaran Antara Segi Empat dalam Pygame?

Bagaimana untuk Mengesan Perlanggaran Antara Segi Empat dalam Pygame?

Barbara Streisand
Barbara Streisandasal
2024-12-24 13:55:16439semak imbas

How to Detect Collisions Between Rectangles in Pygame?

Cara Mengesan Perlanggaran Antara Dua Objek Segiempat atau Imej dalam Pygame

Masalah:

Anda sedang membangunkan permainan di mana mangkuk mesti menangkap barang yang jatuh. Anda mempunyai imej untuk item dan mangkuk, tetapi tidak pasti cara untuk mengesan perlanggaran antara mereka.

import math
import pygame
import random

# Game initialization
pygame.init()
# Screen dimensions
display_width = 800
display_height = 600

# Initialize the screen
game_display = pygame.display.set_mode((display_width, display_height))
# Set the clock
clock = pygame.time.Clock()
# Game title
pygame.display.set_caption("Catch the Ball")

# Colors and images
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 255, 0)

player_img = pygame.image.load("Images/soup.png")
thing_imgs = [
    pygame.image.load('Images/muffin.png'),
    pygame.image.load('Images/dessert.png'),
    pygame.image.load('Images/cheese.png'),
    pygame.image.load('Images/fruit.png'),
]


def player(x, y):
    game_display.blit(player_img, (x, y))


def things(x, y, img):
    game_display.blit(img, (x, y))


def game_loop():
    running = True

    x = display_width * 0.45
    y = display_height * 0.8
    x_change = 0

    player_width = 64
    player_height = 64

    things_cor = [[random.randint(0, display_width), 32]]
    things_added = [random.choice(thing_imgs)]
    thing_height = 32
    thing_width = 32
    y_change = 5

    caught = 0

    while running:
        for event in pygame.event.get():
            # Quit the game
            if event.type == pygame.QUIT:
                running = False

            # Player movement
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    x_change = -5

                if event.key == pygame.K_RIGHT:
                    x_change = 5

            # Stop player movement
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    x_change = 0

        # Clear the screen
        game_display.fill(white)

        player(x, y)
        # Update the player's position
        x += x_change

        for i in range(len(things_cor)):
            thing_x, thing_y = things_cor[i]
            things(thing_x, thing_y, things_added[i])

        for i in range(len(things_cor)):
            things_cor[i][1] += y_change
            # Reset the item to the top of the screen if it goes off the bottom
            if things_cor[i][1] > display_height:
                things_cor[i][1] = random.randint(-2000, -1000)
                things_cor[i][0] = random.randint(0, display_width)
                things_added[i] = random.choice(thing_imgs)

                # Add a new item if the list is less than 6
                if len(things_added) < 6:
                    things_cor.append(
                        [random.randint(0, display_width), -10]
                    )

        # Limit player movement
        if x < 0:
            x = 0
        elif x > display_width - player_width:
            x = display_width - player_width

        # Delay the game start by 100 seconds
        passed_time = pygame.time.get_ticks()  # Time in milliseconds
        start_time = 100 * 1000  # Start time in milliseconds

        # Update the scene and display
        if passed_time >= start_time:
            game_display.fill(white)
            player(x, y)
            for i in range(len(things_cor)):
                thing_x, thing_y = things_cor[i]
                things(thing_x, thing_y, things_added[i])
            pygame.display.update()

        # Set the frame rate
        clock.tick(60)


game_loop()

Penyelesaian:

Untuk mengesan perlanggaran antara dua objek segi empat tepat atau imej dalam Pygame, gunakan objek pygame.Rect dan colliderect() kaedah:

# Create rectangles for the player and the items
player_rect = player_img.get_rect(topleft = (x, y))
for i in range(len(things_cor)):
    thing_rect = things_added[i].get_rect(topleft = things_cor[i])

# Check for collisions
if player_rect.colliderect(thing_rect):
    print("hit")

Dengan meletakkan kod ini dalam gelung permainan, anda boleh terus menyemak perlanggaran antara pemain dan item.

Atas ialah kandungan terperinci Bagaimana untuk Mengesan Perlanggaran Antara Segi Empat dalam Pygame?. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn