2017-08-07 82 views
1

我想在Python中使用pygame和類做一些雨效應。我不習慣面向對象,我不知道我做錯了什麼。該下降只是在屏幕上方凍結。這是我的代碼:Python 3.x pygame雨

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的工作,所以任何幫助將是巨大的。

+0

這是你的第一個項目?如果是這樣,我會建議先做一個基於文本的遊戲(儘管你可以自己去做。) –

+0

爲什麼你沒有爲'__init __()設置參數'x','y'和'yspeed'? '功能,因爲目前所有這些變量將保持undefined –

+0

你知道什麼行特別是程序凍結?如果您爲了調試目的而在代碼中放置打印語句,它會顯示嗎? – SeeDerekEngineer

回答

0

我看到這段代碼有幾個問題,第一個是你在類中使用變量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(x,y,yspeed) 

此外,降凍結的原因是,你運行drop.fall()然後drop.show()一次,這意味着這段代碼只運行一次,因此繪製並停止。相反,您需要將其添加到底部運行的while循環中,實際上這是所有重複代碼應該在您的程序中運行的位置。

+0

非常感謝,現在它工作! –

+0

嗨@Raluca Pelin如果這個或任何答案已經解決了您的問題,請點擊複選標記,考慮[接受它](https://meta.stackexchange.com/q/5234/179419)。這向更廣泛的社區表明,您已經找到了解決方案,併爲答覆者和您自己提供了一些聲譽。沒有義務這樣做。 –