微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

当我使用 Pygame 在 python 中达到某个点时显示“You Win”

如何解决当我使用 Pygame 在 python 中达到某个点时显示“You Win”

我想知道当我的玩家在游戏中达到 2000 分时,如何在游戏结束时显示“You Win”和图片。我还想在玩家与类 Reseta 碰撞时随机显示一个提示。下面是我目前的代码。请对我有耐心。谢谢!

import pygame
import os
import random

pygame.init()
pygame.display.set_caption("Chimera")
SCREEN_HEIGHT = 576
SCREEN_WIDTH = 936
SCREEN = pygame.display.set_mode((SCREEN_WIDTH,SCREEN_HEIGHT))

RUNNING = [pygame.transform.scale(pygame.image.load("images/Main1_side_right.png"),(64,64)),pygame.transform.scale(pygame.image.load("images/Main1_side_right_1.png"),pygame.transform.scale(pygame.image.load("images/Main1_side_right_2.png"),pygame.transform.scale(pygame.image.load("images/Main1_side_right_3.png"),pygame.transform.scale(pygame.image.load("images/Main1_side_right_4.png"),pygame.transform.scale(pygame.image.load("images/Main1_side_right_5.png"),pygame.transform.scale(pygame.image.load("images/Main1_side_right_6.png"),pygame.transform.scale(pygame.image.load("images/Main1_side_right_7.png"),64))]

JUMPING = pygame.transform.scale(pygame.image.load("images/Main1_jump_right.png"),64))

DUCKING = [pygame.transform.scale(pygame.image.load("images/slide3.png"),pygame.transform.scale(pygame.image.load("images/slide3.png"),64))]

TREE = [pygame.transform.scale(pygame.image.load("images/Tree_1.png"),140)),pygame.transform.scale(pygame.image.load("images/Tree_1.png"),pygame.transform.scale(pygame.image.load("images/Tree_2.png"),140))]
Box = [pygame.transform.scale(pygame.image.load("images/Box1.png"),(110,90)),pygame.transform.scale(pygame.image.load("images/Box2.png"),pygame.transform.scale(pygame.image.load("images/Box3.png"),90))]

SHADOW = [pygame.transform.scale(pygame.image.load("images/Enemy_1.png"),pygame.transform.scale(pygame.image.load("images/Enemy_2.png"),]

PORTAL = [pygame.transform.scale(pygame.image.load("images/portal_real.png"),128)),pygame.transform.scale(pygame.image.load("images/portal_real.png"),128))]

RESETA = [pygame.transform.scale(pygame.image.load("images/reseta_real.png"),(45,120)),pygame.transform.scale(pygame.image.load("images/reseta_real.png"),120))]
DRUG = [pygame.transform.scale(pygame.image.load("images/Drug.png"),pygame.transform.scale(pygame.image.load("images/Drug.png"),90))]

STANDING = pygame.transform.scale(pygame.image.load("images/Main1_front.png"),64))
BG = pygame.image.load(os.path.join("images","Background_2.jpg"))

class Boy:
    X_POS = 80
    Y_POS = 390
    Y_POS_DUCK = 430
    JUMP_VEL = 8.5

    def __init__(self):
        self.duck_img = DUCKING
        self.run_img = RUNNING
        self.jump_img = JUMPING

        self.boy_duck = False
        self.boy_run = True
        self.boy_jump = False

        self.step_index = 0
        self.jump_vel = self.JUMP_VEL
        self.image = self.run_img[0]
        self.boy_rect = self.image.get_rect()
        self.boy_rect.x = self.X_POS
        self.boy_rect.y = self.Y_POS

    def update(self,userInput):
        if self.boy_duck:
            self.duck()
        if self.boy_run:
            self.run()
        if self.boy_jump:
            self.jump()

        if self.step_index >= 10:
            self.step_index = 0

        if userInput[pygame.K_UP] and not self.boy_jump:
            self.boy_duck = False
            self.boy_run = False
            self.boy_jump = True
        elif userInput[pygame.K_DOWN] and not self.boy_jump:
            self.boy_duck = True
            self.boy_run = False
            self.boy_jump = False
        elif not (self.boy_jump or userInput[pygame.K_DOWN]):
            self.boy_duck = False
            self.boy_run = True
            self.boy_jump = False

    def duck(self):
        self.image = self.duck_img[self.step_index // 5]
        self.boy_rect = self.image.get_rect()
        self.boy_rect.x = self.X_POS
        self.boy_rect.y = self.Y_POS_DUCK
        self.step_index += 1

    def run(self):
        self.image = self.run_img[self.step_index // 5]
        self.boy_rect = self.image.get_rect()
        self.boy_rect.x = self.X_POS
        self.boy_rect.y = self.Y_POS
        self.step_index += 1

    def jump(self):
        self.image = self.jump_img
        if self.boy_jump:
            self.boy_rect.y -= self.jump_vel * 4
            self.jump_vel -= 0.8
        if self.jump_vel < - self.JUMP_VEL:
            self.boy_jump = False
            self.jump_vel = self.JUMP_VEL

    def draw(self,SCREEN):
        SCREEN.blit(self.image,(self.boy_rect.x,self.boy_rect.y))
class Obstacle:
    def __init__(self,image,type):
        self.image = image
        self.type = type
        self.rect = self.image[self.type].get_rect()
        self.rect.x = SCREEN_WIDTH

    def update(self):
        self.rect.x -= game_speed
        if self.rect.x < -self.rect.width:
            obstacles.pop()

    def draw(self,SCREEN):
        SCREEN.blit(self.image[self.type],self.rect)


class Box(Obstacle):
    def __init__(self,image):
        self.type = random.randint(0,2)
        super().__init__(image,self.type)
        self.rect.y = 380


class Tree(Obstacle):
    def __init__(self,self.type)
        self.rect.y = 325


class Shadow(Obstacle):
    def __init__(self,image):
        self.type = 0
        super().__init__(image,self.type)
        self.rect.y = 390
        self.index = 0


    def draw(self,SCREEN):
        if self.index >= 9:
            self.index = 0
        SCREEN.blit(self.image[self.index//5],self.rect)
        self.index += 1

class Drug(Obstacle):
    def __init__(self,self.type)
        self.rect.y = 325


class Portal(Obstacle):
    def __init__(self,self.type)
        self.rect.y = 300
class Reseta(Obstacle):
    def __init__(self,self.type)
        self.rect.y = 350
def main():
    global game_speed,x_pos_bg,y_pos_bg,points,obstacles
    run = True
    clock = pygame.time.Clock()
    player = Boy()
    # cloud = Cloud()
    game_speed = 10
    x_pos_bg = 0
    y_pos_bg = 0
    points = 0
    font = pygame.font.Font('freesansbold.ttf',20)
obstacles = []
death_count = 0
def score():
    global points,game_speed
    points += 1
    if points % 500 == 0:
        game_speed += 1
    text = font.render("Points: " + str(points),True,(0,0))
    textRect = text.get_rect()
    textRect.center = (850,30)
    SCREEN.blit(text,textRect)
def background():
    global x_pos_bg,y_pos_bg
    image_width = BG.get_width()
    SCREEN.blit(BG,(x_pos_bg,y_pos_bg))
    SCREEN.blit(BG,(image_width + x_pos_bg,y_pos_bg))
    if x_pos_bg <= -image_width:
        SCREEN.blit(BG,y_pos_bg))
        x_pos_bg = 0
    x_pos_bg -= game_speed
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    SCREEN.fill((255,255,255))
    userInput = pygame.key.get_pressed()


    background()
    player.draw(SCREEN)
    player.update(userInput)

    if len(obstacles) == 0:
        if random.randint(0,2) == 0:
            obstacles.append(Box(Box))
        elif random.randint(0,2) == 1:
            obstacles.append(Tree(TREE))
        elif random.randint(0,2) == 2:
            obstacles.append(Shadow(SHADOW))
        elif random.randint(0,2) == 0:
            obstacles.append(Portal(PORTAL))
        elif random.randint(0,2) == 0:
            obstacles.append(Reseta(RESETA))
        elif random.randint(0,2) == 0:
            obstacles.append(Drug(DRUG))

    for obstacle in obstacles:
        obstacle.draw(SCREEN)
        obstacle.update()
        if player.boy_rect.colliderect(obstacle.rect):
            pygame.time.delay(2000)
            death_count += 1
            menu(death_count)
    score()

    clock.tick(30)
    pygame.display.update()
def menu(death_count):
global points
run = True
while run:
    # SCREEN.fill((255,255))
    SCREEN.blit(BG,0))
    font = pygame.font.Font('freesansbold.ttf',30)

    if death_count == 0:
        text = font.render("Press any Key to Start",(250,245,225))
        save = font.render("score 1000 to save the Girl",225))
        saveRect = save.get_rect()
        saveRect.center = (SCREEN_WIDTH // 2,SCREEN_HEIGHT // 2 + 50)
        SCREEN.blit(save,saveRect)
    elif death_count > 0:
        text = font.render("Press any Key to Restart",225))
        score = font.render("Your score: " + str(points),225))
        scoreRect = score.get_rect()
        scoreRect.center = (SCREEN_WIDTH // 2,SCREEN_HEIGHT // 2 + 50)
        SCREEN.blit(score,scoreRect)
    textRect = text.get_rect()
        textRect.center = (SCREEN_WIDTH // 2,SCREEN_HEIGHT // 2)
        SCREEN.blit(text,textRect)

        SCREEN.blit(STANDING,(SCREEN_WIDTH // 2 - 20,SCREEN_HEIGHT // 2 - 140))
        pygame.display.update()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
            if event.type == pygame.KEYDOWN:
                main()
menu(death_count=0)

下面是我的游戏中使用的图像文件夹的文件https://drive.google.com/file/d/1t_kDNw3G1Q6X4KKZ9IfsCmYKpEecz9Ci/view?usp=sharing

解决方法

我为您创建了一个小例子。您唯一需要记住的是我的类 Game 中包含的方法 main_loop() 的用途(注释将帮助您理解它)。请记住,您添加了多个 while 循环,这些循环取决于您将要更改的变量以更改游戏状态。每个循环根据其目标打印出不同的内容。

对于要到达的点,只需创建一个不可见的 rect 并检查您的播放器 rect 是否与不可见的 rect 碰撞。如果是,请切换变量以进入另一个循环,该循环将打印出游戏以外的其他内容(在这种情况下,您可以打印出“您赢了”。

对于分数,您可以在玩家每次做某事时添加分数,并检查每一帧分数是否超过您设置的获胜分数。在这种情况下,只需切换变量即可更改游戏状态。

import pygame

# creating screen
screen = pygame.display.set_mode((1000,500))


class Player(pygame.sprite.Sprite):

    """Defining a little class just to show the player on the screen"""

    def __init__(self):
        # initialize super class (pygame.sprite.Sprite)
        super().__init__()

        # defining rect of the player
        self.rect = pygame.Rect((100,100),(100,100))
        self.color = (255,0)

    def move_right(self):

        self.rect.x += 20

    def show_player(self):

        pygame.draw.rect(screen,self.color,self.rect)


class Game:

    """Defining the game class that contains the main loop and main variables"""

    def __init__(self):

        # defining variables for game loops
        self.running = True
        self.end_menu = False
        self.game = True

        # initialising player class
        self.pl = Player()

        # creating an invisible rect that the player has to reach
        self.reach_point = pygame.Rect((500,100))

    def main_loop(self):
        
        """The goal here is to create several loops. One will be for the main game loop that will contains 
        the two other loops (as many as you want),when an event you chose will happens,the variable that makes
        the loop run will turn on false and the variable that makes the loop of the other stage you want to reach
        will turn on true. So you will constantly run a loop because your main loop will end up only if you quit the
        game."""
        
        while self.running:

            while self.game:

                for event in pygame.event.get():

                    if event.type == pygame.QUIT:
                        self.running = False
                        self.game = False

                    if event.type == pygame.KEYDOWN:

                        # defining just a key for the example
                        if event.key == pygame.K_d:
                            self.pl.move_right()

                # detecting if the player reach the invisible rect
                if self.pl.rect.colliderect(self.reach_point):
                    self.game = False
                    self.end_menu = True

                # fill the screen in white
                screen.fill((255,255,255))

                # shows the player
                self.pl.show_player()

                # update the screen
                pygame.display.flip()

            while self.end_menu:

                for event in pygame.event.get():

                    if event.type == pygame.QUIT:
                        self.running = False
                        self.end_menu = False

                    if event.type == pygame.KEYDOWN:

                        if event.key == pygame.K_p:

                            self.game = True
                            self.end_menu = False

                # fills the screen in order to see the different states of the game
                screen.fill((255,0))

                # update the screen
                pygame.display.flip()


# initializing the class game
game = Game()

pygame.init()

# calling function `main_loop()` contained in the class Game (initialised as game)
game.main_loop()

pygame.quit()

,

当分数达到 200 时,有一种非常简单的方法可以让您在游戏中显示“You Win”。您需要一个变量来表示每次发生某些事情时都会增加的分数。首先,您必须通过执行 pygame.image.load(file name.png) 为“You Win”加载图像,然后您必须为图像的 x 轴和 y 轴分配变量(我使用 You_WinX 和 You_WinY 作为示例) 那么你可以简单地这样做:

if score == 2000:
     You_WinX = (location on x-axis)
     You_WinY = (location in y-axis)

这会做的是当分数达到 2000 的值时,“You Win”的图像将出现在屏幕上您想要的位置 (x,y)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。