如何在 pygame 中获得多个精灵的路线以进行蚂蚁模拟?

问题描述

我正在尝试获取 500 个“蚂蚁”的路径,但是使用 update() 函数,我不确定我是否可以绘制甚至找到更好的方法来做到这一点。我正在尝试找到一种从更新中获取信息的方法,但我不确定如何做到这一点。这是一个蚂蚁模拟,这里是代码

import random
import json
#Ant position adding into json file removed from code (all 350,350)
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((750,750))
screen.fill((255,255,255))
background = pygame.image.load("background.png")
running = True
food_found = False
#foodfind() for each ant check if it collides with the food group
class Ant(pygame.sprite.Sprite):
    def __init__(self,picture_path,pos_x,pos_y):
        super().__init__()
        self.image = pygame.image.load(picture_path)
        self.rect = self.image.get_rect()
        self.rect.center = [pos_x,pos_y]
    def update(self):
        directs = random.randint(1,4)
        #move ants randomly
        if 750 - self.rect.x > 5:
            if directs == 1:
                self.rect.x -= 5
                x = -5
        if 750 - self.rect.x < 745:
            if directs == 2:
                self.rect.x += 5
                x = 5
        if 750 - self.rect.y > 5:
            if directs == 3:
                self.rect.y -= 5
                y = -5
        if 750 - self.rect.y < 745:
            if directs == 4:
                self.rect.y += 5
                y = 5
        with open("positions.json",'r') as f:
            positions = json.load(f)
        positions[i]["x"] += x
        positions[i]["y"] += y
        with open("positions.json",'w') as f:
            json.dump(positions,f)
    def go_home(self):
        if food_found != False:
            pass
        #not done yet
pos_x,pos_y = random.randint(0,750),random.randint(0,750)
class Food(pygame.sprite.Sprite):
    #food for "ants"
    def __init__(self,picture_path):
        super().__init__()
        self.image = pygame.image.load(picture_path)
        self.rect = self.image.get_rect(center=(pos_x,pos_y))
        self.hitBox = self.rect.inflate(100,100)
        x = random.randint(pos_x-25,pos_x+25)
        y = random.randint(pos_y - 25,pos_y + 25)
        self.rect.x = x
        self.rect.y = y
    def update(self):
        self.hitBox.center = self.rect.center
ant_gr = pygame.sprite.Group()
food_gr = pygame.sprite.Group()
# i add 500 ants and 1000 foods (not included)
#main loop not included

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)