Reputation: 603
In my game that I came up with, I have to press the key corresponding to the letter falling. However, I do not know of a function, class, statement, etc. that can help me with this. So Python chooses a random letter from a list and I want to know if the player has pressed that key corresponding to it. If the player has, it will spawn another letter. Here is my code:
import pygame
import random
from pygame.locals import *
# Set the height and width of the screen
window_width = 700
window_height = 500
size = [window_width, window_height]
game_win = pygame.display.set_mode(size)
# Creating colors
white = (225, 225, 225)
black = (0, 0, 0)
gray = (100, 100, 100)
# Setting a font
pygame.font.init()
font = pygame.font.SysFont("consolas", 25)
large_font = pygame.font.SysFont("consolas", 80)
# Setting a window name
pygame.display.set_caption("Letters Game")
# Creating a messaging function
def message(sentence, color, x, y, font_type, display):
sentence = font_type.render(sentence, True, color)
display.blit(sentence, [x, y])
# Main function
def mainLoop():
# Creating a letter list
letters = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
random_letter = random.choice(letters)
# Initializing PyGame
pygame.init()
# variable to keep a loop going
done = False
y = 12
y_moved = 0
random_x = random.choice(list(range(50, 550)))
# Starting a loop
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
y_moved = 7
y += y_moved
game_win.fill(black)
message("Type the letter before it touches the line", white, 10, 10, font, game_win)
pygame.draw.rect(game_win, white, [0, 450, 700, 5])
message(random_letter, white, random_x, y, large_font, game_win)
clock = pygame.time.Clock()
clock.tick(25)
pygame.display.flip()
if __name__ == "__main__":
mainLoop()
Upvotes: 2
Views: 272
Reputation: 210890
Get the KEYDOWN
event and evaluate the .unicode
attribute of the event (see event). Note, since your characters are capital letters, you have to get the lower case character form random_letter
:
def mainLoop():
# [...]
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
y_moved = 7
if event.type == pygame.KEYDOWN:
if event.unicode == random_letter.lower():
print("correct")
# [...]
Upvotes: 3