Commit d0554396 authored by Hubert Denkmair's avatar Hubert Denkmair
Browse files

add ObjectPool for segments

parent 8ebe1f89
......@@ -33,6 +33,10 @@ function GameVisualization(assets, snakeMoveStrategy, container)
this.mainStage = new PIXI.Container();
this.app.stage.addChild(this.mainStage);
this.segmentPool = new ObjectPool(function() {
return new SnakeSegment(this.txBody);
}, this, 10000);
}
GameVisualization.prototype.Run = function()
......@@ -63,7 +67,7 @@ GameVisualization.prototype.CreateSnake = function(bot)
{
this.ego_id = bot.id;
}
let snake = new Snake(this.txHead, this.txBody, bot.name, bot.color, this.world_size_x, this.world_size_y);
let snake = new Snake(this.txHead, this.segmentPool, bot.name, bot.color, this.world_size_x, this.world_size_y);
snake.snake_id = bot.id;
snake.db_id = bot.db_id;
this.snakes[bot.id] = snake;
......
"use strict";
function ObjectPool(allocFunc, allocThis, initialSize)
{
this.allocFunc = allocFunc;
this.allocThis = allocThis;
this.pool = [];
this.usedCount = 0;
for (let i=0; i<initialSize; i++)
{
this.pool.push(allocFunc.call(this.allocThis));
}
}
ObjectPool.prototype.get = function()
{
this.usedCount++;
if (this.pool.length>0)
{
return this.pool.pop();
}
return this.allocFunc.call(this.allocThis);
};
ObjectPool.prototype.free = function(element)
{
this.usedCount--;
this.pool.push(element);
};
"use strict";
function Snake(headTexture, bodyTexture, name, colorScheme, world_size_x, world_size_y)
function Snake(headTexture, segmentPool, name, colorScheme, world_size_x, world_size_y)
{
this._name = name;
this._colorScheme = colorScheme;
this._bodyTexture = bodyTexture;
this._segmentPool = segmentPool;
this.textureRadius = headTexture.width / 2;
this.spriteScale = 0.1;
......@@ -56,11 +56,12 @@ Snake.prototype.SetLength = function(newLength)
{
let seg = this._segments.pop();
this._segmentContainer.removeChild(seg.GetSprite());
this._segmentPool.free(seg);
}
for (let i=this.GetLength(); i<newLength; i++)
{
let segment = new SnakeSegment(this._bodyTexture);
let segment = this._segmentPool.get();
if (this._segments.length > 0)
{
segment.ClonePosition(this._segments[this._segments.length-1]);
......
......@@ -2,6 +2,7 @@
<script src="{% static "visualization/lib/pixi.min.js" %}"></script>
<script src="{% static "visualization/lib/websocket/reconnecting-websocket.min.js" %}"></script>
<script src="{% static "visualization/ParticleGeoMap.js" %}"></script>
<script src="{% static "visualization/ObjectPool.js" %}"></script>
<script src="{% static "visualization/SnakeSegment.js" %}"></script>
<script src="{% static "visualization/Snake.js" %}"></script>
<script src="{% static "visualization/FoodSprite.js" %}"></script>
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment