【问题标题】:How can you end your game with text on the screen?你怎么能用屏幕上的文字结束你的游戏?
【发布时间】:2021-01-22 20:52:18
【问题描述】:

对于我的多项选择程序,当用户用完生命时,屏幕上会弹出文本“游戏结束”。但是,当我添加此选项时,多项选择选项仍会与问题一起显示在屏幕上,并且它们仍然可以继续进行游戏。如果他们继续,“游戏结束”文本会突然消失。

下面是我的代码相关部分的sn-p:

    def update(self, events, dt):
        for event in events:
            if event.type == pygame.MOUSEBUTTONDOWN:
                n = 1
                for rect in self.rects:
                    if rect.collidepoint(event.pos):
                        self.gamestate.answer(n)
                        if self.gamestate.questions:
                            return ('GAME', self.gamestate)
                        else:
                            quit()
                    n += 1



class QuitScene:
    def __init__(self):
        if SimpleScene.FONT == None:
            SimpleScene.FONT = pygame.freetype.SysFont(None, 32)

    def start(self, gamestate):
        self.background = pygame.Surface((1275, 775))
        self.background.fill(pygame.Color('white'))
        self.gamestate = gamestate

    def draw(self, screen):
        screen.blit(self.background, (0, 0))
        game_over_surf = font100.render("Game Over", True, (0, 0, 0))
        screen.blit(game_over_surf, game_over_surf.get_rect(center=screen.get_rect().center))

    def update(self, events, dt):
        for event in events:
            if event.type == pygame.MOUSEBUTTONDOWN:
                quit()
            if self.gamestate.questions and self.gamestate.lives > 0:
                            return ('GAME', self.gamestate)
            elif self.gamestate.lives == 0:
                        return ('QUIT',)
            n += 1


def main():
    pygame.init()
    screen = pygame.display.set_mode((1275, 775))
    clock = pygame.time.Clock()
    dt = 0

    scenes = {
        'TITLE': SimpleScene('SETTING', 'You have chosen category 1: Introduction to Programming ', '', '', '', 'press [SPACE] to start'),
        'SETTING': SettingScene(),
        'GAME': GameScene(),
        'QUIT': QuitScene(),
    }
    scene = scenes['TITLE']
    while True:
        events = pygame.event.get()
        for e in events:
            if e.type == pygame.QUIT:
                return

        game = scene.update(events, dt)
        if game:
            next_scene, state = game
            if next_scene:
                scene = scenes[next_scene]
                scene.start(state)


        scene.draw(screen)

        pygame.display.flip()
        dt = clock.tick(60)


if __name__ == '__main__':
    main()

有没有一种方法可以让游戏在生命耗尽时完全停止,但“游戏结束”文本会留在屏幕上?谢谢。

