0

私は進化シミュレーションでいくつかの作業をしたいと思っていました。最初の部分は、pygame で独立して動く正方形を作成することでした。これは、1 つのわずかなヒッチを除いて機能するようです。for ステートメントの 43 行目を使用すると、最初の 1 つだけが生成されるすべての正方形には適用されないようです。したがって、1 つの正方形は意図したとおりに動き、残りは何もせずにそこに座っているだけです。助けてください :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()
4

2 に答える 2

1

シンプル: コードにはポリゴンが 1 つしかありません。何pygame.draw.polygon()が返されるかわかりません。documentationによると、有用なものは何も返されません。

代わりに行う必要があるのは、ポリゴンの座標をリストに入れrobot_file(これはリストのかなり悪い名前です)、それらの座標を更新することです。

于 2012-08-29T08:27:31.737 に答える
0

最初の正方形だけが生成されるすべての正方形に適用されるわけではないようです。

ここでの問題は、正方形がないことです。描画機能を使って何かを描くだけです。これをよりよく理解するには、メインループからゲームオブジェクトを抽象化するクラスを作成するだけかもしれません。

例:

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()
于 2012-08-29T09:34:34.587 に答える