使用pygame创建随机对象

时间:2014-03-26 21:42:07

标签: python python-3.x pygame game-physics

我正在使用pygame在python 3.3中开发游戏。 我可以请一个可以执行以下操作的代码: 创建一个大小为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 :(得分:0)

感谢您添加代码。我对pygame没有经验,所以我不得不重写它以弄清楚如何完成它。我想我已经提出了足够的意见,以明确每个部分的作用。

如果你想要更多关于如何使用pygame的培训,我使用了programarcadegame" introduction to sprites"帮助我弄清楚如何完成这项工作。

空载欧洲盒燕子

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()

下一次

P.S。请不要期望在StackOverflow上为将来的答案创建这么多代码。我只是希望有这项工作的经验。我希望它对你有所帮助。将来,我建议您在撰写成功问题时阅读this kind of guide以获得更好的答案和更多的选票。

答案 1 :(得分: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)