【问题讨论】:

    标签: python pygame


    【解决方案1】:

    如果我正确理解你想要什么,我相信这段代码会对你有所帮助:

    import pygame
    pygame.init()
    import pygame.freetype
    import random
    
    X = 1275
    Y = 775
    green = (50, 205, 50)
    blue = (0, 0, 205)
    screen = pygame.display.set_mode((X,Y))
    font100 = pygame.font.SysFont(None, 100)
    
    Heart = pygame.image.load("C:/Users/Davina/Documents/Python/Testing/Hearts.png")
    Heart1 = pygame.image.load("C:/Users/Davina/Documents/Python/Testing/Hearts.png")
    Heart2 = pygame.image.load("C:/Users/Davina/Documents/Python/Testing/Hearts.png")
    
    
    
    class SimpleScene:
        FONT = None
    
        def __init__(self, next_scene, *text):
            self.background = pygame.Surface((1275, 775))
            self.background.fill(pygame.Color('white'))
    
            y = 200
            if text:
                if SimpleScene.FONT == None:
                    SimpleScene.FONT = pygame.freetype.SysFont(None, 32)
                for line in text:
                    SimpleScene.FONT.render_to(self.background, (220, y), line, pygame.Color('black'))
                    SimpleScene.FONT.render_to(self.background, (220, y - 1), line, pygame.Color('black'))
                    y += 50
    
            self.next_scene = next_scene
            self.additional_text = None
    
        def start(self, text):
            self.additional_text = text
    
        def draw(self, screen):
            screen.blit(self.background, (0, 0))
            if self.additional_text:
                y = 180
                for line in self.additional_text:
                    SimpleScene.FONT.render_to(screen, (120, y), line, pygame.Color('black'))
                    SimpleScene.FONT.render_to(screen, (119, y - 1), line, pygame.Color('white'))
                    y += 50
    
        def update(self, events, dt):
            for event in events:
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        return (self.next_scene, None)
    
    
    class GameState:
        def __init__(self, difficulty):
            self.difficulty = difficulty
    
            self.lives = 3
    
            # CHANGE
            self.questions = [
                ("Q1: Choose the correct symbol. 4 __ 6 = 10 ?"),
                ("Q2: Variables store data. Choose the appropriate variable. ______ = 1"),
                ("Q3: What should be the output?    Number = 1    Total = Number * 3    print(Total)")
                             ]
            self.answers = [4, 1, 2]
            self.current_question = None
    
            # CHANGE
            self.question_index = 0
    
    
        def pop_question(self):
            q = self.questions[0]
            self.current_question = q
            return q
    
    
        def answer(self, answer):
            if answer != self.answers[self.question_index]:
                self.lives -= 1
            else:
                self.question_index += 1
                self.questions.pop(0)
    
    class SettingScene:
    
        def __init__(self):
            self.background = pygame.Surface((1275, 775))
            self.background.fill(pygame.Color('white'))
    
            if SimpleScene.FONT == None:
                SimpleScene.FONT = pygame.freetype.SysFont(None, 32)
    
            SimpleScene.FONT.render_to(self.background, (120, 50), 'Select your difficulty level', pygame.Color('black'))
            SimpleScene.FONT.render_to(self.background, (119, 49), 'Select your difficulty level', pygame.Color('black'))
    
            self.rects = []
    
            # CHANGE
            for n in range(4):
                rect = pygame.Rect(50, (n * 70) + 100, 500, 50)
                self.rects.append(rect)
    
        def start(self, *args):
            pass
    
        def draw(self, screen):
            screen.blit(self.background, (0, 0))
            n = 1
            for rect in self.rects:
                if rect.collidepoint(pygame.mouse.get_pos()):
                    pygame.draw.rect(screen, pygame.Color('darkgrey'), rect)
                pygame.draw.rect(screen, pygame.Color('darkgrey'), rect, 5)
    
                # CHANGE
                SimpleScene.FONT.render_to(screen, (rect.x + 30, rect.y + 15), str(n), pygame.Color('black'))
                SimpleScene.FONT.render_to(screen, (rect.x + 29, rect.y + 14), str(n), pygame.Color('black'))
    
                n += 1
    
        def update(self, events, dt):
            for event in events:
                if event.type == pygame.MOUSEBUTTONDOWN:
                    n = 1
                    for rect in self.rects:
                        if rect.collidepoint(event.pos):
                            return ('GAME', GameState(n))
                        n += 1
    
    class GameScene:
        def __init__(self):
            if SimpleScene.FONT == None:
                SimpleScene.FONT = pygame.freetype.SysFont(None, 32)
    
            self.rects = []
    
            for n in range(4):
                rect = pygame.Rect(420, (n * 70) + 300, 500, 50)
                self.rects.append(rect)
    
            # CHANGE
            self.choices = [['x', '-', '*', '+'], ["number", "fruit", "weather", "letter"], ["4", "3", "-2", "13"]]
    
        def start(self, gamestate):
            self.background = pygame.Surface((1275, 775))
            self.background.fill(pygame.Color('white'))
            self.gamestate = gamestate
            question = gamestate.pop_question()
            SimpleScene.FONT.render_to(self.background, (20, 150), question, (blue))
    
        def draw(self, screen):
            screen.blit(self.background, (0, 0))
    
            if self.gamestate.lives >= 1:
                screen.blit(Heart, (500, 10))
            if self.gamestate.lives >= 2:
                screen.blit(Heart1, (X // 2, 10))
            if self.gamestate.lives >= 3:
                screen.blit(Heart2, (775, 10))
            if self.gamestate.lives == 0:
                game_over_surf = font100.render("Game Over", True, (0, 0, 0))
                screen.blit(game_over_surf, game_over_surf.get_rect(center=screen.get_rect().center))
    
    
    
            n = 0
            for rect in self.rects:
                if rect.collidepoint(pygame.mouse.get_pos()):
                    pygame.draw.rect(screen, pygame.Color('darkgrey'), rect)
                pygame.draw.rect(screen, pygame.Color('darkgrey'),
                                 rect, 5)
    
                # CHANGE
                for i in range(len(self.choices)):
                    if self.gamestate.question_index == i:
                        SimpleScene.FONT.render_to(screen, (rect.x + 30, rect.y + 20), str(self.choices[i][n]),
                                                   (green))
                        SimpleScene.FONT.render_to(screen, (rect.x + 29, rect.y + 19), str(self.choices[i][n]),
                                                   (green))
                n += 1
    
        def update(self, events, dt):
            for event in events:
                if event.type == pygame.MOUSEBUTTONDOWN:
                    n = 1
                    for rect in self.rects:
                        if rect.collidepoint(event.pos):
                            self.gamestate.answer(n)
                            if self.gamestate.questions and self.gamestate.lives > 0:
                                return ('GAME', self.gamestate)
                        elif self.gamestate.lives == 0:
                            return ('QUIT', self.gamestate)
                        else:
                            quit() # Here the program ends after the third question is answered correctly and you have more than 0 lives
                        n += 1
    
    class QuitScene:
        def __init__(self):
            if SimpleScene.FONT == None:
                SimpleScene.FONT = pygame.freetype.SysFont(None, 32)
    
        def start(self, gamestate):
            self.background = pygame.Surface((1275, 775))
            self.background.fill(pygame.Color('white'))
            self.gamestate = gamestate
    
        def draw(self, screen):
            screen.blit(self.background, (0, 0))
            game_over_surf = font100.render("Game Over", True, (0, 0, 0))
            screen.blit(game_over_surf, game_over_surf.get_rect(center=screen.get_rect().center))
    
        def update(self, events, dt):
            for event in events:
                if event.type == pygame.MOUSEBUTTONDOWN:
                    quit() # You have to add another behaviour here if you want to avoid closing the app after mouse button down
    
    
    
    def main():
        pygame.init()
        screen = pygame.display.set_mode((1275, 775))
        clock = pygame.time.Clock()
        dt = 0
    
        scenes = {
            'TITLE': SimpleScene('SETTING', 'You have chosen category 1: Introduction to Programming ', '', '', '', 'press [SPACE] to start'),
            'SETTING': SettingScene(),
            'GAME': GameScene(),
            'QUIT': QuitScene(),
        }
        scene = scenes['TITLE']
        while True:
            events = pygame.event.get()
            for e in events:
                if e.type == pygame.QUIT:
                    return
    
            game = scene.update(events, dt)
            if game:
                next_scene, state = game
                if next_scene:
                    scene = scenes[next_scene]
                    scene.start(state)
    
    
    
            scene.draw(screen)
    
            pygame.display.flip()
            dt = clock.tick(60)
    
    
    if __name__ == '__main__':
        main()
    

    我修改了GameScene 类。在update 方法中调用了quit()。该调用将完全关闭应用程序。所以我添加了一个新场景,即QuitScene,它在屏幕上显示 Game Over 文本,点击后,应用程序关闭。如果您不想关闭它,我添加了一条注释,指出您必须在哪里修改代码才能更改该行为。

    【讨论】:

    • 所有问题都正确后会发生什么?因为您可以在gamestate 中添加一个新变量,其中包含要显示的文本,就在return ('QUIT', self.gamestate) 之前。然后你可以在这里使用该变量game_over_surf = font100.render("Game Over", True, (0, 0, 0)) 而不是“Game Over”字符串。类似于game_over_surf = font100.render(self.gamestate.finaltext, True, (0, 0, 0))
    • 您可以执行以下操作:if self.gamestate.questions and self.gamestate.lives > 0: return ('GAME', self.gamestate) elif self.gamestate.lives == 0: return ('QUIT', self.gamestate) 抱歉格式化。该代码的唯一问题是您仍然需要处理用户获胜时发生的事情。
    • 我将使用该代码编辑我的答案代码。完成。
    • 我运行了您编辑的代码版本,但仍然无法正常工作。检查我的问题的更新版本以查看图像。理想情况下,如果生命值大于零,我不会在屏幕上寻找任何内容。
    • 第三个问题后程序是否可以结束?鉴于他们的生命不止零?如果用户获胜,我可以使用它。
    猜你喜欢
    • 2015-04-05
    • 2013-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多