簡體   English   中英

Pygame 運行幾秒后無響應

[英]Pygame Becomes Unresponsive after running for a few seconds

我正在嘗試編寫一個 GUI 來顯示 Knights Tour 回溯算法。 我的算法可以正常工作,但是在運行 GUI 時,它會在幾秒鍾后變得無響應。

import pygame
import time

# Init Gui

pygame.init()


# Window Size
WIN_DIMENSION = 800

win = pygame.display.set_mode((WIN_DIMENSION, WIN_DIMENSION))
pygame.display.set_caption("Knights Tour")


# Board Size
N = 8

TARGETMOVES = N**2

# Colors
white = (255, 255, 255)
black = (0, 0, 0)
red = (180, 0, 0)

def DisplayGui(board, final=False):

    win.fill(black)

    for i in range(N):
        ydraw = i * (WIN_DIMENSION/N)
        for n in range(N):
            xdraw = n * (WIN_DIMENSION / N)
            pygame.draw.rect(win, red, (xdraw, ydraw, WIN_DIMENSION/N, WIN_DIMENSION/N), 3)
            displayText(board[i][n], xdraw, ydraw)

    while final:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                final = False
                print("CLOSING")

    pygame.display.update()
    #time.sleep(1)


def text_objects(text, font):
    textSurface = font.render(str(text), True, white)
    return textSurface, textSurface.get_rect()


def displayText(text, xdraw, ydraw):
    font = pygame.font.Font('freesansbold.ttf', 7 * N)
    TextSurf, TextRect = text_objects(text, font)
    TextRect.center = ((xdraw + (WIN_DIMENSION / N) / 2), (ydraw + (WIN_DIMENSION / N) / 2))
    win.blit(TextSurf, TextRect)


def checkValid(board, movx, movy):
    '''
        params:
        movx => next x move
        movy => next y move

        checks if move is valid
    '''
    if (movx >= 0 and movy >= 0 and movx < N and movy < N and board[movx][movy] == " "):
        return True
    return False


def printBoard(board):
    '''
        Prints Board
    '''
    for i in range(len(board)):
        print(board[i])


def KnightsTour():
    currx = 0
    curry = 0

    # Init board
    board = [[" " for i in range(N)] for i in range(N)]

    xmoves = [-2, -2, -1, -1, 1, 1, 2, 2]
    ymoves = [1, -1, 2, -2, 2, -2, 1, -1]

    totalmoves = 1

    board[0][0] = 0
    DisplayGui(board)

    if generateMove(board, currx, curry, totalmoves, xmoves, ymoves):
        printBoard(board)
        DisplayGui(board, True)
    else: print("Invalid")





def generateMove(board, currx, curry, totalmoves, xmoves, ymoves):
    if totalmoves == TARGETMOVES:
        return True

    print("X: {} <> Y: {}".format(currx, curry)) # draw  board here

    DisplayGui(board)        


    for i in range(8):

        nextx = currx + xmoves[i]
        nexty = curry + ymoves[i]

        if checkValid(board, nextx, nexty):
            board[nextx][nexty] = totalmoves


            if generateMove(board, nextx, nexty, totalmoves+1, xmoves, ymoves):

                return True
            # backtracking
            board[nextx][nexty] = " "

    return False


if __name__ == "__main__":
    KnightsTour()

我試圖使用 sys.sleep() 來減慢它的速度,但這並沒有幫助它。 我不知道是什么導致 GUI 凍結。 算法仍在后台運行。

如果您想在不顯着更改代碼的情況下解決這個問題,您可以在DisplayGui()函數中調用pygame.event.pump( )。 這將使您的操作系統/窗口管理器相信您的程序沒有凍結。

def DisplayGui(board, final=False):

    win.fill(black)
    if not final:
        pygame.event.pump()
    for i in range(N):
        ...

實際處理 QUIT 事件會更有幫助,這樣您就可以在不結束 python 進程的情況下提前結束程序。

如果您正在考慮重新組織您的代碼,也許這本openbook會很有用。 本節描述了一個標准的游戲循環,它應該類似於:

事件處理→更新狀態→繪制新狀態→更新顯示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM