Introduction
We know that the gaming industry is one of the major developing industries in the current world using current developing technologies. And on the parallel side, Python is also one of the famous programming languages which are stretching its hands in all the fields due to its simplicity and a full-fledged pack of libraries. Gaming is really a fun way of learning things. Game programming also includes many concepts such as math, computer programming, logic development, and many more. In the current developing technology, AI is also showing some support for game programming. Python can be used for Game Programming by using the Pygame library. Pygame library is one of the python programming libraries which has very efficient functionalities such as building custom events, taking input from the user through the keyboard, creating custom input boxes for taking inputs, etc. You can learn how to add custom events and get keyboard input in pygame using this link and this link. This article will try to discuss how to create an input box in our pygame application. Hope You will enjoy the article!
Creating the input box in Pygame
Steps:
- First, install all the necessary packages and call pygame.init() to initialize all the imported modules.
- Set the size of the screen using pygame.display.set_mode().
- Set the font of the text if you are willing to do so by using pygame.font.Font().
- You can add color to the input box when the box is clicked by the user - by using pygame.Color() method.
- Create a string variable to store the user text to be displayed.
- For taking the input text, we need to draw a rectangle, and we need to pass an argument that should be displayed on the screen.
Example:
import pygame
import sys
pygame.init()
display = pygame.display.set_mode([700, 600])
font_size = pygame.font.Font(None, 45)
usr_txt = ‘ ‘
usr_inp_rect = pygame.Rect(400, 400, 320, 50)
color = pygame.Color(‘chartreuse4’)
active = True
while True:
for event in pygame.event.get():
# if the user types QUIT then the screen will close
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
# Check for backspace
if event.key == pygame.K_BACKSPACE:
usr_txt = usr_txt[:-1]
else:
usr_txt += event.unicode
# draw rectangle and the argument passed which should be on-screen
pygame.draw.rect(display, color, usr_inp_rect)
txt_surface = base_font.render(usr_inp_rect , True, (255, 255, 255))
# render at position stated in arguments
display.blit(txt_surface, (usr_inp_rect.x+5, usr_inp_rect.y+5))
# set the width of textfield so that text cannot get outside of user's text input
usr_inp_rect.w = max(100, txt_surface.get_width()+10)
# display.flip() will try to update only a portion of the screen to updated, not full area
pygame.display.flip()
Here is another sample link.