我想在进化模拟方面做一些工作。第一部分是在pygame上制作独立移动的方块。这似乎工作除了一个轻微的故障!当使用for语句第43行时,它似乎不会将它应用于仅生成第一个的所有方块。所以一个方格按预期移动其余的只是坐在那里什么都不做..请帮助:D
import pygame, sys
from pygame.locals import *
import time
import random
pygame.init()
# set up the window
DISPLAYSURF = pygame.display.set_mode((500, 500), 0, 32)
pygame.display.set_caption('Drawing')
# set up the colors
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = ( 0, 255, 0)
BLUE = ( 0, 0, 255)
# draw on the surface object
DISPLAYSURF.fill(BLACK)
robot_list=[]
counter =0
while counter < 26:
x=random.randrange(1,500)
x2 = x +6
y= random.randrange(1,500)
y2 = y +6
robot_file=pygame.draw.polygon(DISPLAYSURF, WHITE, ((x, y), (x2, y), (x2, y2), (x, y2)))
robot_list.append(robot_file)
counter +=1
# run the game loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
for r in robot_list:
time.sleep(0.1)
pygame.draw.polygon(DISPLAYSURF, BLACK, ((x, y), (x2, y), (x2, y2), (x, y2)))
rand2=random.randrange(1,6)
rand1=random.randrange(-6,6)
x += rand1
x2+= rand1
y+=rand2
y2+=rand2
pygame.draw.polygon(DISPLAYSURF, WHITE, ((x, y), (x2, y), (x2, y2), (x, y2)))
pygame.display.update()
pygame.display.update()
答案 0 :(得分:1)
简单:代码中只有一个多边形。我不确定pygame.draw.polygon()
返回什么; according to the documentation,它不会返回任何有用的内容。
您需要做的是将多边形的坐标放入列表robot_file
(这是一个非常糟糕的列表名称,BTW),然后更新这些坐标。
答案 1 :(得分:0)
似乎没有将它应用于仅生成第一个的所有方块。
这里的问题是你没有任何 square 。你只需使用绘图功能绘制一些东西。要更好地理解这一点,也许只需创建一个从主循环中抽象出游戏对象的类。
示例:强>
class Polygon(object):
def __init__(self):
self.x = random.randrange(1,500)
self.x2 = self.x + 6
self.y = random.randrange(1,500)
self.y2 = self.y + 6
def move(self):
rand2 = random.randrange(1,6)
rand1 = random.randrange(-6,6)
self.x += rand1
self.x2 += rand1
self.y += rand2
self.y2 += rand2
def draw(self, surface):
pygame.draw.polygon(surface, WHITE, ((self.x, self.y), (self.x2, self.y), (self.x2, self.y2), (self.x, self.y2)))
for _ in xrange(26):
robot_list.append(Polygon())
# run the game loop
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
for r in robot_list:
r.move()
r.draw(DISPLAYSURF)
time.sleep(0.1)
pygame.display.update()