【问题标题】:tracing image in pygame [duplicate]在pygame中跟踪图像[重复]
【发布时间】:2021-09-19 09:57:37
【问题描述】:

最近我一直在尝试使用 Pygame 创建一个乒乓球游戏,但我似乎不知道为什么?或者当我在游戏中把它变成一个移动的物体时,它是如何开始追踪的。我该如何解决这个问题?

import pygame, sys

def ball_ani():
    global speedx, speedy
    ball.x += speedx
    ball.y += speedy

    if ball.top <= 0 or ball.bottom >= h:
        speedy *= -1
    if ball.left <= 0 or ball.right >= w:
        speedx *= -1
    
    if ball.colliderect(player) or ball.colliderect(player2):
        speedx *= -1

pygame.init()
clock = pygame.time.Clock()

w, h = 1000, 500

pygame.display.set_caption('Fut Pong')
win = pygame.display.set_mode((w, h))
win.fill("black")
pygame.draw.line(win, "white", (w//2, 0), (w//2, h), 3)

ball = pygame.Rect(w//2 - 10, h//2 - 10, 20, 20)
player = pygame.Rect(w - 15, h//2 - 50, 10, 100)
player2 = pygame.Rect(5, h//2 - 50, 10, 100)

speedx, speedy = 7, 7

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

    ball_ani()

    pygame.draw.ellipse(win, "green", ball)
    pygame.draw.rect(win, "white", player)
    pygame.draw.rect(win, "white", player2)

    pygame.display.flip()
    clock.tick(60)

【问题讨论】:

    标签: python python-3.x pygame game-physics


    【解决方案1】:

    你必须清除每一帧的显示:

    run = True
    while run:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = Fasle
    
        ball_ani()
    
        win.fill("black") # <--- this is missing
    
        pygame.draw.ellipse(win, "green", ball)
        pygame.draw.rect(win, "white", player)
        pygame.draw.rect(win, "white", player2)
    
        pygame.display.flip()
        clock.tick(60)
    
    pygame.quit()
    exit()
    

    典型的 PyGame 应用程序循环必须:

    【讨论】:

    • @hc_dev cleat 是一个错字。比较pygame.quit()sys.exit()
    • 谢谢指导.. 会深入研究,刚刚看到我的直觉在official docs example:if event.type == pygame.QUIT: sys.exit() 中得到证实(解释为“只需退出程序,pygame 将确保一切都干净地关闭。” )。学到了一些新东西。
    猜你喜欢
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-26
    • 2019-09-22
    相关资源
    最近更新 更多