-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.htm
413 lines (331 loc) · 15 KB
/
game.htm
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Game of life</title>
<style>
body{
margin: 0px;
padding: 0px;
}
canvas#gamecanvas{
width: 100vw;
height: 100vh;
}
</style>
</head>
<body>
<canvas id="gamecanvas"></canvas>
<script>
class GameInput{
constructor(canvas, left, top, right, bottom, hCells, vCells){
}
addPlayPauseListener(listener){
// Function 'listener()' will be called on play/pause event.
// Remove these comments once implemented.
}
addCellClickListener(listener){
// Function 'listener(row, col)' will be called on cell click.
// It will be passed the cell row as arg1 and column as arg2.
// Remove these comments once implemented.
}
}
class GameRenderer{
ClearCanvas(clearColor = [0.0, 0.0, 0.0, 1.0]){
this.gl.clearColor(clearColor[0],clearColor[1],clearColor[2],clearColor[3])
this.gl.clear(this.gl.COLOR_BUFFER_BIT | this.gl.DEPTH_BUFFER_BIT)
}
//Draw an array of clip space vertices as triangles to screen
DrawVertArray(verts, color){
this.gl.bufferData(this.gl.ARRAY_BUFFER, new Float32Array(verts), this.gl.DYNAMIC_DRAW);
this.gl.uniform4fv(this.programInfo.uniformLocations.Color,color);
this.gl.drawArrays(this.gl.TRIANGLES, 0, verts.length / 2);
}
constructor(canvas, left, top, right, bottom, hCells, vCells){
this.hCells = hCells
this.vCells = vCells
const obj = this
const width = canvas.width = right - left
const height = canvas.height = bottom - top
this.gl = canvas.getContext("webgl",{preserveDrawingBuffer: true})
if (this.gl === null){
alert("Unable to initialize WebGL. Your browser or machine may not support it.")
return
}
this.Colors = {
background: [0.1,0.1,0.1,1],
grid: [0.3,0.3,0.3,1],
cell: [1,1,1,1]
}
const VertexShaderSource = `
attribute vec4 aVertexPosition;
void main(){
gl_Position = aVertexPosition;
}
`
const FragmentShaderSource = `
uniform mediump vec4 uColor;
void main(){
gl_FragColor = uColor;
}
`
// Creates a shader of the given type, uploads the source and
// compiles it
function createShader(type, source){
const shader = obj.gl.createShader(type)
// Send the source to the shader object
obj.gl.shaderSource(shader, source)
obj.gl.compileShader(shader)
// See if it compiled successfully
if (!obj.gl.getShaderParameter(shader, obj.gl.COMPILE_STATUS))
{
alert(`An error occurred compiling the shaders: ${obj.gl.getShaderInfoLog(shader)}`)
obj.gl.deleteShader(shader)
return null
}
return shader;
}
// Create a shader program, attach vertex and fragment shaders and link program
function initShaderProgram(vsSource, fsSource){
const vertexShader = createShader(obj.gl.VERTEX_SHADER, vsSource)
const fragmentShader = createShader(obj.gl.FRAGMENT_SHADER, fsSource)
// Create the shader program
const shaderProgram = obj.gl.createProgram()
obj.gl.attachShader(shaderProgram, vertexShader)
obj.gl.attachShader(shaderProgram, fragmentShader)
obj.gl.linkProgram(shaderProgram)
// If linking the shader program failed, alert
if (!obj.gl.getProgramParameter(shaderProgram, obj.gl.LINK_STATUS))
{
alert(`Unable to initialize the shader program: ${obj.gl.getProgramInfoLog(shaderProgram)}`)
return null
}
return shaderProgram
}
const shaderProgram = initShaderProgram(VertexShaderSource, FragmentShaderSource)
// Info needed to use the shader program
this.programInfo = {
program: shaderProgram,
attribLocations: {
vertexPosition: this.gl.getAttribLocation(shaderProgram, "aVertexPosition"),
},
uniformLocations: {
Color: this.gl.getUniformLocation(shaderProgram, "uColor"),
},
}
// Create a buffer for vertex positions
function initPositionBuffer(){
const positionBuffer = obj.gl.createBuffer()
// Select the positionBuffer as the one to apply buffer
// operations to from here out
obj.gl.bindBuffer(obj.gl.ARRAY_BUFFER, positionBuffer)
// Create an array of positions for a test shape.
const positions = [0.5, 0.0, 0.0, 0.5, 0.0, -0.5]
// Pass the list of positions into WebGL to build the
// shape by creating a Float32Array from the
// JavaScript array, then use it to fill the current buffer
obj.gl.bufferData(obj.gl.ARRAY_BUFFER, new Float32Array(positions), obj.gl.DYNAMIC_DRAW)
return positionBuffer
}
//Create required buffers
function initBuffers(){
const positionBuffer = initPositionBuffer()
return {
position: positionBuffer,
}
}
// Tell WebGL how to pull out the positions from the position
// buffer into the vertexPosition attribute
function setPositionAttribute(buffers, programInfo){
const numComponents = 2 // Pull out 2 values per iteration
const type = obj.gl.FLOAT // The data in the buffer are 32bit floats
const normalize = false // Don't normalize
const stride = 0 // Number of bytes to get from one set of values to the next
// 0 = use type and numComponents above
const offset = 0 // Number of bytes inside the buffer to start from
obj.gl.bindBuffer(obj.gl.ARRAY_BUFFER, buffers.position)
obj.gl.vertexAttribPointer(
programInfo.attribLocations.vertexPosition,
numComponents,
type,
normalize,
stride,
offset,
)
obj.gl.enableVertexAttribArray(programInfo.attribLocations.vertexPosition)
}
function initDraw(programInfo, buffers){
obj.gl.clearDepth(1.0) // Clear everything
obj.gl.enable(obj.gl.DEPTH_TEST) // Enable depth testing
obj.gl.depthFunc(obj.gl.LEQUAL) // Near things obscure far things
obj.ClearCanvas(obj.Colors.background)
// Set up vertex attribute array
setPositionAttribute(buffers, programInfo)
// Tell WebGL to use our program when drawing
obj.gl.useProgram(programInfo.program)
obj.gl.uniform4fv(programInfo.uniformLocations.Color,[1.0,1.0,1.0,1.0])
}
const buffers = initBuffers();
initDraw(this.programInfo, buffers);
let smallerLen = (width > height) ? height : width
this.WorldToClipSpace = [smallerLen * 2 / width, smallerLen * 2 / height]
this.WorldSize = [width / smallerLen, height / smallerLen]
this.PixelSize = 1 / smallerLen
}
draw(buffer){
//Clip coordinates go from (-1,1)(top left) to (1,-1)(bottom right)
const cellHalfSize = [1 / this.hCells, 1 / this.vCells]
const baseVerts = [-cellHalfSize[0],cellHalfSize[1],cellHalfSize[0],
cellHalfSize[1],cellHalfSize[0],-cellHalfSize[1],
cellHalfSize[0],-cellHalfSize[1],-cellHalfSize[0],
-cellHalfSize[1],-cellHalfSize[0],cellHalfSize[1]]
for(var row=0; row < this.vCells; row++){
for(var col=0; col < this.hCells; col++){
let offset = [-1 + (col * 2 + 1) * cellHalfSize[0], 1 - (row * 2 + 1) * cellHalfSize[1]]
let verts = [baseVerts[0] + offset[0],baseVerts[1] + offset[1],baseVerts[2] + offset[0],
baseVerts[3] + offset[1],baseVerts[4] + offset[0],baseVerts[5] + offset[1],
baseVerts[6] + offset[0],baseVerts[7] + offset[1],baseVerts[8] + offset[0],
baseVerts[9] + offset[1],baseVerts[10] + offset[0],baseVerts[11] + offset[1]]
if (buffer[row][col] > 0){
this.DrawVertArray(verts, this.Colors.cell)
}
else{
this.DrawVertArray(verts, this.Colors.background)
}
}
}
}
}
function makeGameRendererFor(canvas, width, height, cellSize){
function cellsInLength(length, cellSize){
return Math.floor(length / cellSize)
}
function clampToSize(number, size){
return number - ( number % size)
}
const windowWidth = clampToSize(width, cellSize)
const windowHeight = clampToSize(height, cellSize)
const hMargin = width - windowWidth
const vMargin = height - windowHeight
const left = Math.floor(hMargin / 2)
const top = Math.floor(vMargin / 2)
const right = left + windowWidth
const bottom = top + windowHeight
const hCells = cellsInLength(windowWidth, cellSize)
const vCells = cellsInLength(windowHeight, cellSize)
return {
renderer: new GameRenderer(
canvas, left, top, right, bottom, hCells, vCells
),
hCells: hCells, vCells: vCells
}
}
class GameOfLife{
#hCells
#vCells
#grid
getGrid(){
return this.#grid
}
#setGrid(grid){
this.#grid = grid
}
#clearGrid(){
const clearGrid = []
for(var row=0; row < this.#vCells; row++){
const rowArray = []
for(var col=0; col < this.#hCells; col++){
rowArray.push(0)
}
clearGrid.push(rowArray)
}
this.#setGrid(clearGrid)
}
#seedGrid(){
const grid = this.getGrid()
for(var row=0; row < this.#vCells; row++){
for(var col=0; col < this.#hCells; col++){
grid[row][col] = Math.round(Math.random())
}
}
}
constructor(hCells, vCells){
this.#hCells = hCells
this.#vCells = vCells
this.#clearGrid(vCells, hCells)
this.#seedGrid()
}
#calculateNextCellState(row, col){
const grid = this.getGrid()
let topIndex = row - 1
let bottomIndex = row + 1
if(topIndex < 0){
topIndex = topIndex + this.#vCells
}
else if(bottomIndex >= this.#vCells){
bottomIndex = bottomIndex - this.#vCells
}
let leftIndex = col - 1
let rightIndex = col + 1
if(leftIndex < 0){
leftIndex = leftIndex + this.#hCells
}
else if(rightIndex >= this.#hCells){
rightIndex = rightIndex - this.#hCells
}
let aliveNeighbors = 0
aliveNeighbors += grid[topIndex][leftIndex]
aliveNeighbors += grid[topIndex][col]
aliveNeighbors += grid[topIndex][rightIndex]
aliveNeighbors += grid[row][leftIndex]
aliveNeighbors += grid[row][rightIndex]
aliveNeighbors += grid[bottomIndex][leftIndex]
aliveNeighbors += grid[bottomIndex][col]
aliveNeighbors += grid[bottomIndex][rightIndex]
let cellState = grid[row][col]
if(aliveNeighbors === 3){
cellState = 1
}
else if(aliveNeighbors !== 2){
cellState = 0
}
return cellState
}
calculateNextGrid(){
const newGrid = []
for(var row=0; row < this.#vCells; row++){
const rowArray = []
for(var col=0; col < this.#hCells; col++){
const cellValue = this.#calculateNextCellState(
row, col
)
rowArray.push(cellValue)
}
newGrid.push(rowArray)
}
this.#setGrid(newGrid)
return newGrid
}
}
function startGame(){
const gameCanvas = document.getElementById("gamecanvas")
const { renderer, hCells, vCells } = makeGameRendererFor(
gameCanvas, window.innerWidth, window.innerHeight, 16
)
const game = new GameOfLife(hCells, vCells)
renderer.draw(game.getGrid())
const frameDuration = 1000 / 60
setInterval(
function (){
requestAnimationFrame(function (){
renderer.draw(game.calculateNextGrid())
})
},
frameDuration
)
}
startGame()
</script>
</body>
</html>