I was just making a pygame Snake game, and I was trying to get the input from some keys to translate into moving my player charecter. It didn’t work. It worked earlier, when I was making another game using code mentioned here.(Using method 2)
It is not working for me now.
I am using VS Code on Windows 11, if that info helps.
My Python Version – 3.12.3
I expected the code would work normally, of course, but it didn’t show any errors and PyGame was definitely detecting my keys, but the player movement wasn’t happening. Please help. Thank you for any response.
My code:-
import pygame
from sys import exit
from random import randint
# boilerplate
pygame.init()
screen = pygame.display.set_mode((800,800))
pygame.display.set_caption('Sneky-Snek')
clock = pygame.time.Clock()
game_active = False
ph = 0
isMoving = False
#all graphics
font = pygame.font.SysFont("Comic_Sans_MS", 30)
snektext = font.render('Sneky-Snek',True,(255,255,255))
snekk = font.render('A simple Snake(esqe) Game',False,(255,255,255))
snekk_rect = snekk.get_rect(center = (400,250))
snektext_2x = pygame.transform.scale2x(snektext)
snektext_rect_2x = snektext_2x.get_rect(center = (400,200))
menutext = font.render('Press SPACE to Start',False,(255,255,255))
menutext_rect = menutext.get_rect(center = (400,650))
# boilerplate
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and game_active == False:
game_active = True
if event.key == pygame.K_RIGHT and isMoving == False:
isMoving = True
print('hi!')
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT and isMoving:
isMoving = False
print('bye!')
# display updates
if game_active:
screen.fill('Black')
snek = pygame.draw.rect(screen,(0,255,0),pygame.Rect(30,30,20,20))
if isMoving==True:
snek.x += 10
#x = randint(0,800)
#y = randint(0,800)
#pygame.draw.rect(screen, (255,0,0), pygame.Rect(x, y, 20, 20))
else:
screen.blit(snektext_2x,snektext_rect_2x)
screen.blit(menutext,menutext_rect)
screen.blit(snekk,snekk_rect)
pygame.display.update()
clock.tick(60)