python – Problem trying to detect input focus pygame


I am currently creating my version of the classic “Snake” game from scratch. I have added code that creates a dialogue box using the Tkinter module, allowing the player to choose whether or not to continue playing. However, after using the box the Pygame window gets deselected, so you can’t provide inputs until you click on it. This is a minor error, but it is very bothersome. My objective is to detect when the player has selected the window and then go on with the game, and this seems to work fine when the window is enabled by default upon running the code. However, when line 49 of my code runs and the window isn’t actively selected, it returns:

Traceback (most recent call last):
  File "C:UserssamueAppDataLocalProgramsPythonPython39snakegame.py", line 49, in <module>
    if pygame.mouse.get_focused() == True:
pygame.error: video system not initialized

This confuses me as the first thing I do after importing modules in the code is to initialize pygame. I tried specifically initializing the display module, but it returned the same. How should I fix this?

Here is the code for my game. The important section is in the “if restart:” part for when the game starts or is replayed. More specifically, the “while delay:” loop.

import pygame
import random
from tkinter import *
from tkinter import messagebox

pygame.init()

savedpos = []

myfont = pygame.font.SysFont('Arial', 30)

textsurface = myfont.render('Some Text', False, (255, 0, 0))

foodlocx = (random.randint(0, 25)*20)
foodlocy = (random.randint(0, 25)*20)

win = pygame.display.set_mode((520,520))

pygame.display.set_caption("Snake Game by Sammy T.")

width = 20
height = 20
vel = 20

window = Tk()
#window.eval('tk::PlaceWindow %s center' % window.winfo_toplevel())
window.withdraw()

restart = True

run = True
while run:
    if restart:
        up = False
        down = False
        left = False
        right = True
        score = 0
        restart = False
        x = 240
        y = 240
        win.fill((0,0,0))
        pygame.draw.rect(win, (255, 0, 0), (foodlocx, foodlocy, width, height))
        pygame.draw.rect(win, (0, 255, 0), (x, y, width, height))
        pygame.display.update()
        savedpos = []
        delay = True
        while delay:
            if pygame.mouse.get_focused() == True:
                delay = False
            else:
                pygame.quit()
            
    pygame.time.delay(100)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_LEFT]:
        if not right:
            left = True
            right = False
            up = False
            down = False

    if keys[pygame.K_RIGHT]:
        if not left:
            left = False
            right = True
            up = False
            down = False

    if keys[pygame.K_UP]:
        if not down:
            left = False
            right = False
            up = True
            down = False

    if keys[pygame.K_DOWN]:
        if not up:
            left = False
            right = False
            up = False
            down = True

    if (foodlocx == x) and (foodlocy == y):
        score += 1
        foodlocx = (random.randint(0, 25)*20)
        foodlocy = (random.randint(0, 25)*20)
        for i in savedpos:
            while i[0] == foodlocx and i[1] == foodlocy:
                foodlocx = (random.randint(0, 25)*20)
                foodlocy = (random.randint(0, 25)*20)

    savedpos.append((x,y))

    if (len(savedpos)) > score:
        del savedpos[0]

    if left:
        x -= vel

    if right:
        x += vel

    if up:
        y -= vel

    if down:
        y += vel
        
    win.fill((0,0,0))
    
    if (x > 500) or (x < 0) or (y > 500) or (y < 0):
        textsurface = myfont.render('YOU HIT THE WALL! SCORE: ' + str(score), False, (255, 0, 0))
        win.fill((0,0,0))
        win.blit(textsurface,(70,250))
        pygame.display.update()
        if messagebox.askyesno('You Died!', 'Would you like to play again?') == True:
            restart = True
        else:
            run = False

    for i in savedpos:
        pygame.draw.rect(win, (200, 200, 200), (i[0], i[1], width, height))
        if (i[0] == x) and (i[1] == y):
            textsurface = myfont.render('YOU HIT YOUR TAIL! SCORE: ' + str(score), False, (255, 0, 0))
            win.fill((0,0,0))
            win.blit(textsurface,(70,250))
            pygame.display.update()
            if messagebox.askyesno('You Died!', 'Would you like to play again?') == True:
                restart = True
            else:
                run = False
            

    pygame.draw.rect(win, (255, 0, 0), (foodlocx, foodlocy, width, height))
    pygame.draw.rect(win, (0, 255, 0), (x, y, width, height))
    pygame.display.update()

pygame.quit()



Source link

More To Explore

Share on facebook
Share on twitter
Share on linkedin
Share on email