我如何在碰撞时重生

发布于 2025-02-06 17:31:29 字数 6127 浏览 1 评论 0原文

我一直在与敌人一起制作一个简单的收藏游戏,但我不知道如何在与之相撞后将收藏品产生在随机位置。就像在玩家与硬币相撞的许多硬币收集器游戏中一样,它在另一个位置产卵,并且有一个得分系统,我尝试了很多次,但失败了。请帮忙!这是我的代码:

#import some libraries
import sys
import random
import pygame
from pygame import mixer


pygame.init()
mixer.init()
pygame.font.init()
width = 1440
height = 810
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('test')
collectible_img = pygame.image.load('img/collectible.png')
pygame.display.set_icon(collectible_img)
white = (255, 255, 255)
intro = pygame.mixer.Sound('sfx/intro.ogg')
gameplay = pygame.mixer.Sound('sfx/gameplay.ogg')
coll_audio = pygame.mixer.Sound('sfx/cool.ogg')
screen_rect = screen.get_rect()
score = 0
txt = pygame.font.SysFont("Britannic Bold", 40)
class Player(pygame.sprite.Sprite):

    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('img/player.png')
        self.rect = self.image.get_rect()
        self.x = 300
        self.y = 640
        self.speed = 10

    def keyboard(self, keys):
        if keys[pygame.K_UP]:
            self.y -= self.speed
        if keys[pygame.K_DOWN]:
            self.y += self.speed
        if keys[pygame.K_RIGHT]:
            self.x += self.speed
        elif keys[pygame.K_LEFT]:
            self.x -= self.speed
    def update(self):
        self.rect.topleft = self.x, self.y


class Collectible(pygame.sprite.Sprite):

    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('img/collectible.png')
        self.rect = self.image.get_rect()
        self.x = 200
        self.y = 100

    def update(self):
        self.rect.topleft = self.x, self.y
class Enemy(pygame.sprite.Sprite):

    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('img/enemy.png')
        self.rect = self.image.get_rect()
        self.movementx = random.randrange(10, 50)
        self.movementy = random.randrange(10, 50)
        self.x = 900
        self.y = 500
    def update(self):
        self.rect.topleft = self.x, self.y
def play_screen(end_it, cutscence):
    while (end_it == False):
        screen.fill(white)
        intro.play(0)
        bg = pygame.image.load('img/splashscreen.png')
        font = pygame.font.SysFont("Britannic Bold", 40)
        label = font.render("test", 1, (255, 0, 0))
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                end_it = True
                intro.stop()
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                gameplay.stop()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                    gameplay.stop()
                    intro.stop()
        screen.blit(bg, (0, 0))
        pygame.display.flip()
    while (cutscence == False): 
        coll_audio.play(0)
        test2 = pygame.image.load('img/player.png')
        screen.fill((0, 0, 0))
        text = font.render("Click to continue", 1, (255, 255, 255))
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                cutscence = True
                coll_audio.stop()
                gameplay.play(0)
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
        screen.blit(text, (50, 50))
        screen.blit(test2, (500, 500))
        pygame.display.flip()

