FreeBasic
Главная
Вход
Регистрация
Четверг, 28.03.2024, 18:26Приветствую Вас Гость | RSS
[ Новые сообщения · Участники · Правила форума · Поиск · RSS ]
  • Страница 1 из 1
  • 1
Форум » Freebasic » Исходники » Псевдо ИИ (Инструменты создания искусственного интеллекта)
Псевдо ИИ
ntvgjhfnjДата: Понедельник, 28.11.2022, 07:24 | Сообщение # 1
Лейтенант
Группа: Проверенные
Сообщений: 59
Репутация: 1
Статус: Offline
Переписал для FB

архив со статьёй и примером

P.S. Думаю всёже медленно работать будет с многочиленными объектами. Если кто сделает лучше и удобнее выложите , хоть посмотрю как надо писать правильно.
Прикрепления: TaskManager.rar (218.1 Kb) · 1998981.rar (4.5 Kb)


polopok

Сообщение отредактировал ntvgjhfnj - Пятница, 09.12.2022, 16:07
 
zamabuvaraeuДата: Среда, 30.11.2022, 10:32 | Сообщение # 2
Подполковник
Группа: Друзья
Сообщений: 147
Репутация: 4
Статус: Offline
Недостатки которые бросились в глаза:

Код в заголовочном файле, нет разделения на модули.
Дефиниции прямо внутри функций.
Лишний Scope.
Код в комментариях.
Проблема с неймингом: маловразумительные d, sd, a, b, c, f, bi и прочие n.
Несколько инструкций на одной строке.
Нет согласованности между объявлениями переменных: то i и j объявляются извне цикла, то прямо внутри цикла.
Однострочный If.
Магические константы.
Плавающий регистр символов: то Function с большой буквы, то boolean с маленькой.
Нет пробелов внутри формул: вместо «a+b» следует писать «a + b».
 
ntvgjhfnjДата: Четверг, 01.12.2022, 19:16 | Сообщение # 3
Лейтенант
Группа: Проверенные
Сообщений: 59
Репутация: 1
Статус: Offline
Да всё так, вариант сырой и требует правок, но рабочий. Выложил как вариант. Думаю каждый сам допилит если нужно.
Писал спонтанно , от того и столько лишнего.
Приложил и саму статью с Флэшь роликом , там доступно и с примером.

Код на AS3
Код

