如何修复PyGame中闪烁的图形?只更新一次屏幕

2024-04-20 09:35:28 发布

您现在位置:Python中文网/ 问答频道 /正文

import pygame as pg
from pygame.constants import MOUSEBUTTONDOWN, MOUSEBUTTONUP
import random

pg.init()
WIDTH = 700
HEIGHT = 700

screen = pg.display.set_mode((WIDTH, HEIGHT))
screen.fill("white")

boxIMG = pg.image.load('asteroid.png')

rndCorner = [(0, 0), (0, 700), (700, 0), (700, 700)]

def draw_screen():
    obstacle = pg.draw.line(screen, (0, 0, 0), (random.choice(rndCorner)), (200, 200), 2)

def box(x, y):
    screen.blit(boxIMG, (x, y))

def game_loop():
    
    running = True
    left_clicking = False
    boxX = 0
    boxY = 0
    clock = pg.time.Clock()
    
    while running:            
        screen.fill("white")
        for event in pg.event.get():
            if event.type == pg.QUIT:
                running = False
                pg.quit()
                
            if event.type == MOUSEBUTTONDOWN:
                if event.button == 1:
                    left_clicking = True
                    
            if event.type == MOUSEBUTTONUP:
                if event.button == 1:
                    left_clicking = False
                    
        if left_clicking:
            boxX, boxY = pg.mouse.get_pos()
            boxX -= 32.5
            boxY -= 32.5
            
            if boxX < 0:
                boxX = 0
            elif boxX > 635:
                boxX = 635
            elif boxY < 0:
                boxY =  0
            elif boxY > 635:
                boxY = 635
                
        # Update Screen
        draw_screen()
        box(boxX, boxY)
        pg.display.update()
        
        clock.tick(60)
                    
game_loop()

因此,我遇到了一个问题,在调用“draw_Screen()”时,我画的线在闪烁。我尝试使用doublebuf,但这并没有解决我的问题。如果你想知道我想实现什么,我试图在按住左键的同时移动盒子(主要玩家),因此“如果左键点击”


1条回答
网友
1楼 · 发布于 2024-04-20 09:35:28

在每个帧中选择一个新的随机角点坐标。这会导致闪烁。拾取一次随机角点,并在每个帧中使用相同的坐标:

random_corner = random.choice(rndCorner)
def draw_screen():
    obstacle = pg.draw.line(screen, (0, 0, 0), random_corner, (200, 200), 2)

相关问题 更多 >