gpt4 book ai didi

python - Pygame 中的屏幕输入

转载 作者:太空宇宙 更新时间:2023-11-04 04:59:14 26 4
gpt4 key购买 nike

对于学校的一个编程项目,我必须使用 pygame 创建一个拼写游戏。但是,由于我对这整件事还很陌生,所以我无法弄清楚如何让用户输入字母并使它们出现在游戏显示屏上。到目前为止,这是我的代码(以及我尝试解决此问题的失败尝试):

import pygame
import random

pygame.init()

display_width = 800
display_height = 600

black = (0,0,0)
white = (255,255,255)
red = (255,0,0)

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Spelling Game")
myfont = pygame.font.SysFont("Arial", 50)
clock = pygame.time.Clock()
mouse = pygame.mouse.get_pos()

city = pygame.image.load("city.png")

charac_str = "" #new string to store written character
# font object to render str to surface
font_renderer = pygame.font.SysFont("Arial",30)

def background(x,y):
gameDisplay.blit(city,(-200,-100))

with open("words.txt") as f:
WORDS = f.read().split()

def random_word():
return random.choice(WORDS)


gameExit = False
word = random_word()

while not gameExit:
#event-handling loop based on user input
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()

gameDisplay.fill(white)

background(0,0)
textsurface = myfont.render(word, True, red)
gameDisplay.blit(textsurface, (340, 400)) #the random word

rendered_charac = font_renderer.render(charac_str, True, red)
gameDisplay.blit(rendered_charac, (100,100))

pygame.display.update()

for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if pygame.K_0 < event.key < pygame.K_9: #checks key pressed
character = chr(event.key) #conv num to char
charac_str += str(character) # add num to end of string
gameDisplay.blit(charac_str) # display the input?doesn't work

最佳答案

pygame.KEYDOWN 事件有一个 unicode 属性,您可以简单地将其添加到字符串中,例如text += event.unicode。然后在主循环中渲染并显示文本。

import pygame as pg


def main():
screen = pg.display.set_mode((640, 480))
font = pg.font.Font(None, 32)
clock = pg.time.Clock()
color = pg.Color('dodgerblue2')
text = ''

while True:
for event in pg.event.get():
if event.type == pg.QUIT:
return
elif event.type == pg.KEYDOWN:
if event.key == pg.K_RETURN:
print(text)
text = ''
elif event.key == pg.K_BACKSPACE:
text = text[:-1]
else:
text += event.unicode

screen.fill((30, 30, 30))
txt_surface = font.render(text, True, color)
screen.blit(txt_surface, (50, 100))

pg.display.flip()
clock.tick(30)


if __name__ == '__main__':
pg.init()
main()
pg.quit()

关于python - Pygame 中的屏幕输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46252905/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com