2017-08-07 81 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)。这向更广泛的社区表明,您已经找到了解决方案,并为答复者和您自己提供了一些声誉。没有义务这样做。 –