Pygame错误;球的渐变

时间:2015-12-10 12:15:06

标签: python pygame logic

长时间用户,第一次询问。刚刚开始使用pygame并且现在需要一些帮助,我的游戏无法正常工作,因为程序选择球的渐变似乎有问题,现在球似乎沿着x轴的直线走。代码在下面,提前感谢任何帮助

from pygame import *
import time 
import random
init()

width = 1000
height = 1000
screen = display.set_mode((width,height))
display.set_caption('Graphics')

ball1 = Rect(10,10,40,40)
ball1dx = 2
ball1dy = 3

ball2 = Rect(500,500,40,40)

gradient = [-0.25,-0.5,-0.75,-1]
ran = 0

endProgram = False
a = 0
d = 0
w = 0
s = 0

while not endProgram:
    for e in event.get():
        if e.type == KEYUP:
            if (e.key == K_a):
                a = True
                d = False
                w = False
                s = False
            if (e.key == K_d):
                d = True
                a = False
                w = False
                s = False
            if (e.key == K_w):
                w = True
                a = False
                d = False
                s = False
            if (e.key == K_s):
                s = True
                a = False
                d = False
                w = False
    if a:
        ball2.x -= 1
    if d:
        ball2.x += 1
    if w:
        ball2.y -= 1
    if s:
        ball2.y += 1

ball1.move_ip(ball1dx,ball1dy)
if ball1.y < 0 or ball1.y > height - 40:
    ran = random.random()
    ball1dy *= random.choice(gradient)
if ball1.x < 0 or ball1.x > width - 40:
    ran = random.random()
    ball1dx *= random.choice(gradient)

screen.fill((0,0,200))
draw.ellipse(screen, (0,255,0), ball1)
draw.ellipse(screen, (255,0,0),ball2)
display.update()

1 个答案:

答案 0 :(得分:0)

我不知道您的期望是什么,但如果您将数字乘以10之间的分数,您将开始接近0并基本上获得{{1 }}。如果在选择渐变后添加打印语句,您将看到您的数字快速朝向零。

0

我假设你只是试图让球在屏幕上反弹,你只需乘以-1.5 -0.5 0.5 -0.375 0.28125 -0.2109375 0.158203125 -0.0791015625 0.059326171875 -0.0296630859375 0.0222473144531 -0.0111236572266 . . . -1.28840161923e-281 6.44200809614e-282 -3.22100404807e-282 3.22100404807e-282 即可。如果您想要在弹跳时变速,则必须设置最小和最大速度的范围,并且如果它不超过这些边界,则仅乘以渐变。你可以这样做

-1

作为旁注,您可以在ball1.move_ip(ball1dx,ball1dy) if ball1.y < 0 or ball1.y > height - 40: choice = random.choice(gradient) if abs(ball1dy*choice) < 5 and abs(ball1dy*choice) > 0.25: ball1dy *= choice else: ball1dy*=-1 if ball1.x < 0 or ball1.x > width - 40: choice = random.choice(gradient) if abs(ball1dx*choice) < 5 and abs(ball1dx*choice) > 0.25: ball1dx *= choice else: ball1dx*=-1 之前将所有if语句更改为False,然后仅将{1}}切换为if,从而缩小if语句

True