Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在屏幕上显示文字来结束游戏?_Python_Pygame - Fatal编程技术网

Python 如何在屏幕上显示文字来结束游戏?

Python 如何在屏幕上显示文字来结束游戏?,python,pygame,Python,Pygame,对于我的选择题程序,当用户的生命耗尽时,屏幕上会弹出“游戏结束”的文本。然而,当我添加这个选项时,多项选择选项仍然保留在屏幕上,并且它们仍然可以继续游戏。如果继续,则“游戏结束”文本会突然消失 下面是我的代码的相关部分的片段: def update(self, events, dt): for event in events: if event.type == pygame.MOUSEBUTTONDOWN: n =

对于我的选择题程序,当用户的生命耗尽时,屏幕上会弹出“游戏结束”的文本。然而,当我添加这个选项时,多项选择选项仍然保留在屏幕上,并且它们仍然可以继续游戏。如果继续,则“游戏结束”文本会突然消失

下面是我的代码的相关部分的片段:

    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()

是否有一种方式,当生命耗尽时,游戏将完全停止,但“游戏结束”文本将保留在屏幕上?谢谢。

如果我正确理解了您的需求,我相信此代码将帮助您:

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()

我已经修改了
游戏场景
类。在
update
方法中调用了
quit()
。该呼叫将完全关闭应用程序。因此,我添加了一个新的场景,即
quitsecene
,它通过屏幕上的文本显示游戏,单击后,应用程序关闭。如果您不想关闭它,我已经添加了一条注释,指出您必须在何处修改代码以更改该行为。

在所有问题都正确后应该怎么办?因为您可以在
返回('QUIT',self.gamestate)
之前,使用要显示的文本向
游戏状态添加一个新变量。然后您可以在这里使用该变量
game\u over\u surf=font100.render(“game over”,True,(0,0,0))
而不是“game over”字符串。类似于
game\u over\u surf=font100.render(self.gamestate.finaltext,True,(0,0,0))
您可以执行如下操作:
if self.gamestate.questions和self.gamestate.lifes>0:return('game',self.gamestate)elf self.gamestate==0:return('QUIT',self gamestate.gamestate)
抱歉设置了格式。该代码的唯一问题是,您仍然需要处理用户获胜时发生的情况。我将使用该代码编辑我的答案代码。完成。我运行了你编辑过的代码版本,但仍然不起作用。查看问题的更新版本以查看图像。理想情况下,如果寿命超过零,我在屏幕上什么也不找。程序有可能在第三个问题之后结束吗?考虑到他们有超过零的生命?如果用户赢了,我可以使用它。