python - opygame : trying to bouce a ball, 但它卡住了

标签 python if-statement pygame bounce

import pygame

Red = 255, 0, 0
Black= 0,0,0
rectXpos = 2
rectypos = 2
speed = 2
screenedgex = 500

pygame.init()

window = pygame.display.set_mode(size=(500, 500))

clock = pygame.time.Clock()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        pygame.display.update()

        window.fill(Black)
        square = pygame.draw.rect(window, Red, [rectXpos, rectypos, 50, 50],2)
        rectXpos += 2

        if rectXpos < 500:
            rectXpos -= 2



        clock.tick(60)
        print(rectXpos)`enter code here`

那我做错了什么?我尝试使用 if 语句来停止球并将其反转,但它使球保持在窗口的边缘

最佳答案

这是完整的代码,我将 x 和 y 反弹分开,因此您可以使用其中任何一个,还更新了代码,再加上一些额外的格式。

# Imports
import pygame

# Vars
Red = 255, 0, 0
Black= 0,0,0
rectXpos = 2
rectYpos = 2
rect_width = 50
rect_height = 50
screen_width = 500
screen_height = 500
block_x_direction = 1
block_y_direction = 1

# Setup Code
pygame.init()
window = pygame.display.set_mode(size=(screen_width, screen_height))
clock = pygame.time.Clock()
running = True

# Game Loop
########################################################
while running:
    # Event Loop
    ########################################################
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False


    # Game Code - Update
    ########################################################
    # Game Code - Update - Rect X Bounce
    if rectXpos + (rect_width)>= screen_width:
        block_x_direction = block_x_direction * -1
    rectXpos += 2 * block_x_direction
    # Game Code - Update - Rect Y Bounce
    if rectYpos + (rect_height)>= screen_height:
        block_y_direction = block_y_direction * -1
    rectYpos += 2 * block_y_direction

    # - Tick Game    
    clock.tick(60)

    # Game Code - Render
    ########################################################
    window.fill(Black)
    square = pygame.draw.rect(window, Red, [rectXpos, rectYpos, rect_width, rect_height],2)
    pygame.display.update()

    # Game Code - Debug Code
    ########################################################
    print(clock.tick)

关于python - opygame : trying to bouce a ball, 但它卡住了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59798069/

相关文章:

python - 将任务分配给每个单独的核心

android - Android,if/else构造总是失败(编译器无法读取更改)

python - python 上的 tic tac toe 程序出现某种错误,弹出黑屏,程序没有响应

python - 属性错误: 'Ball' object has no attribute 'x'

MySQL 查询 - IF 或 CASE 以及 AND 和异常(exception)(用于计算)

python - Pygame 能在图形方面做哪些 wxPython 做不到的事情?

python - Pandas:根据两列的条件按组进行行比较

python - 根据条件Python将请求传递给不同的类

python - 找不到目录时停止python程序关闭

javascript - 如果条件不运行但条件有效