def play_again():
    player = Player()
    collectible = Collectible()
    enemy = Enemy()
    all_sprites = pygame.sprite.Group(player, collectible, enemy)
    collectibles = pygame.sprite.Group(collectible)
    enemies = pygame.sprite.Group(enemy)
    pos = pygame.mouse.get_pos()
    global score
    clock = pygame.time.Clock()
    running = True
    end_it = False
    game = False
    cutscence = False
    end_screen = False
    exit_screen = False
    while running:
        while (exit_screen == True):
            font = pygame.font.SysFont("Britannic Bold", 40)
            exit_img = pygame.image.load('img/death.png')
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    exit_screen = False
                    gameplay.play()
                    play_again()
                if event.type == pygame.QUIT:
                    exit_screen = False
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        exit_screen = False
                        pygame.quit()
                        sys.exit()
            screen.blit(exit_img, (0, 0))
            pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                    sys.exit()
        keys = pygame.key.get_pressed()
        player.keyboard(keys)
        all_sprites.update()
        global collided_collectibles
        collided_collectibles = pygame.sprite.spritecollide(player, collectibles, True)
        for collided_collectible in collided_collectibles:
            print('Collision.')
            score += 1
        collided_enemies = pygame.sprite.spritecollide(player, enemies, False)
        for collided_enemy in collided_enemies:
            exit_screen = True
            score *= 0
            gameplay.stop()
        screen.fill((255, 255, 255))
        score_counter = txt.render("Score: " + str(score), 1, (0, 0, 0))
        screen.blit(score_counter, (0, 0))
        all_sprites.draw(screen)
        pygame.display.flip()
        clock.tick(30)

play_screen(False, False)
play_again()
pygame.quit()
sys.exit()

I have been making a simple collecter game with enemies but I have no idea how to make the collectible spawn in a random position upon being collided with. Just like in many coin collecter games when the player collides with the coin, it spawns in a different spot and there is a scoring system I have tried too many times but it has failed. Please help! Here is my code:

#import some libraries
import sys
import random
import pygame
from pygame import mixer


pygame.init()
mixer.init()
pygame.font.init()
width = 1440
height = 810
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('test')
collectible_img = pygame.image.load('img/collectible.png')
pygame.display.set_icon(collectible_img)
white = (255, 255, 255)
intro = pygame.mixer.Sound('sfx/intro.ogg')
gameplay = pygame.mixer.Sound('sfx/gameplay.ogg')
coll_audio = pygame.mixer.Sound('sfx/cool.ogg')
screen_rect = screen.get_rect()
score = 0
txt = pygame.font.SysFont("Britannic Bold", 40)
class Player(pygame.sprite.Sprite):

    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('img/player.png')
        self.rect = self.image.get_rect()
        self.x = 300
        self.y = 640
        self.speed = 10

    def keyboard(self, keys):
        if keys[pygame.K_UP]:
            self.y -= self.speed
        if keys[pygame.K_DOWN]:
            self.y += self.speed
        if keys[pygame.K_RIGHT]:
            self.x += self.speed
        elif keys[pygame.K_LEFT]:
            self.x -= self.speed
    def update(self):
        self.rect.topleft = self.x, self.y


class Collectible(pygame.sprite.Sprite):

    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('img/collectible.png')
        self.rect = self.image.get_rect()
        self.x = 200
        self.y = 100

    def update(self):
        self.rect.topleft = self.x, self.y
class Enemy(pygame.sprite.Sprite):

    def __init__(self):
        super().__init__()
        self.image = pygame.image.load('img/enemy.png')
        self.rect = self.image.get_rect()
        self.movementx = random.randrange(10, 50)
        self.movementy = random.randrange(10, 50)
        self.x = 900
        self.y = 500
    def update(self):
        self.rect.topleft = self.x, self.y
def play_screen(end_it, cutscence):
    while (end_it == False):
        screen.fill(white)
        intro.play(0)
        bg = pygame.image.load('img/splashscreen.png')
        font = pygame.font.SysFont("Britannic Bold", 40)
        label = font.render("test", 1, (255, 0, 0))
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                end_it = True
                intro.stop()
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
                gameplay.stop()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
                    gameplay.stop()
                    intro.stop()
        screen.blit(bg, (0, 0))
        pygame.display.flip()
    while (cutscence == False): 
        coll_audio.play(0)
        test2 = pygame.image.load('img/player.png')
        screen.fill((0, 0, 0))
        text = font.render("Click to continue", 1, (255, 255, 255))
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                cutscence = True
                coll_audio.stop()
                gameplay.play(0)
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    sys.exit()
        screen.blit(text, (50, 50))
        screen.blit(test2, (500, 500))
        pygame.display.flip()

