为什么 PyGame 在延迟或睡眠之前不在窗口中绘制?

2025-02-18 09:23:00
admin
原创
88
摘要:问题描述:我正在开发一款乒乓球游戏。当任一分数达到 10 时,它应该在屏幕上显示一些文字,并说右边的玩家赢了或左边的玩家赢了。但是,在我的程序中,它不起作用。当它必须显示右边或左边的玩家赢了的文字时,它不会显示。但它对其他一切都有效。以下是代码:# Importing libraries import pyg...

问题描述:

我正在开发一款乒乓球游戏。当任一分数达到 10 时,它应该在屏幕上显示一些文字,并说右边的玩家赢了或左边的玩家赢了。但是,在我的程序中,它不起作用。当它必须显示右边或左边的玩家赢了的文字时,它不会显示。但它对其他一切都有效。以下是代码:

# Importing libraries
import pygame
import random
import time

# Initializing PyGame
pygame.init()

# Setting a window name
pygame.display.set_caption("Ping Pong")

# Creating a font
pygame.font.init()
font = pygame.font.SysFont(None, 30)
pong_font = pygame.font.SysFont("comicsansms", 75)

# Set the height and width of the screen
window_width = 700
window_height = 500
size = [window_width, window_height]
game_win = pygame.display.set_mode(size)
game_win2 = pygame.display.set_mode(size)


# Creating a messaging system
def message(sentence, color, x, y, font_type, display):
    sentence = font_type.render(sentence, True, color)
    display.blit(sentence, [x, y])


# Creating colors
white = (225, 225, 225)
black = (0, 0, 0)
gray = (100, 100, 100)

# Setting up ball
ball_size = 25


class Ball:
    """
    Class to keep track of a ball's location and vector.
    """

    def __init__(self):
        self.x = 0
        self.y = 0
        self.change_x = 0
        self.change_y = 0


def make_ball():
    ball = Ball()
    # Starting position of the ball.
    ball.x = 350
    ball.y = 250

    # Speed and direction of rectangle
    ball.change_x = 5
    ball.change_y = 5

    return ball


def main():
    # Scores
    left_score = 0
    right_score = 0

    pygame.init()

    # Loop until the user clicks the close button.
    done = False

    ball_list = []

    ball = make_ball()
    ball_list.append(ball)

    # Right paddle coordinates
    y = 200
    y_change = 0
    x = 50
    # Left paddle coordinates
    y1 = 200
    y1_change = 0
    x1 = 650

    while not done:
        
        # --- Event Processing
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w:
                    y_change = -7

                elif event.key == pygame.K_s:
                    y_change = 7

                elif event.key == pygame.K_UP:
                    y1_change = -7

                elif event.key == pygame.K_DOWN:
                    y1_change = 7

            elif event.type == pygame.KEYUP:
                y_change = 0
                y1_change = 0

        y += y_change
        y1 += y1_change

        # Preventing from letting the paddle go off screen
        if y > window_height - 100:
            y -= 10
        if y < 50:
            y += 10
        if y1 > window_height - 100:
            y1 -= 10
        if y1 < 50:
            y1 += 10

        # Logic
        for ball in ball_list:
            # Move the ball's center
            ball.x += ball.change_x
            ball.y += ball.change_y

            # Bounce the ball if needed
            if ball.y > 500 - ball_size or ball.y < ball_size:
                ball.change_y *= -1
            if ball.x > window_width - ball_size:
                ball.change_x *= -1
                left_score += 1
            if ball.x < ball_size:
                ball.change_x *= -1
                right_score += 1

            ball_rect = pygame.Rect(ball.x - ball_size, ball.y - ball_size, ball_size * 2, ball_size * 2)

            left_paddle_rect = pygame.Rect(x, y, 25, 75)
            if ball.change_x < 0 and ball_rect.colliderect(left_paddle_rect):
                ball.change_x = abs(ball.change_x)

            right_paddle_rect = pygame.Rect(x1, y1, 25, 75)
            if ball.change_x > 0 and ball_rect.colliderect(right_paddle_rect):
                ball.change_x = -abs(ball.change_x)
                            
            # Here is the where the messaging system doesn't work, I don't know why! It works fine for everything else
            if right_score == 10:
                message("RIGHT PLAYER HAS WON!!", white, 300, 200, font, game_win)
                time.sleep(5)
                pygame.quit()
                quit()
            elif left_score == 10:
                message("LEFT PLAYER HAS WON!!", white, 300, 200, font, game_win)
                time.sleep(5)
                pygame.quit()
                quit()
        # Drawing
        # Set the screen background
        game_win.fill(black)

        # Draw the balls
        for ball in ball_list:
            pygame.draw.circle(game_win, white, [ball.x, ball.y], ball_size)

        # Creating Scoreboard
        message("Left player score: " + str(left_score), white, 10, 10, font, game_win)
        message("Right player score: " + str(right_score), white, 490, 10, font, game_win)

        # Drawing a left paddle
        pygame.draw.rect(game_win, white, [x, y, 25, 100])
        # Drawing a right paddle
        pygame.draw.rect(game_win, white, [x1, y1, 25, 100])

        # Setting FPS
        FPS = pygame.time.Clock()
        FPS.tick(60)

        # Updating so actions take place
        pygame.display.flip()


