使用pygame创建随机物体

-4 投票
2 回答
2907 浏览
提问于 2025-04-18 00:03

我正在用Python 3.3和pygame开发一个游戏。 我能不能请你给我一段代码,能做到以下这些: 创建一个800 * 800大小的屏幕。 在屏幕上,固定大小为30 * 30的矩形从右边出现,并慢慢向左移动。 一旦它们碰到左边的墙壁,就消失。 这些矩形应该在随机的高度出现,并且以固定的速度移动。 这是我尝试过的:

import pygame, sys
from pygame.locals import *
addrect = 0
addrect_rate = 40
rectangles = []
while True:
    for r in rectangles:
        addrect += 1
        if addrect == addrect_rate:
            addect = 0
            newrect = {'rect': pygame.Rect(40, 40, 10, 10),
                       'speed': rect_speed,
                       'image': pygame.draw.rect((50, 50), 10, 10)
                      } 
    for r in rectangles:
        rectangles.append(newrect)

基本的思路就是这样。请帮我完成代码,绘制屏幕,并让这个功能正常工作。 谢谢!

2 个回答

0

关于你的代码,有几点需要注意。首先,你不应该在每次循环中都往列表里添加一个矩形,特别是在for循环里。

import pygame, sys, random
from pygame.locals import *
pygame.init()
surface = pygame.display.set_mode((400,400))
addrect = 0 addrect_rate = 40
rectangles = []
while True: 
    addrect += 1
    if addrect == addrect_rate:
        # also wrong!!! You are using a pygame call in a dict newrect = {'rect': pygame.Rect(40, 40, 10, 10), 'speed': rect_speed, 'image': pygame.draw.rect((50, 50), 10, 10) }
        newrect = {'rect': pygame.Rect(40, random.randint(1,400), 10, 10), 'speed': rect_speed }
    for r in rectangles:
        r['rect'].x += r['speed']
        pygame.draw.rect(surface, (255,0,0) r['rect'])
    #wrong
    #for r in rectangles: 
        #addrect += 1 
        #if addrect == addrect_rate:
            #addect = 0 
            #newrect = {'rect': pygame.Rect(40, 40, 10, 10), 'speed': rect_speed, 'image': pygame.draw.rect( }
    #for r in rectangles:
        #rectangles.append(newrect)
0

谢谢你添加代码。我对pygame不太熟悉,所以我不得不重写一遍代码,才能弄明白怎么做。我觉得我加了足够的注释,让每个部分的功能都很清楚。

如果你想更深入地学习如何使用pygame,我参考了programarcadegame的“精灵入门”来帮助我完成这个任务。

无负担的欧洲箱燕

import random

import pygame

# create a screen of size say 800 * 800.
screen_width, screen_height = 800, 800
pygame.init()
pygame.display.set_caption('Unladen European Box Swallows')
screen = pygame.display.set_mode((800, 800))

# On the screen rectangles of a fixed size of 30*30...
BLACK, WHITE = (0, 0, 0), (255, 255, 255)
swallows = pygame.sprite.Group()
class Swallow(pygame.sprite.Sprite):
    def __init__(self, width=30, height=30, x=0, y=0, color=WHITE):
        #super(Swallow, self).__init__()  # this is for python 2.x users
        super().__init__()
        # self.image and self.rect required for sprite.Group.draw()
        self.image = pygame.Surface((width, height))
        self.image.fill(color)
        self.rect = self.image.get_rect()
        self.x_subpixel = x
        self.y_subpixel = y

    # subpixel required for constant movement rate per second
    @property
    def x_subpixel(self):
        return self._x_subpixel
    @x_subpixel.setter
    def x_subpixel(self, new_x):
        self._x_subpixel = new_x
        self.rect.x = int(round(new_x))
    @property
    def y_subpixel(self):
        return self._y_subpixel
    @y_subpixel.setter
    def y_subpixel(self, new_y):
        self._y_subpixel = new_y
        self.rect.y = int(round(new_y))


chance_to_appear = 0.01
airspeed_velocity = 100
clock = pygame.time.Clock()
done = False
while not done:
    ticks = clock.tick(60)
    # ...appear from the right [at random heights]...
    if random.random() < chance_to_appear:
        swallow = Swallow(x=screen_width, y=random.randrange(screen_height))
        swallows.add(swallow)
    # ...[and fixed speed]
    for swallow in swallows:
        swallow.x_subpixel -= float(airspeed_velocity) * ticks / 1000
    # as soon as they collide with the left wall, they disappear.
    for swallow in swallows:
        if swallow.x_subpixel <= 0:
            swallows.remove(swallow)
    # do regular pygame stuff
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    screen.fill(BLACK)
    swallows.draw(screen)  # Group.draw uses each .image and .rect to draw
    pygame.display.flip()
pygame.quit()

下次再见

附言:请不要期待以后在StackOverflow上会有这么多代码的创作。我只是想体验一下让这个程序运行的过程。希望这对你有帮助。将来,我建议你阅读这种指南,学习如何写出成功的问题,以便获得更好的答案和更多的投票。

撰写回答