Game of Life

Developer
Size
5,070 Kb
Views
24,288

How do I make an game of life?

What is a game of life? How do you make a game of life? This script and codes were developed by Alexandr on 04 December 2022, Sunday.

Game of Life Previews

Game of Life - Script Codes HTML Codes

<!DOCTYPE html>
<html >
<head> <meta charset="UTF-8"> <title>Game of Life</title> <link rel="stylesheet" href="css/style.css">
</head>
<body>
<canvas id="life"></canvas>
<button class="but" id="create" onclick="window['location'].reload(true);">CREATE</button>
<button class="but" id="stop" onclick="times=times_till_end;">STOP</button> <script src="js/index.js"></script>
</body>
</html>

Game of Life - Script Codes CSS Codes

body { background-color: #001;
}
canvas#life { background-color: #000; border: 5px solid #000; margin: 20px 100px;
}
button.but { display: block; position: absolute; width: 200px; height: 50px; border-radius: 10px; border: 1px ridge #fff; background: transparent; color: #fff; font-size: 20px; cursor: pointer; opacity: 0.3;
}
button#create { bottom: calc(5% + 60px); left: 50px;
}
button#stop { bottom: 5%; left: 50px;
}

Game of Life - Script Codes JS Codes

var variant = 0; // 0 - 7
var size = 5; //размер клетки 2 - 30
var delay = 100; // задержка в милисекундах (10-1000)
var rarefaction = 12;
var too_few = 2; // 2 или 3. Если соседей меньше too_few, то клетка гибнет.
var birth = 3; // условие рождения
var too_much = 3; // 3 или 4. Если соседей больше too_mush, клетка гибнет.
var w = 1700, h = 1000; //размеры окна
//var w = 1900, h = 1000; //размеры окна
var times_till_end = 15000;
if (variant==1) {size = 4; rarefaction = 3; too_few =3; too_much=4; birth = 3;}
if (variant==2) {size = 5; rarefaction = 1; too_few =3; too_much=4; birth = 3;}
if (variant==3) {size = 5; rarefaction = 40; too_few =2; too_much=4; birth = 3;}
if (variant==4) {size = 5; rarefaction = 21; too_few =2; too_much=3; birth = 3;}
if (variant==5) {size = 2; rarefaction = 21; too_few =2; too_much=3; birth = 3;}
if (variant==6) {size = 2; rarefaction = 27; too_few =1; too_much=3; birth = 3;}
if (variant==7) {size = 4; rarefaction = 9; too_few =2; too_much=3; birth = 3;}
var nw = Math.floor(w/size), nh = Math.floor(h/size); //размеры массива world
var world =[], newworld=[];
var list = [];
console.log ("nw = "+nw+" nh = "+nh);
//var window = document.getElementById("life");
ctx = life.getContext('2d'); life.width = w; life.height = h;	ctx.fillStyle = "#dfe"; // белые - это жизнь	ctx.font = "bold 20px Arial";
function circ(x,y,r){
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI*2, false);
ctx.closePath();
ctx.fill();
}
function rand(x){ // x - соотношение ч и б точек, 2 означает, что ч в 2 раза больше чем б.	var lim = 1-(1/(1+x));	var k=0;	for (var i=0; i<nw; i++){	world[i]=[];	for (var j=0; j<nh; j++) {	//cell = {}; cell.x=i; cell.y=j;	if (Math.random()>lim) world[i][j]=1; else world[i][j]=0;// заполняю массив живыми и мёртвыми клетками.	list[k]=[]; list[k][0]=i; list[k][1]=j; k++;	}}	//alert (world[5][5]);	//alert ("world.width"+k);	//console.log ("list.length = "+list.length+" rand(x) worked.");
}
function draw_rects(){	ctx.clearRect(0, 0, w, h);	for (var i=0; i<list.length; i++) {	//obj = world[list[i]];	//obj = list[i];	if (world[list[i][0]][list[i][1]]==1) ctx.fillRect(list[i][0]*size, list[i][1]*size, size, size);	}
}
function draw_circs(){	ctx.clearRect(0, 0, w, h);	for (var i=0; i<list.length; i++) {	//obj = list[i];	if (world[list[i][0]][list[i][1]]==1) circ(list[i][0]*size, list[i][1]*size, size/2);	}
}
function all_in_list(){	//console.log ("Начало all_in_list.");	var k=0;	//world = []; world = newworld.slice();	world = []; world = clone_arr(newworld);	for (var i=0; i<nw; i++) {	for (var j=0; j<nh; j++) {	list[k][0]=i;list[k][1]=j; k++;	//list.push(newworld[i][j]);
}}
//console.log ("В списке "+k+" клеток."+" all_in_list() worked.");
}
function neighbors(x,y){	//var nei=[];	var nei=0;	var k=0;	//var x=cel.x, y=cel.y; //alert ("y="+y);	//nei['num']=0; //alert( "Длина nei "+nei.length);	var change=false;	for (var i=-1; i<2; i++) {	xx=x+i; if (xx < 0) xx=xx+nw; if (xx >= nw) xx=xx-nw; //alert( "xx="+xx);	for (var j=-1; j<2; j++) {	yy=y+j; if (yy < 0) yy=yy+nh; if (yy >= nh) yy=yy-nh;	//nei[k]=world[xx][yy]; // alert("bbfffffffffff");	if (world[xx][yy]!=newworld[xx][yy]) change=true;	if (i!=0 || j!=0) {	if(world[xx][yy]==1) {nei++;} // подсчёт живых соседей	k++;} //если это сама клетка, а не сосед, не увеличивая k, переписываем ячейку nei[4]	}}	if (change) {nei=nei+0.1;} // если у соседей и самой частицы нет изменений, передаём отриц. число соседей.	//console.log("Конец neighbors(cel).");	//if ((x==0 || x==nw) && (y==0 ||y==nh)) nei['num']=0;	return nei;
}
function step(){	var factor=false;	//alert("Begin_step");	newworld = []; newworld = clone_arr(world);	//a = [[2,3],[35,46]]; b = clo(a); a[1][0]=8; alert(b[1][0]);
//a[5][5] = 7; a[5][5] = 67;a = []; alert(b[5][5]);
//alert ("Начало step()."+world.length);	//for (var i=0; i<list.length; i++){	var neig;	for (var i=0; i<list.length; i++) {	neig = neighbors(list[i][0],list[i][1]);	if (!factor && neig!=Math.floor(neig)) factor = true;	var num_alive_neig = Math.floor(neig);	if (num_alive_neig==birth) {newworld[list[i][0]][list[i][1]]=1;} // зарождение	if (num_alive_neig<too_few || num_alive_neig>too_much) {newworld[list[i][0]][list[i][1]]=0;} // смерть
};	if (!factor) times=times_till_end; //если нет изменений, останавливаем скрипт.
}
function eq_world(arr,x,y){	for (var i = 0; i<arr.length; i++){	world[x+arr[i][0]][y+arr[i][1]]=1;
}}
function create_glider(x,y){ // создание организма "планер"	var arr = [[1,0],[2,1],[0,2],[1,2],[2,2]];	eq_world(arr,x,y);
}
function create_signal_lights(x,y) { // создание организма "сигнальные огни"	var arr = [[0,0],[1,0],[2,0]];	eq_world(arr,x,y);
}
function create_glider_gun(x,y) {	var arr = [[0,0],[1,0],[0,1],[1,1], [34,-1],[35,-1],[34,-2],[35,-2], [11,0],[11,-1],[11,1], [15,0],[15,-1],[15,1], [16,0],[16,-1],[16,1], [12,-2],[12,2], [13,-3],[13,3], [14,-2],[14,2], [21,-1],[21,-2],[21,-3], [22,0],[22,-1],[22,-3],[22,-4],[23,0],[23,-1],[23,-3],[23,-4], [24,0],[24,-1],[24,-3],[24,-4], [24,-2], [25,1],[25,0],[25,-4],[25,-5],];	for(var i=-2; i<37; i++){	for(var j=-7; j<7; j++){	world[x+i][x+j]=0;	}}	eq_world(arr,x,y);
}
function clone_arr(arr) { // ф-я создания независимой копии 2мерного массива (массива массивов)	var newarr = [];	for (var i=0; i<arr.length; i++){	newarr[i]=[];	for (var j=0; j<arr[i].length; j++){	newarr[i][j]=arr[i][j];	}}	return newarr;
}
rand(rarefaction);
create_glider(Math.floor(Math.random()*nw), Math.floor(Math.random()*nh)); // запуск "планера" в случайном месте
create_glider(nw-10, 10); // создаю ещё планер
create_glider_gun(10,10);
//create_signal_lights(40,10); // создаю сигнальный огонь
var times=0;
(function life(){
id = setInterval(function() {	draw_circs();	step(); //alert("step");	all_in_list(); //alert("list");	times++; //alert("times = "+times);	if (times>=times_till_end){clearInterval(id); //alert ("END.")};	};	//if (world.join(';')==newworld.join(';'){clearInterval(id); alert ("The end. Мир не развивается.");
}, delay);
})(); // ctx.strokeRect(15, 15, 266, 266); // ctx.strokeRect(18, 18, 260, 260); // ctx.fillRect(20, 20, 256, 256); // for (i = 0; i < 8; i += 2) // for (j = 0; j < 8; j += 2) { // ctx.clearRect(20 + i * 32, 20 + j * 32, 32, 32); // ctx.clearRect(20 + (i + 1) * 32, 20 + (j + 1) * 32, 32, 32); // }
Game of Life - Script Codes
Game of Life - Script Codes
Home Page Home
Developer Alexandr
Username Aortan
Uploaded December 04, 2022
Rating 3
Size 5,070 Kb
Views 24,288
Do you need developer help for Game of Life?

Find the perfect freelance services for your business! Fiverr's mission is to change how the world works together. Fiverr connects businesses with freelancers offering digital services in 500+ categories. Find Developer!

Alexandr (Aortan) Script Codes
Create amazing love letters with AI!

Jasper is the AI Content Generator that helps you and your team break through creative blocks to create amazing, original content 10X faster. Discover all the ways the Jasper AI Content Platform can help streamline your creative workflows. Start For Free!