package com.xitri.managers{
    import flash.display.Sprite;
    import flash.events.Event;
    
    /**
  * @author Romanko Denis (Stormit) http://xitri.com
  * @version 3.0
  */
    
    public class TaskManager extends Sprite{
  static public const ALL_TASKS_DONE:String = "allTasksDone";
  
  protected var tasks:Array;
  protected var pauseCount:Number = 0;
  protected var isStarted:Boolean = false;
  protected var isPaused:Boolean = false;
  protected var result:Boolean;
  public var cycle:Boolean;
  
  /**
   * Constructor
   * @param cycle Boolean value indicating whether or not use cycle mode.
   *
   */  
  public function TaskManager(cycle:Boolean = false) {
   this.cycle = cycle;
   tasks = [];
  }
  
  /**
   * Add task to the end of queue. This function will called by ENTER_FRAME event yet will not return true.
   * @param func Function that will called
   * @param params Array of parameters that will passed to function
   * @param ignoreCycle Boolean value. If true function will call once (it makes sense if cycle=true)
   *
   */  
  public function addTask(func:Function, params:Array = null, ignoreCycle:Boolean = false):void {
   tasks.push({func:func, params:params, ignoreCycle:ignoreCycle});
   start();
  }
  
  /**
   * Add task to the end of queue. This function will called once. After that the following task will be carried out.
   * @param func Function that will called
   * @param params Array of parameters that will passed to function
   * @param ignoreCycle Boolean value. If true function will call once (it makes sense if cycle=true)
   *
   */
  public function addInstantTask(func:Function, params:Array = null, ignoreCycle:Boolean = false):void {
   tasks.push({func:func, params:params, ignoreCycle:ignoreCycle, isInstant:true});
   start();
  }
  
  /**
   * Add task and makes it first in queue. This function will called by ENTER_FRAME event yet will not return true.
   * @param func Function that will called
   * @param params Array of parameters that will passed to function
   * @param ignoreCycle Boolean value. If true function will call once (it makes sense if cycle=true)
   *
   */    
  public function addUrgentTask(func:Function, params:Array = null, ignoreCycle:Boolean = false):void{
   tasks.unshift({func:func, params:params, ignoreCycle:ignoreCycle});
   start();
  }
  
  /**
   * Add task and makes it first in queue. This function will called once. After that the following task will be carried out.
   * @param func Function that will called
   * @param params Array of parameters that will passed to function
   * @param ignoreCycle Boolean value. If true function will call once (it makes sense if cycle=true)
   *
   */
  public function addUrgentInstantTask(func:Function, params:Array = null, ignoreCycle:Boolean = false):void{
   tasks.unshift({func:func, params:params, ignoreCycle:ignoreCycle, isInstant:true});
   start();
  }
  
  /**
   * Add pause between tasks
   * @param t Quantity of frames which will last a pause
   * @param ignoreCycle Boolean value. If true function will call once (it makes sense if cycle=true)
   *
   */   
  public function addPause(t:int, ignoreCycle:Boolean = false):void {
   addTask(timerFrame, [t], ignoreCycle);
  }
  
  /**
   * @private
   * Function that implements a pause task. Adds to queue when addPause() is caused.
   * @param t int The internal counter
   *
   */  
  protected function timerFrame(t:int):void {
   pauseCount++;
   if(pauseCount >= t) {
    pauseCount = 0;
    nextTask();
   }
  }
  
  /**
   * Remove all tasks from queue. In fact stops the TaskManager object.
   *
   */  
  public function removeAllTasks():void {
   tasks = [];
  }
  
  /**
   * Passes to the next task. Usually this function is caused automatically when the current task returns result true. But you can cause it compulsorily if that is demanded by the logic of your application.
   * @param ignoreCycle Boolean value. If true current task will not be added to the end of queue (it makes sense if cycle=true)
   *
   */  
  public function nextTask(ignoreCycle:Boolean = false):void {
   if(cycle && !ignoreCycle) {
    tasks.push(tasks.shift());
   } else {
    tasks.shift();
   }
  }
  
  /**
   * @private
   * Starts TaskManager. It is caused when the new task is added.
   */  
  protected function start():void {
   if(!isStarted) {
    addEventListener(Event.ENTER_FRAME, step, false, 0, true);
    isStarted = true;
    isPaused = false;
   }
  }
  
  /**
   * @private
   * Stop TaskManager. It is caused when the last task return true.
   */    
  protected function stop():void {
   removeEventListener(Event.ENTER_FRAME, step);
   isStarted = false;
  }
  
  /**
   * @private
   * It is main function that caused by ENTER_FRAME and calls current task.
   * When all tasks are done dispatch an ALL_TASK_DONE event
   * @param e Event object
   *
   */  
  protected function step(e:Event):void {
   var curTask:Object = tasks[0] as Object;
   if(curTask) {
    result = (curTask.func as Function).apply(this, curTask.params);
    if(curTask == tasks[0] && (curTask.isInstant || result)) {
     nextTask(curTask.ignoreCycle);
    }
   } else {
    stop();
    dispatchEvent(new Event(ALL_TASKS_DONE));
   }
  }
  
  /**
   * Set on/off pause.
   * Contains boolean value
   *
   */  
  public function get pause():Boolean {
   return isPaused;
  }
   
  public function set pause(value:Boolean):void {
   if(value && !isPaused) {
    isPaused = true;
    removeEventListener(Event.ENTER_FRAME, step);
   } else if(tasks[0] && isPaused) {
    isPaused = false;
    addEventListener(Event.ENTER_FRAME, step, false, 0, true);
   }
  }
  
  /**
   * Read only.
   * Contains quantity of tasks in queue.
   *
   */  
  public function get tasksNum():int {
   return tasks.length;
  }
    }
}


Добавлено (01.12.2022, 19:20)
---------------------------------------------
Адрес http://xitri.com не рабочий , когда-то сохранял статьи с того сайта.

Добавлено (10.12.2022, 03:44)
---------------------------------------------



polopok

Сообщение отредактировал ntvgjhfnj - Пятница, 09.12.2022, 16:06
 
ntvgjhfnjДата: Суббота, 16.03.2024, 21:24 | Сообщение # 4
Лейтенант
Группа: Проверенные
Сообщений: 59
Репутация: 1
Статус: Offline
Переделанный вариант Менеджера задач. пример Game
Прикрепления: taskmanager.rar (6.5 Kb)


polopok
 
Форум » Freebasic » Исходники » Псевдо ИИ (Инструменты создания искусственного интеллекта)
  • Страница 1 из 1
  • 1
Поиск: