简体   繁体   中英

Cant quit the pygame loop

I recently started trying out pygame. I followed a tutorial until it got to the point where I was supposed to quit the loop. At first, it didn't work but then it suddenly did. I honestly don't know what happened. Next time I went and tried doing something else with pygame. And surprisingly it didn't work, so I looked back at the resolved code to see where the mistake was. The problem is I think they are identical. I can't close the window, it doesn't even say "Not Responding." I just have to close it through task manager every time. This is the whole code, I am sending all of it since I think something might be blocking it(pay no attention to the actual code, I am still working on it and there may be mistakes):

#importing modules
import pygame
import time

#creating the window and starting pygame
pygame.init()
win = pygame.display.set_mode((640, 480))
pygame.display.set_caption('Second Game')

#assigning valid and uppercase characters
validChars = "`123456789-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./"
shiftChars = '~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:"ZXCVBNM<>?'

#creating a class for the Text box
class TextBox(pygame.sprite.Sprite):
    def __init__(self, message):
        pygame.sprite.Sprite.__init__(self)
        self.message = message
        self.text = ""
        self.font = pygame.font.Font(None, 50)
        self.image = self.font.render(self.message , False, [0, 0, 0])
        self.rect = self.image.get_rect()

    def add_chr(self, char):
        global shiftDown
        if char in validChars and not shiftDown:
            self.text += char
        elif char in validChars and shiftDown:
            self.text += shiftChars[validChars.index(char)]
        self.update()

    def update(self):
        old_rect_pos = self.rect.center
        self.image = self.font.render(self.text, False, [0, 0, 0])
        self.rect = self.image.get_rect()
        self.rect.center = old_rect_pos

#decides which question it should show in typerun
def textBoxMessage():
    global textBox
    playercount = 0
    if len(textBox.text) == 0:
        if playercount == 0:
            textBox = TextBox(message = 'How many people will be playing?')
        elif playercount == 0 and player_names == []:
            playercount += 1
            for player_num in range(1, playercount):
                textBox = TextBox(message = 'Player ' + playercount + ' please enter your name.')

#creating the screen and assigning values
textBox = TextBox(message = 'How many people will be playing?')
shiftDown = False
textBox.rect.center = [320, 240]
playercount = 0


#the main loop         
run = True
while run:
    #setting up the quit option
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    #creating the typing enviroment
    typerun = True
    while typerun == True:

        textBoxMessage()
        screen = pygame.display.set_mode([640, 480])
        shiftDown = False
        textBox.rect.center = [320, 240]
        screen.fill([255, 255, 255])
        screen.blit(textBox.image, textBox.rect)
        pygame.display.flip()

        #assigning functions to keys
        for e in pygame.event.get():
            if e.type == pygame.KEYUP:
                if e.key in [pygame.K_RSHIFT, pygame.K_LSHIFT]:
                    shiftDown = False
            if e.type == pygame.KEYDOWN:
                textBox.add_chr(pygame.key.name(e.key))
                if e.key == pygame.K_SPACE:
                    textBox.text += " "
                    textBox.update()
                if e.key in [pygame.K_RSHIFT, pygame.K_LSHIFT]:
                    shiftDown = True
                if e.key == pygame.K_BACKSPACE:
                    textBox.text = textBox.text[:-1]
                    textBox.update()
                if e.key == pygame.K_RETURN:
                    if len(textBox.text) > 0:
                        #giving the ENTER button the right to end typerun when everything is done
                        if textBox == TextBox(message = 'How many people will be playing?') and len(textBox.text) > 0 and type(textBox.text) is int:
                            playercount = textBox.text
                            print(playercount)
                        elif textBox == TextBox(message = 'Player ' + str(playercount) + ' please enter your name.'):  
                            typerun = False
pygame.quit()

So I edited it and it didn't work, if this is what u meant:

run = True
while run:
    #setting up the quit option

    #creating the typing enviroment
    typerun = True
    while typerun == True:
        # [...]

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

            if e.type == pygame.KEYUP:
                # [...]
    pygame.quit()

You have to implement the pygame.QUIT event in the inner loop. Note the code in the outer loop is only executed when the inner loop has been terminated:

run = True
while run:
    #setting up the quit option

    #creating the typing enviroment
    typerun = True
    while typerun == True:
        # [...]

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

            if e.type == pygame.KEYUP:
                # [...]

Anyway, in your case it is absolutely unnecessary to implement 2 nested loops, remove the outer loop. One loop is perfectly sufficient:

typerun = True
while typerun == True:
    # [...]

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

        if e.type == pygame.KEYUP:
            # [...]

Complete example code:

#the main loop         
run = True
while run:
    #creating the typing enviroment
    typerun = True
    while typerun == True:

        textBoxMessage()
        screen = pygame.display.set_mode([640, 480])
        shiftDown = False
        textBox.rect.center = [320, 240]
        screen.fill([255, 255, 255])
        screen.blit(textBox.image, textBox.rect)
        pygame.display.flip()

        #assigning functions to keys
        for e in pygame.event.get():
            if e.type == pygame.QUIT:
                run = False
                typerun = False       

            if e.type == pygame.KEYUP:
                if e.key in [pygame.K_RSHIFT, pygame.K_LSHIFT]:
                    shiftDown = False
            if e.type == pygame.KEYDOWN:
                textBox.add_chr(pygame.key.name(e.key))
                if e.key == pygame.K_SPACE:
                    textBox.text += " "
                    textBox.update()
                if e.key in [pygame.K_RSHIFT, pygame.K_LSHIFT]:
                    shiftDown = True
                if e.key == pygame.K_BACKSPACE:
                    textBox.text = textBox.text[:-1]
                    textBox.update()
                if e.key == pygame.K_RETURN:
                    if len(textBox.text) > 0:
                        #giving the ENTER button the right to end typerun when everything is done
                        if textBox == TextBox(message = 'How many people will be playing?') and len(textBox.text) > 0 and type(textBox.text) is int:
                            playercount = textBox.text
                            print(playercount)
                        elif textBox == TextBox(message = 'Player ' + str(playercount) + ' please enter your name.'):  
                            typerun = False
pygame.quit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM