-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSimulation.js
120 lines (97 loc) · 3.09 KB
/
Simulation.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// Simulation class
function Simulation(width, height, size)
{
this.size = size || 10;
// Create a div
div =document.createElement('div');
// Place holder for status text
this.status =document.createElement('div');
$(this.status).css({"float": "clear"});
//$(this.status).html("Status")
$(this.status).appendTo(div)
// Create canvas and rendering context
canvas =document.createElement('canvas');
this.ctx = canvas.getContext("2d");
$(canvas).appendTo(div);
var simdiv = $("#simulations");
$(div).css({"float": "left"});
$(div).appendTo(simdiv);
// Defines a local grid of y rows and x columns
this.x = width;
this.y = height;
this.ctx.canvas.width = this.x * this.size * 1.2;
this.ctx.canvas.height = this.y * this.size * 1.2;
// Variables defined for movement in animation
this.flipx = 0;
this.flipy = 0;
this.grid = new Array(this.y);
for (var i = 0; i < this.y; i++)
{
this.grid[i] = new Array(this.x);
}
// First color is background color and the rest are used
this.palette = ["#FFFFFF" , "#E768AD", "#6D87D6"];
// this.Init();
};
Simulation.prototype.Draw = function()
{
// Draws the simulation
for(var j = 0; j < this.y; j++)
{
for(var i = 0; i < this.x; i++)
{
// Select the colors from the pallette
if (this.grid[j][i] > this.palette.length - 1 )
{
this.ctx.fillStyle = this.palette[0];
}
else
{
this.ctx.fillStyle = this.palette[this.grid[j][i]]
}
//console.log(ctx.fillStyle);
this.ctx.fillRect(i*this.size, j*this.size, this.size, this.size);
}
}
};
Simulation.prototype.Init = function()
{
// Defaults to random values between 1 and 2
// Can inherit and customize this
for(var j = 0; j < this.y; j++)
{
for(var i = 0; i < this.x; i++)
{
this.grid[j][i] = Math.floor(Math.random()*2) + 1;
//console.log(this.grid[i][j])
}
}
};
Simulation.prototype.Flip = function(i,j)
{
if (this.grid[i][j] === 1)
{
this.grid[i][j] = 2;
}
else
{
this.grid[i][j] = 1;
}
}
Simulation.prototype.Animate = function(ctx)
{
// Flip a pixel and move in random direction
this.Flip(this.flipx, this.flipy);
// Get the random direction to move
var dirx = Math.floor(Math.random()*3) - 1;
var diry = Math.floor(Math.random()*3) - 1;
// Flip a pixel and move in random direction
this.flipx = this.flipx + dirx;
this.flipy = this.flipy + diry;
// Reset it if it goes too far
if(this.flipx >= this.x) this.flipx = 0;
if(this.flipx < 0) this.flipx = this.x-1;
if(this.flipy >= this.y) this.flipy = 0;
if(this.flipy < 0) this.flipy = this.y-1;
this.Draw(ctx, 15);
}