2016-04-25 19 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或什麼,看看是否真或假。

相關問題