【问题标题】:Pygame: Limit Name to 3 or 4 LettersPygame:将名称限制为 3 或 4 个字母
【发布时间】:2013-12-30 12:30:52
【问题描述】:

我正在为我正在创建并正在添加分数的游戏学习 pygame 中的文本输入。我已经学会了如何将文本写入文件,然后读取并在屏幕上显示文本。现在我正在尝试学习如何将名称限制为 3 或 4 个字符,以便分数整齐排列。目前玩家可以随意输入名字。例如,他们可以做 ABC,但我只需要 3 或 4 个字符。这是我正在处理的代码:

import pygame, random
from pygame.locals import *

FONT_SIZE = 60

def name():

    screen = pygame.display.set_mode((1280, 720))
    name = ""
    lol = random.randint(0, 100)
    font = pygame.font.SysFont(None, FONT_SIZE)

    while True:
        #  readlines returns a list; having this in
        #  loop allows pygame to draw recently added
        #  string; no need to close and open a window
        namefile = open('test.txt', 'r')
        names = namefile.readlines()

        for event in pygame.event.get():
            if event.type == KEYDOWN:
                if event.unicode.isalpha():
                    if event.unicode == 3:
                        name += 0
                    else:
                        name += event.unicode
                elif event.key == K_BACKSPACE:
                    name = name[:-1]
                elif event.key == K_RETURN:
                    f = open("test.txt", "a")
                    f.write(str(name) + " " + str(lol) + "\n")
                    f.close()
                    name = ""
            elif event.type == QUIT:
                return

        #  create a Rectangle container, where yours
        #  text variable will be drawn
        #  Rect(left, top, width, height)
        textrect = Rect(0, 0, 100, FONT_SIZE)
        screen.fill((0, 0, 0))
        for i in names:
            #  iterate through lines from text file (it is stored
            #  in names variable and it is a list)

            #  create text variable and draw it to textrect
            text = font.render(i[:-1], True, (255,0,0), (0,0,0))
            screen.blit(text, textrect)
            #  change y coordinate of textrect; in next iteration
            #  next line will appear below the previous line
            textrect.centery += FONT_SIZE

        block = font.render(name, True, (255, 255, 255))
        rect = block.get_rect()
        rect.center = screen.get_rect().center
        screen.blit(block, rect)
        pygame.display.update()
        pygame.display.flip()

if __name__ == "__main__":
    pygame.init()
    name()
    pygame.quit()

以下是我所追求的示例:

【问题讨论】:

  • 统计变量名的字母,如果长度超过3个字符,只写名称[0:2]。

标签: python python-2.7 pygame


【解决方案1】:

你可以这样做

if event.unicode.isalpha():
    if len(name) < 3:
        if event.unicode == 3:
            name += 0
        else:
            name += event.unicode

这样,你只在名字不长的时候添加一个字符

【讨论】:

  • 让我现在试试这个:)
猜你喜欢
  • 2016-08-27
  • 1970-01-01
  • 2013-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 2019-10-14
相关资源
最近更新 更多