Pygame:如何在用户按下ENTER键后捕捉用户输入



我正在制作一个基于文本的RPG,作为我的第一个python/pygame项目。在我的游戏中,我想向玩家提供选择,然后让他们输入。我可以下载并导入一个接受用户输入并在屏幕上显示的模块。然而,在将其用于类似。。比方说,如果用户输入是"是",那么他们进入一个新的区域,我希望程序只在用户按下回车键时接受用户输入。我相信我下载的文本输入模块的教程中有这样做的说明,但老实说,我只是不明白它在说什么。我尝试过多种类型的循环,但都没有成功。任何帮助都将不胜感激。这是我的主要游戏代码:

import pygame_textinput
import pygame
pygame.init()
#fps
clock=pygame.time.Clock()
# create font here
font_name = pygame.font.get_default_font()
WHITE_TEXT_COLOR = (255, 255, 255)
# create screen and window and display and font here
screen_width, screen_height = 800, 700
background_color_black = (0, 0, 0)
screen = pygame.display.set_mode((screen_width, screen_height))
our_game_display = pygame.Surface((screen_width, screen_height))
pygame.display.set_caption('MyRPGGame')
#create text input object
textinput = pygame_textinput.TextInput()



def draw_text(text, size, x, y):
pygame.font.init()
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, WHITE_TEXT_COLOR)
text_rect = text_surface.get_rect()
text_rect.center = (x, y)
our_game_display.blit(text_surface, text_rect)

def choose_to_play():
draw_text("You've decided to play",20,screen_width/2,screen_height/2+50)
def first_area():
our_game_display.fill(background_color_black)
draw_text('The story of this game depends on your choices. Do you wish to play?', 20, screen_width / 2,screen_height / 2 - 100)
draw_text('Type your answer and hit enter.', 20, screen_width / 2,screen_height / 2 - 50)
draw_text('Yes', 20, screen_width/2,screen_height/2+50)
draw_text('No', 20, screen_width/2,screen_height/2+100)

screen.blit(our_game_display, (0, 0))
pygame.display.update()

while True:
our_game_display.fill((background_color_black))
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
exit()
first_area()
# Feed it with events every frame
textinput.update(events)

# Blit its surface onto the screen
screen.blit(textinput.get_surface(), (10, 600))
pygame.display.update()
clock.tick(30)

现在这里是pygame文本输入模块的来源,我想我会链接到代码,这样这篇文章就不会太拥挤:https://github.com/Nearoo/pygame-text-input

您需要一个用于游戏状态的变量。按下回车键后,更改状态。根据游戏状态在应用程序循环中实现不同的情况::

game_state = 'start'
while True:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
game_state = 'input'
our_game_display.fill((background_color_black))
if game_state == 'input':
textinput.update(events)
# [...]

最新更新