while True:
    game_win2.fill(black)
    pygame.event.get()
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()
    message("Pong", white, 280, 100, pong_font, game_win2)
    if 150 + 100 > mouse[0] > 150 and 350 + 50 > mouse[1] > 350:
        pygame.draw.rect(game_win, gray, [150, 350, 100, 50])
        if click[0] == 1:
            break
    else:
        pygame.draw.rect(game_win, white, [150, 350, 100, 50])

    if 450 + 100 > mouse[0] > 450 and 350 + 50 > mouse[1] > 350:
        pygame.draw.rect(game_win, gray, [450, 350, 100, 50])
        if click[0] == 1:
            pygame.quit()
            quit()
    else:
        pygame.draw.rect(game_win, white, [450, 350, 100, 50])

    message("Start", black, 175, 367, font, game_win2)
    message("Quit", black, 475, 367, font, game_win2)

    # Go ahead and update the screen with what we've drawn.
    pygame.display.flip()

    # Wrap-up
    # Limit to 60 frames per second
    clock = pygame.time.Clock()
    clock.tick(60)

if __name__ == "__main__":
    main()

我添加了一条小注释,即:“ # Here is the where the messaging system doesn't work, I don't know why! It works fine for everything else”。现在当有人得分 10 分时,什么也不会发生。这=等待几秒钟。这样你就可以在程序关闭之前读到“左边玩家赢了”或“右边玩家赢了”。但它根本就没有出现!我不知道为什么!有人能帮忙吗?


解决方案 1:

pygame.display.update()仅当调用或时,显示才会更新pygame.display.flip()
。请参阅pygame.display.flip()

这将更新整个显示屏的内容。

此外,您还必须使用 处理事件pygame.event.pump(),然后显示更新才会在窗口中可见。

pygame.event.pump()

对于游戏的每一帧,您都需要对事件队列进行某种调用。这可确保您的程序能够与操作系统的其余部分进行内部交互。

如果您想显示文本并延迟游戏,那么您必须更新显示并处理事件。

编写一个延迟游戏并更新显示的函数。我建议使用pygame.time模块来实现延迟(例如pygame.time.delay()

def update_and_wait(delay):
    pygame.display.flip()
    pygame.event.pump()
    pygame.time.delay(delay * 1000) # 1 second == 1000 milliseconds

或者甚至实现一个具有自己的事件循环的函数来保持应用程序响应。通过以下方式测量时间pygame.time.get_ticks()

def update_and_wait(delay):
    start_time = pygame.time.get_ticks()
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                print("auit")
                pygame.quit()
                return False
        if pygame.time.get_ticks() >= start_time + delay * 1000: 
            break
    return True

在应用程序中使用该功能:

def main():
    # [...]

    while not done:
        # [...]

        for ball in ball_list:
            # [...]

            if right_score == 0:
                message_wait("RIGHT PLAYER HAS WON!!", white, 300, 200, font, game_win)
                update_and_wait(5)
                quit()
            elif left_score == 0:
                message_wait("LEFT PLAYER HAS WON!!", white, 300, 200, font, game_win)
                update_and_wait(5)
                quit()
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   2757  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1693  
  在全球化的浪潮下,企业的业务范围不断拓展,跨文化协作变得愈发普遍。不同文化背景的团队成员在合作过程中,由于语言、价值观、工作习惯等方面的差异,往往会面临诸多沟通挑战。而产品生命周期管理(PLM)系统作为企业管理产品全生命周期的重要工具,如何有效支持跨文化协作成为了关键问题。通过合理运用沟通策略,PLM系统能够在跨文化团...
plm是什么软件   15  
  PLM(产品生命周期管理)系统在企业的产品研发、生产与管理过程中扮演着至关重要的角色,其中文档版本控制是确保产品数据准确性、完整性和可追溯性的关键环节。有效的文档版本控制能够避免因版本混乱导致的错误、重复工作以及沟通不畅等问题,提升企业整体的运营效率和产品质量。接下来,我们将深入探讨 PLM 系统实现文档版本控制的 6...
plm是什么意思   19  
  PLM(产品生命周期管理)项目管理旨在通过有效整合流程、数据和人员,优化产品从概念到退役的整个生命周期。在这个过程中,敏捷测试成为确保产品质量、加速交付的关键环节。敏捷测试强调快速反馈、持续改进以及与开发的紧密协作,对传统的测试流程提出了新的挑战与机遇。通过对测试流程的优化,能够更好地适应PLM项目的动态变化,提升产品...
plm管理系统   18  
热门文章
项目管理软件有哪些?
曾咪二维码

扫码咨询,免费领取项目管理大礼包!

云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用