2016-04-25 52 views
-1

我在pygame中编写项目,现在正在编写Login部分。 我写了一个函数,打印一个字符到屏幕的特定位置,但它不起作用,我不知道为什么。我有用于在pygame中写入屏幕的功能,但它不起作用

这里我的代码:函数调用print_char_by_place(char,row,col),我在代码的最后使用它。

import pygame 
import os 




def if_button_pressed(left_col, right_col, high_row, low_row, mouse): 
    if mouse[0]>=left_col and mouse[0]<=right_col and mouse[1]>=high_row and   mouse[1]<=low_row: 
     return True 
    return False 

# get char that pressed in the keyboard and print it by place 
def print_char_by_place(char, row, col): 
    font = pygame.font.SysFont("monospace", 15) 
    label = font.render(char, 1, black) 
    screen.blit(label, (row, col)) 



pygame.init() 
screen = pygame.display.set_mode((700, 700)) 
done = True 
login = True 
user_name_p = False 
password_p = False 
username = "" 
password = "" 
row_u = 343 
col_u = 260 
while done: 
    img = pygame.image.load("LOGIN.png") 
    screen.blit(img,(0,0)) 
    for event in pygame.event.get(): 
     if event.type == pygame.MOUSEBUTTONUP: 
      mouse = pygame.mouse.get_pos() 
      if if_button_pressed(255,418,331,355,mouse):  # if the  username pressed 
       username_p = True 
       password_p = False 

      if if_button_pressed(255,418,382,403,mouse):  # if the password pressed 
       username_p = False 
       password_p = True 

      else: 
       user_name_p = False 
       password_p = False 

     if event.type == pygame.KEYDOWN: 
      if user_name_p: 
       char = str(event.key) 
       username+=char 
       print_char_by_place(char,row_u,col_u) 
       col_u+=2 



     if event.type == pygame.QUIT: 
      done = False 
    pygame.display.update() 

回答

1

你的问题是,用户输入的每个字符只能渲染一个帧。一旦下一个框架滚动,背景图像将被绘制在顶部,并且您再也不会看到它(如果您甚至能够首先注意到它)。

如果您希望文本保持可见状态,则需要不断绘制每一帧。可能你不想在按键检测代码中这样做,它已经有逻辑来扩展变量username。你应该添加一些其他的代码,将username渲染到屏幕上(而不仅仅是当按下按键时的帧)。

0
name="" 
if event.key>=97 and event.key<=122 and len(name)< 22 or event.key>=48 and event.key<=57 and len(name)< 22: 
    name += str(pygame.key.name(event.key)) 

您可以使用此代码读取每个按键并添加字符串。这个字符串可以转换为图像并打印到每个循环。如果您需要删除最后的字符,你根本就

if event.key == K_BACKSPACE: 
    name = name[:-1] 

的名字一旦完成,你可以比较这串与塔的实际USENAME或什么,看看是否真或假。