我是一名編寫Python程序的新手編程人員,使用Pygame庫來模擬自然選擇。如何測試區域是否重疊(Python)
我試圖完成的事情之一是使移動橢圓(或者如果這是太複雜,矩形)重疊的對象會產生繼承其特徵的子對象。
我的問題是我無法創建一個工作代碼來識別何時兩個對象區域重疊。我需要代碼來確定兩個物體何時穿越路徑(並且瞬間重疊),以便遊戲知道產生另一個形狀。
有一次,我嘗試了一個複雜的嵌套for循環,我認爲會工作,但這導致模擬崩潰。
這是我的代碼是:
import pygame, random
# Define some colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
pygame.init()
# Set the width and height of the screen
map_width = 800
map_height = 800
size = [map_width, map_height]
screen = pygame.display.set_mode(size)
# Display name
pygame.display.set_caption("Natural Selection Game")
# Loop until the user clicks the close button.
done = False
# Used to manage how fast the screen updates
clock = pygame.time.Clock()
# -------- Organism -----------
class Organism:
def __init__(self):
# Speed and direction
self.change_x = random.randrange(0,6)
self.change_y = random.randrange(0,6)
# Dimensions
self.width = random.randrange(5,50)
self.height = random.randrange(5,50)
# Diet (WIP)
self.color = random.choice([red, green, blue])
# Starting position
self.x = random.randrange(0 + self.width, 800 - self.width)
self.y = random.randrange(0 + self.height, 800 - self.height)
# Spawn
def spawn(self, screen):
pygame.draw.ellipse(screen, self.color, [self.x, self.y, self.width, self.height])
# Initiate movement
def move(self):
self.x += self.change_x
self.y += self.change_y
# Bounce
def bounce(self, map_width, map_height):
if self.x < 0 or self.x > map_width - self.width:
self.change_x = self.change_x * -1
if self.y < 0 or self.y > map_height - self.height:
self.change_y = self.change_y * -1
# Initial spawning conditions
org_list = []
org_number = 15
for i in range(0,org_number):
org = Organism()
org_list.append(org)
# -------- Main Program Loop -----------
while not done:
# ---- Event Processing ----
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# ---- Logic ----
# Movement
for i in org_list:
i.move()
i.bounce(map_width, map_height)
# Reproduction
# ---- Drawing ----
# Set the screen background
screen.fill(white)
# Spawn organisms
for i in org_list:
i.spawn(screen)
# --- Wrap-up
# Limit to 60 frames per second
clock.tick(60)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Close everything down
pygame.quit()
任何有識之士將不勝感激。
這將是很好,如果你可以MSPaint或一些你正在尋找的例子。我想我理解,但我不確定* –
你的形狀可以旋轉嗎?或者他們有固定的方向嗎? – depperm
您沒有發佈使仿真崩潰的代碼,是嗎? (我看不到嵌套的循環)。 – coredump