I am using Python 3.4 with Pygame 1.9.2 on a windows 8 hp computer. I am working on a simple snake game where the worm eats the apple and gets longer. The code seems to be fine as far as I know, and the game works for what I have so far (worm doesn't grow yet). But the problem I'm having is that while I am testing the game it will occasionally, temporarily freeze the keys. The game will still run, but I can't use the keys for a few seconds or so, causing game over as the worm runs into the edge of the window. If I leave the curser within the screen and click, the functionality will return sooner, but you shouldn't have to deal with this problem while playing a snake game. Every second counts! Any suggestions?
import pygame
import time
import random
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Game Experiment")
clock = pygame.time.Clock()
framePsecond = 10
block_size = 10
font = pygame.font.SysFont(None, 25)
def message_to_screen(msg,color):
screen_text = font.render(msg, True, color)
gameDisplay.blit(screen_text, [display_width/2 - 175,display_height/2])
def gameLoop():
gameExit = False
gameOver = False
lead_x = display_width/2
lead_y = display_height/2
lead_x_change = 0
lead_y_change = 0
randApplex = round(random.randrange(0, display_width-block_size)/10.0)*10.0
randAppley = round(random.randrange(0, display_height-block_size)/10.0)*10.0
while not gameExit:
while gameOver == True:
gameDisplay.fill(black)
message_to_screen("Game over! Press 'p' to play again or 'q' to quit",white)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_p:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -block_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = block_size
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -block_size
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = block_size
lead_x_change = 0
if lead_x >= display_width or lead_x <= 0 or lead_y >= display_height or lead_y < 0:
gameOver = True
lead_x += lead_x_change
lead_y += lead_y_change
gameDisplay.fill(green)
pygame.draw.rect(gameDisplay, red, [randApplex,randAppley,block_size,block_size])
pygame.draw.rect(gameDisplay, red, [lead_x,lead_y,block_size,block_size])
pygame.display.update()
if lead_x == randApplex and lead_y == randAppley:
randApplex = round(random.randrange(0, display_width-block_size)/10.0)*10.0
randAppley = round(random.randrange(0, display_height-block_size)/10.0)*10.0
clock.tick(framePsecond)
pygame.quit()
quit()
gameLoop()