Не могу выйти из цикла пигмеев - PullRequest
1 голос
/ 01 мая 2020

Я недавно начал пробовать Pygame. Я следовал учебному пособию, пока не добрался до точки, где я должен был выйти из l oop. Сначала это не сработало, но потом вдруг сработало. Честно говоря, я не знаю, что случилось. В следующий раз я пошел и попытался сделать что-то еще с Pygame. И удивительно, что это не сработало, поэтому я оглянулся на исправленный код, чтобы увидеть, где была ошибка. Проблема, я думаю, они идентичны. Я не могу закрыть окно, оно даже не говорит "Не отвечает". Мне просто нужно закрыть его через диспетчер задач каждый раз. Это весь код, я отправляю все это, поскольку я думаю, что что-то может блокировать его (не обращайте внимания на реальный код, я все еще работаю над этим, и могут быть ошибки):

#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()

Так что я отредактировал его, и оно не сработало, если вы имели в виду следующее:

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()

1 Ответ

1 голос
/ 01 мая 2020

Вы должны реализовать событие pygame.QUIT во внутреннем l oop. Обратите внимание, что код во внешнем l oop выполняется только тогда, когда внутренний l oop завершен:

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:
                # [...]

В любом случае, в вашем случае абсолютно необязательно реализовывать 2 вложенных цикла, удалите внешний л oop. Одного л oop вполне достаточно:

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

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

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

Полный пример кода:

#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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...