让精灵随机出现
我想让一些小图标(精灵)在屏幕上随机出现,但不想用面向对象的编程方法。
这段代码是一个关于蚂蚁的演示,目的是为了展示人工智能。
if randint(1, 10) == 1:
leaf = Leaf(world, leaf_image)
leaf.location = Vector2(randint(0, w), randint(0, h))
world.add_entity(leaf)
world.process(time_passed)
world.render(screen)
pygame.display.update()
问题: 我怎么才能让精灵随机出现在屏幕上呢? 我知道怎么把它们画出来, 但是不使用面向对象的方法该怎么做呢?
我这段代码唯一缺少的就是让精灵随机出现的方法。 这是我在antstate.py文件中找到的代码: http://www.mediafire.com/?5tjswcyl9xt5huj
1 个回答
1
精灵是一种对象。所以你需要用一些面向对象编程(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)