【发布时间】:2016-12-06 19:49:58
【问题描述】:
我是一名编码新手,正在编写 Python 程序以使用 Pygame 库模拟自然选择。
我正在尝试完成的一件事是使重叠的移动椭圆(或者如果这太复杂,则为矩形)对象产生一个继承其特征的子对象。
我的问题是我无法创建一个工作代码来识别任何两个对象区域何时重叠。我需要代码来识别两个对象何时穿过路径(并且暂时重叠),以便游戏知道生成另一个形状。
有一次我尝试了一个我认为可行的复杂嵌套 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 或其他您正在寻找的示例,那就太好了。我想我明白了,但我不确定确定
-
你的形状可以旋转还是有固定的方向?
-
您没有发布导致模拟崩溃的代码,是吗? (我没有看到嵌套的 for 循环)。
-
形状不旋转,它们是固定方向但在屏幕上移动。不久前我摆脱了嵌套的 for 循环,甚至还没有想到寻求帮助,因为我认为这毫无意义。
-
这正是 Pygame Rect 类的用途:pygame.org/docs/ref/rect.html#pygame.Rect.colliderect
标签: python pygame area rectangles ellipse