簡體   English   中英

python 3.x pygame雨

[英]Python 3.x pygame Rain

我正在嘗試使用pygame和類在Python中進行某種降雨效果。 我不習慣OOP,也不知道我做錯了什么。 拖放僅凍結在屏幕頂部。 這是我的代碼:

import pygame
import random

pygame.init()
width = 400
height = 300
screen = pygame.display.set_mode((width, height))
background = pygame.Surface(screen.get_size())
background.fill((230, 230, 250))
background = background.convert()

x = random.randint(0,width)
y= random.randint(-20,-3)
yspeed = random.randint(1,5)
class Drop(object):
    def __init__(self):
        self.x=x
        self.y=y
        self.yspeed=yspeed
    def fall(self):
        self.y+=self.yspeed

    def show(self):
        pygame.draw.line(background, (138, 43, 226), (self.x, self.y), (self.x, self.y + 10))
        screen.blit(background, (0, 0))
drop=Drop()
drop.fall()
drop.show()

mainloop = True
FPS= 30
clock = pygame.time.Clock()

while mainloop:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
             mainloop = False
    pygame.display.flip()
    clock.tick(FPS)

我剛剛開始在pygame和python中工作,所以任何幫助都會很棒。

我看到這段代碼有兩個問題,第一個問題是您在類中使用變量xyyspeed ,但沒有將這些值用作參數。 要解決此問題,請將您的類定義更改為:

class Drop(object):
    def __init__(self, x, y, yspeed):
        self.x=x
        self.y=y
        self.yspeed=yspeed
    def fall(self):
        self.y+=self.yspeed
    def show(self):
        pygame.draw.line(background, (138, 43, 226), (self.x, self.y), (self.x, self.y + 10))
        screen.blit(background, (0, 0))

然后在創建更多drop時執行以下操作:

drop = Drop(x,y,yspeed)

另外,drop凍結的原因是您先運行drop.fall() ,然后運行drop.fall() drop.show()一次,這意味着此代碼只運行一次,因此繪制了您的drop並停止了它。 相反,您需要將其添加到在底部運行的while循環中,實際上這是所有重復代碼都應放在程序中的位置。

暫無
暫無

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

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