一个月前我开始使用 Pygame,我的第一款游戏在高分表和玩家姓名输入框中运行良好。我的问题是当玩家输入他们的名字时让 shift 键工作。我没有弄乱我的游戏,而是创建了一个小型测试程序。每当我按下任何修饰键或键盘时,我都会收到错误“文件“C:\PythonProjects\NameBox\namebox.py”,第 61 行,询问 current_string += chr(inkey) ValueError: chr() arg not in range( 256)"
任何人都可以帮我完成这项工作。我已经尝试了很多我在网上找到的建议,但无法让它们中的任何一个起作用。也许有更好的方法来做到这一点,但至少这给了我一个名字(所有都是小写),并将它与分数和日期一起输入到正确位置的高分表中。
这是我的测试程序。希望我正确输入了代码。
import pygame, sys, os
os.environ['SDL_VIDEO_CENTERED'] = '1' # centers Pygame SCREEN on desktop
from pygame.locals import *
pygame.font.init()
SCREENWIDTH = 640
SCREENHEIGHT = 480
SCREEN = pygame.display.set_mode((SCREENWIDTH+9, SCREENHEIGHT+9))
BASICFONT = pygame.font.Font('freesansbold.ttf', 18, bold = False, italic=False)
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
GREEN = ( 0, 255, 0)
DARKGREEN = ( 0, 128, 0)
def main():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
elif event.type == KEYDOWN:
if event.key == pygame.K_ESCAPE:
terminate()
elif event.key == pygame.K_n:
getname()
spaceSurf = BASICFONT.render('Press n to enter name', False, WHITE)
spaceRect = spaceSurf.get_rect()
spaceRect.midtop = (SCREENWIDTH / 2, SCREENHEIGHT - 30)
SCREEN.blit(spaceSurf, spaceRect)
pygame.display.update()
def getname():
name = ask("Your name")
SCREEN.fill(BLACK)
nSurf = BASICFONT.render('Press n to enter name', False, WHITE)
nRect = nSurf.get_rect()
nRect.midtop = (SCREENWIDTH / 2, SCREENHEIGHT - 30)
SCREEN.blit(nSurf, nRect)
nameSurf = BASICFONT.render('Your name is '+ name, True, WHITE)
nameRect = nameSurf.get_rect()
nameRect.midtop = (SCREENWIDTH / 2, SCREENHEIGHT / 2)
SCREEN.blit(nameSurf, nameRect)
pygame.display.update()
def ask(question):
"ask(question) -> answer"
current_string = ""
display_box(question + ": " + current_string)
while 1:
inkey = get_key()
if inkey == K_BACKSPACE:
current_string -= 1
elif inkey == K_RETURN or inkey == K_KP_ENTER:
break
elif inkey == pygame.K_ESCAPE:
terminate()
else:
current_string += chr(inkey)
display_box(question + ": " + current_string.capitalize())
return current_string.capitalize() # this is the answer
def get_key():
while 1:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
return event.key
else:
pass
def display_box(message):
"Print a message in a box in the middle of the screen"
SCREEN.fill(BLACK)
left = (SCREENWIDTH / 2) - 156
top = (SCREENHEIGHT / 2) -100
pygame.draw.rect(SCREEN, DARKGREEN, (left, top, 320, 200))
SCREEN.blit(BASICFONT.render("New High Score!", True, GREEN),(left + 90, top + 35))
SCREEN.blit(BASICFONT.render("Press Enter when done.", True, GREEN),
(left + 51, top + 160))
pygame.draw.rect(SCREEN, BLACK, (left + 39, top + 110, 240, 20))
pygame.draw.rect(SCREEN, WHITE, (left + 38, top + 108, 244, 24), 1)
if len(message) != 0:
SCREEN.blit(BASICFONT.render(message, True, WHITE), (left+42, top + 111))
pygame.display.update()
def terminate():
pygame.quit()
sys.exit()
if __name__ == '__main__':
main()