Browse Source

HW<canvas-game> done

Евгения Акиншина 3 years ago
parent
commit
3f419b20ab
3 changed files with 102 additions and 0 deletions
  1. 6 0
      canvas-game of life/css/style.css
  2. 17 0
      canvas-game of life/index.html
  3. 79 0
      canvas-game of life/js/main.js

+ 6 - 0
canvas-game of life/css/style.css

@@ -0,0 +1,6 @@
+#c1 {
+    width: 500px;
+    height: 500px;
+    border: 3px solid black;
+    margin: 40px;
+}

+ 17 - 0
canvas-game of life/index.html

@@ -0,0 +1,17 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta http-equiv="X-UA-Compatible" content="IE=edge">
+    <meta name="viewport" content="width=\, initial-scale=1.0">
+    <link rel="stylesheet" href="css/normalize.css">
+    <link rel="stylesheet" href="css/style.css">
+    <title>HW21</title>
+</head>
+<body>
+    <canvas id='c1' width=500 height=500></canvas>
+    <p>Количество циклов: <span id="count">0</span></p>
+    <button id="start">Start</button>
+    <script src='js/main.js'></script>
+</body>
+</html>

+ 79 - 0
canvas-game of life/js/main.js

@@ -0,0 +1,79 @@
+// не Counter Strike, но решила поиграть в жизнь
+
+var canvas = document.getElementById('c1');
+var ctx = canvas.getContext('2d');
+var mas = [];
+var count = 0;
+var timer;
+
+canvas.onclick = function(e) {
+    var x = e.offsetX;
+    var y = e.offsetY;
+    console.log(x);
+    console.log(y);
+    x = Math.floor(x/10);
+    y = Math.floor(y/10);
+    mas[y][x]=1;
+    console.log(mas);
+    drawField();
+}
+
+function goLife() {
+    var n=50, m=50;
+    for(var i=0; i<m; i++) {
+        mas[i]=[];
+        for(var j=0; j<n; j++) {
+            mas[i][j]=0;
+        }
+    }
+}
+
+goLife();
+
+function drawField() {
+    ctx.clearRect(0, 0, 500, 500);
+    for(var i=0; i<50; i++) {
+        for(var j=0; j<50; j++) {
+            if(mas[i][j]==1) {
+                ctx.fillRect(j*10, i*10, 10, 10);
+            }
+        }
+    }
+}
+
+function startLife(){
+//моделирование жизни
+	var mas2 = [];
+	for (var i=0; i<50; i++){
+		mas2[i]=[];
+		for (var j=0; j<50; j++){
+			var neighbors = 0;
+			if (mas[fpm(i)-1][j]==1) neighbors++; //up
+			if (mas[i][fpp(j)+1]==1) neighbors++; //right
+			if (mas[fpp(i)+1][j]==1) neighbors++; //bottom
+			if (mas[i][fpm(j)-1]==1) neighbors++; //left
+			if (mas[fpm(i)-1][fpp(j)+1]==1) neighbors++;
+			if (mas[fpp(i)+1][fpp(j)+1]==1) neighbors++;
+			if (mas[fpp(i)+1][fpm(j)-1]==1) neighbors++;
+			if (mas[fpm(i)-1][fpm(j)-1]==1) neighbors++;
+			(neighbors==2 || neighbors==3) ? mas2[i][j]=1 : mas2[i][j]==0;
+		}
+	}
+	mas = mas2;
+	drawField();
+	count++;
+	document.getElementById('count').innerHTML = count;
+	timer = setTimeout(startLife, 500);
+}
+
+function fpm(i) {
+    if(i==0) return 50;
+    else return i;
+}
+
+function fpp(i) {
+    if(i==49) return -1;
+    else return i;
+}
+
+document.getElementById('start').onclick = startLife;