Skip to main content
 首页 » 编程设计

python之学习Pygame,为什么这个 'raindrop'(Rect object)不会倒下

2024年10月17日9lonelyxmas

我正在尝试制作 purple rain program在 python 中使用 pygame。我创建了一个名为 Rain 的类,我将使用它来制作多个雨滴,但我尝试测试是否只有 1 个雨对象会掉落但是......它没有,我似乎无法弄清楚我做错了什么。虽然这可能是一个简单且非常明显的问题,但请记住,我仍在学习 pygame 和 python,所以..这是我的代码。

import pygame, sys 
from pygame.locals import * 
import random 
 
pygame.init() 
 
FPS = 60 
 
BLACK = (0,0,0) 
WHITE = (255,255,255) 
PURPLE = (130, 50, 200) 
 
screen_resolution = (800, 600) 
 
screen = pygame.display.set_mode(screen_resolution) 
 
pygame.display.set_caption('Purple Rain') 
 
clock = pygame.time.Clock() 
 
gameLoop = True 
 
class Rain: 
 
    def __init__(self, x, y, width, height, yspeed): 
        self.rect = pygame.Rect(x,y,width,height) 
        self.yspeed = yspeed 
        self.x = x 
        self.y = y 
    def fall(self): 
        self.rect.move(self.x, self.y - self.yspeed) 
    def draw(self): 
        pygame.draw.rect(screen, PURPLE, self.rect) 
drop = Rain(400,300,2,20,9) 
while gameLoop: 
    for event in pygame.event.get(): 
        if event.type == QUIT: 
            pygame.quit() 
            sys.exit() 
    screen.fill(WHITE) 
    drop.draw() 
    drop.fall() 
    pygame.display.flip() 
    clock.tick(FPS) 

请您参考如下方法:

self.rect.move(self.x, self.y - self.yspeed) 返回一个新的矩形,但不改变当前的矩形。

您想执行 self.rect.move_ip(0, - self.yspeed) 以便更新 self.rect 对象。

(且参数为偏移量,非绝对坐标)