Pygame对话系统

Pygame dialog system

我正在尝试在 pygame 中制作一个简单的对话系统。我有一个简单的对话框 class.

class Dialog:
    def __init__(self, npc, player):
        self.player = player
        self.npc = npc
        self.step = 0
        self.text_counter = 0
        self.text = ["Hi ",
                     "Hello",
                     "are you boss or something!?!",
                     "What!"]
        
    def update(self, key):

        if step and self.player.colliderect(self.npc):# if pressed key and if player hits npc
            self.step += 1 # skip to next text
        if self.step > len(self.text)-1:
            self.step = 0

    def draw(self, screen):
        
        draw_text(
                screen,
                self.text[self.step],
                50,
                (255, 0, 0),
                50,
                50
            )`

    merchant = Dialog(merchant,player)#call dialog class

    while True:
        merchant.update(space_key)
        merchant.draw(screen)

但它显示第一个文本时没有将鼠标悬停在字符上,我知道问题出在哪里但我找不到解决它的方法,我遇到这个问题是因为 self.step 自动为 0,你有什么解决办法吗?

可以这样做:

import pygame


pygame.init()
screen = pygame.display.set_mode((600, 500))
clock = pygame.time.Clock()

box = pygame.Rect(300, 200, 100, 100)
player = pygame.Rect(50, 50, 30, 30)

font = pygame.font.SysFont('Times New Roman', 50)
texts = ['Hi', 'Hello', 'Who are ye?', 'Someone']
text_renders = [font.render(text, True, (0, 0, 255)) for text in texts]
index = -1
space_released = True

while True:
    clock.tick(60)
    screen.fill((0, 0, 0))

    keys = pygame.key.get_pressed()
    if keys[pygame.K_a]:
        player.x -= 3
    if keys[pygame.K_d]:
        player.x += 3
    if keys[pygame.K_s]:
        player.y += 3
    if keys[pygame.K_w]:
        player.y -= 3

    pygame.draw.rect(screen, (0, 255, 0), box, width=2)
    pygame.draw.rect(screen, (255, 0, 0), player)

    if player.colliderect(box):
        if keys[pygame.K_SPACE] and space_released:
            space_released = False
            index = (index + 1) if (index + 1) != len(text_renders) else 0
        elif not keys[pygame.K_SPACE]:
            space_released = True
    else:
        index = -1

    if index != -1:
        screen.blit(text_renders[index], (0, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            exit()

    pygame.display.update()

你可以先把索引设为-1,如果索引在那个位置不显示文字,那么当你增加索引时它会从0开始,你还需要当你离开盒子时重置它,以便下次它从头开始(如果那是你需要的)