2011-03-13 71 views
1

我想有精靈隨機使用OOP原理與在屏幕上出現製作精靈隨機出現

這個代碼是從螞蟻演示了AI

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

問題: 我如何獲得精靈隨機在屏幕上? 我知道他們的blit但 如何在不使用面向對象的

這是我的代碼是缺少一種讓精靈隨機出現 此代碼到即時得到的代碼antstate.py只有部分: http://www.mediafire.com/?5tjswcyl9xt5huj

+0

而你的問題是..? – 2011-03-13 21:33:44

+2

我很難理解你的問題。代碼現在在做什麼?你想要它做什麼?如果您可以將問題限制爲非常具體的問題,您將有更好的機會獲得答案。要求人們下載來自mediafire的大量代碼是一個可以忽略的問題。 – 2011-03-13 21:35:30

+0

爲什麼「不使用面向對象的原則」? 'Vector2(randint(0,w),randint(0,h))'產生一個隨機的屏幕位置(x在0..screenwidth,y在0..screenheight);然後將其分配給leaf.location,並將葉子添加到「世界上的事物」中;那麼每次調用world.render()時,都會被告知繪製自己。 – 2011-03-14 00:53:49

回答

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)