Дисплей Pygame не обновляется - PullRequest
1 голос
/ 04 февраля 2020

Я делаю игру в Pygame, но дисплей не обновляется. Я использую функцию update () и очищаю экран в начале l oop с помощью fill (). Pygame также загружается не очень быстро; Мне нужно нажать «quit» в приложении pygame, как только оно отобразится в запущенных приложениях на моем ma c, чтобы появился экран.

"Module Imports"
import pygame as pg
import shelve

"Import Classes"
from Settings import Settings
from Settings import Screen
from Settings import Save
from Random import Random
from Input import Input
from Input import Button
# Init Classes
Settings = Settings()
Screen = Screen()
Random = Random()
Save = Save()

on = True

pg.init()

event_const = pg.event.wait()

save_file = shelve.open("/Volumes/HISTORYGAME/Game_Saves/Save_File")

clock = pg.time.Clock()
MainDisplay = pg.display.set_mode((Screen.width, Screen.height))
pg.display.set_caption(Settings.title)
pg.display.init()


class Mouse:
    def __init__(self):
        self.left = False
        self.right = False


Mouse = Mouse()


def begin_game():
    players = []
    num_players = input("How Many Players (enter int): ")

    save_file["num_players_var"] = num_players

    for pl in range(num_players):
        players.append(raw_input("Enter Player Name: "))

    save_file["players_var"] = players

    print(players)


def intro():
    intro = True

    for event in pg.event.get():
        if event.get == pg.QUIT:
            intro = False
            on = False
        if event.get == pg.event.KEYDOWN:
            pass


# begin_game()

test_button = Button(0, 0, 200, 200, "Enter Text Here", MainDisplay)
buttons = []
buttons.append(test_button)

loops = 0

test_x = 10
test_y = 10

while on:
    MainDisplay.fill((0, 0, 0))
    for event in pg.event.get():
        if event.type == pg.QUIT:
            On = False
            pg.quit()
            exit()
        if event.type == pg.KEYDOWN:
            if event.key == pg.K_ESCAPE:
                On = False
                pg.quit()
                exit()
            if event.key == pg.K_RIGHT:
                test_x += 10
                print("right")
        if event.type == pg.MOUSEBUTTONDOWN:
            if event.button == 1:
                Mouse.left = True
            else:
                Mouse.left = False
        if event.type == pg.MOUSEBUTTONUP:
            if event.button == 1:
                Mouse.left = False

    for button in buttons:
        button.draw(pg.mouse.get_pos(), event_const)
        if button.clicked is True:
            print("True \n" * 100)

    pg.draw.line(MainDisplay, (255, 0, 0), (100, 100), (600, 600))
    pg.draw.rect(MainDisplay, (255, 0, 0), (test_x, test_y, 20, 20))

    pg.display.flip()
    pg.display.update()
    clock.tick(Settings.FPS)
    loops += 1
    print(str(loops))

1 Ответ

1 голос
/ 17 февраля 2020

Я подозреваю, что ожидание события или чтение stdin с input() вызывает проблему блокировки. Но в представленном коде призыв к этому закомментирован. На самом деле невозможно знать.

Эта версия кода с воссозданным классом Button работает нормально, но, очевидно, в ней нет ни одного из упомянутых классов.

"Module Imports"
import pygame 
#import shelve

"Import Classes"
#from Settings import Settings
#from Settings import Screen
#from Settings import Save
#from Random import Random
#from Input import Input
#from Input import Button
# Init Classes
#Settings = Settings()
#Screen = Screen()
#Random = Random()
#Save = Save()

WINDOW_WIDTH  = 600
WINDOW_HEIGHT = 600

class Mouse:
    def __init__(self):
        self.left = False
        self.right = False

class Button:
    def __init__( self, x, y, width, height, label, window ):
        self.rect    = pygame.Rect( x, y, width, height )
        self.clicked = False
        self.window  = window
        self.font    = pygame.font.Font( None, 20 )
        self.label   = self.font.render( label, True, ( 255, 255, 255 ) ) # large white text

    def draw( self, mouse_pos ):
        if ( self.rect.collidepoint( mouse_pos ) ):
            colour = ( 0, 200, 0 )  # green if mouse over
        else:
            colour = (0, 0, 200)    # blue otherwise
        pygame.draw.rect( self.window, colour, self.rect, 0 )  # filled rectangle
        # centred text
        label_rect = self.label.get_rect()
        x_offset = ( self.rect.width  - label_rect.width ) // 2
        y_offset = ( self.rect.height - label_rect.height ) // 2
        self.window.blit( self.label, ( x_offset, y_offset ) )

    def checkClick( self, mouse_pos ):
        if ( self.rect.collidepoint( mouse_pos ) ):
            self.clicked = True
        else:
            self.clicked = False


def begin_game():
    players = [ "Mork", "Mindy", "E.T." ]   # test data
    #players = []
    #num_players = input("How Many Players (enter int): ")
    #save_file["num_players_var"] = num_players
    #for pl in range(num_players):
    #    players.append(raw_input("Enter Player Name: "))
    #save_file["players_var"] = players
    print(players)




# Initialisation
pygame.init()
pygame.font.init()
#event_const = pygame.event.wait()
#save_file = shelve.open("/Volumes/HISTORYGAME/Game_Saves/Save_File")
clock = pygame.time.Clock()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ) )
pygame.display.set_caption( "Settings.title" )
pygame.display.init()



Mouse = Mouse()
begin_game()
test_button = Button(0, 0, 200, 200, "Enter Text Here", window)
buttons = []
buttons.append(test_button)

loops = 0
test_x = 10
test_y = 10

on = True
while on:
    window.fill((0, 0, 0))
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            on = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                on = False
            elif event.key == pygame.K_RIGHT:
                test_x += 10
                print("right")
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                Mouse.left = True
        elif event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:
                Mouse.left = False
                for button in buttons:
                    button.checkClick( event.pos )  # buttons actuate on mouse-up

    for button in buttons:
        button.draw( pygame.mouse.get_pos() ) #, event_const)
        if button.clicked is True:
            print("True \n" * 5) # 100

    pygame.draw.line(window, (255, 0, 0), (100, 100), (600, 600))
    pygame.draw.rect(window, (255, 0, 0), (test_x, test_y, 20, 20))

    pygame.display.flip()
    #pygame.display.update()   # only need update() or flip()
    clock.tick( 60 ) #Settings.FPS)
    loops += 1
    #print(str(loops))   # Too noisy

# exiting
pygame.quit()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...