def play_again():
    player = Player()
    collectible = Collectible()
    enemy = Enemy()
    all_sprites = pygame.sprite.Group(player, collectible, enemy)
    collectibles = pygame.sprite.Group(collectible)
    enemies = pygame.sprite.Group(enemy)
    pos = pygame.mouse.get_pos()
    global score
    clock = pygame.time.Clock()
    running = True
    end_it = False
    game = False
    cutscence = False
    end_screen = False
    exit_screen = False
    while running:
        while (exit_screen == True):
            font = pygame.font.SysFont("Britannic Bold", 40)
            exit_img = pygame.image.load('img/death.png')
            for event in pygame.event.get():
                if event.type == pygame.MOUSEBUTTONDOWN:
                    exit_screen = False
                    gameplay.play()
                    play_again()
                if event.type == pygame.QUIT:
                    exit_screen = False
                    pygame.quit()
                    sys.exit()
                elif event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_ESCAPE:
                        exit_screen = False
                        pygame.quit()
                        sys.exit()
            screen.blit(exit_img, (0, 0))
            pygame.display.flip()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    running = False
                    sys.exit()
        keys = pygame.key.get_pressed()
        player.keyboard(keys)
        all_sprites.update()
        global collided_collectibles
        collided_collectibles = pygame.sprite.spritecollide(player, collectibles, True)
        for collided_collectible in collided_collectibles:
            print('Collision.')
            score += 1
        collided_enemies = pygame.sprite.spritecollide(player, enemies, False)
        for collided_enemy in collided_enemies:
            exit_screen = True
            score *= 0
            gameplay.stop()
        screen.fill((255, 255, 255))
        score_counter = txt.render("Score: " + str(score), 1, (0, 0, 0))
        screen.blit(score_counter, (0, 0))
        all_sprites.draw(screen)
        pygame.display.flip()
        clock.tick(30)

play_screen(False, False)
play_again()
pygame.quit()
sys.exit()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

满意归宿 2025-02-13 17:31:29

我认为问题在于您将类collectible的产卵坐标进行了硬化。您可以制作一个小功能,该功能在屏幕的宽度和高度范围内生成一个随机数,并在创建类的新实例时作为参数传递。

随机产卵坐标的功能:

import random
def spawn_random():
    spawn_x = random.randint(0, 1440)
    spawn_y = random.randint(0,810)
    return spawn_x, spawn_y # returns a tuple, e.g (200, 400)

您的同类需要一些一些更改:

class Collectible(pygame.sprite.Sprite):
    def __init__(self, xy_spawn):
        super().__init__()
        self.image = pygame.image.load('img/collectible.png')
        self.x, self.y = xy_spawn
        self.rect = self.image.get_rect(topleft=(self.x, self.y))

首次创建一个实例collectible = collectible(((200,100),您可以使用您喜欢生成的开始坐标,之后,每次收集都应再次产生(碰撞或任何其他事件)

collectible = Collectible(spawn_random())

I think the problem is that you hardcorded the spawn coordinates of your class Collectible. You could make a little function which generates a random number in range of width and height of your screen and pass it as argument when creating a new instance of the class.

Function for random spawn coordinates:

import random
def spawn_random():
    spawn_x = random.randint(0, 1440)
    spawn_y = random.randint(0,810)
    return spawn_x, spawn_y # returns a tuple, e.g (200, 400)

Your class needs some little changes:

class Collectible(pygame.sprite.Sprite):
    def __init__(self, xy_spawn):
        super().__init__()
        self.image = pygame.image.load('img/collectible.png')
        self.x, self.y = xy_spawn
        self.rect = self.image.get_rect(topleft=(self.x, self.y))

When creating an instance for the first time collectible = Collectible((200,100) you can use your start coordinates where you like to spawn it to start with. After that, everytime the collectible should be spawned again (after collision or any other event) you call it like this:

collectible = Collectible(spawn_random())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文