簡體   English   中英

Pygame錯誤; 球的漸變

[英]Pygame mistake; gradient of the ball

長時間的用戶,第一次請求。 剛開始使用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()

我不知道您所期望的是什么,但是如果您將數字乘以10之間的一個小數,您將開始接近0並實際上得到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 s之前將它們全部更改為False來壓縮if語句,然后像這樣僅將其切換為True

for e in event.get():
    if e.type == KEYUP:
        w = False
        a = False
        s = False
        d = False
        if (e.key == K_a):
            a = True
        if (e.key == K_d):
            d = True
        if (e.key == K_w):
            w = True
        if (e.key == K_s):
            s = True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM