精灵是一个对象。所以你需要使用一些OOP来处理一个精灵。这里有一个例子:
# Sample Python/Pygame Programs
# Simpson College Computer Science
# http://cs.simpson.edu/?q=python_pygame_examples
import pygame
import random
# Define some colors
black = ( 0, 0, 0)
white = (255, 255, 255)
# This class represents the ball
# It derives from the "Sprite" class in Pygame
class Block(pygame.sprite.Sprite):
# Constructor. Pass in the color of the block,
# and its x and y position
def __init__(self, color, width, height):
# Call the parent class (Sprite) constructor
pygame.sprite.Sprite.__init__(self)
# Create an image of the block, and fill it with a color.
# This could also be an image loaded from the disk.
self.image = pygame.Surface([width, height])
self.image.fill(color)
# Fetch the rectangle object that has the dimensions of the image
# image.
# Update the position of this object by setting the values
# of rect.x and rect.y
self.rect = self.image.get_rect()
# Initialize Pygame
pygame.init()
# Set the height and width of the screen
screen_width=700
screen_height=400
screen=pygame.display.set_mode([screen_width,screen_height])
# This is a list of 'sprites.' Each block in the program is
# added to this list. The list is managed by a class called 'RenderPlain.'
block_list = pygame.sprite.RenderPlain()
for i in range(50):
# This represents a block
block = Block(black, 20, 15)
# Set a random location for the block
block.rect.x = random.randrange(screen_width)
block.rect.y = random.randrange(screen_height)
# Add the block to the list of objects
block_list.add(block)
而你的问题是..? – 2011-03-13 21:33:44
我很难理解你的问题。代码现在在做什么?你想要它做什么?如果您可以将问题限制为非常具体的问题,您将有更好的机会获得答案。要求人们下载来自mediafire的大量代码是一个可以忽略的问题。 – 2011-03-13 21:35:30
为什么“不使用面向对象的原则”? 'Vector2(randint(0,w),randint(0,h))'产生一个随机的屏幕位置(x在0..screenwidth,y在0..screenheight);然后将其分配给leaf.location,并将叶子添加到“世界上的事物”中;那么每次调用world.render()时,都会被告知绘制自己。 – 2011-03-14 00:53:49