main.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // не Counter Strike, но решила поиграть в жизнь
  2. var canvas = document.getElementById('c1');
  3. var ctx = canvas.getContext('2d');
  4. var mas = [];
  5. var count = 0;
  6. var timer;
  7. canvas.onclick = function(e) {
  8. var x = e.offsetX;
  9. var y = e.offsetY;
  10. console.log(x);
  11. console.log(y);
  12. x = Math.floor(x/10);
  13. y = Math.floor(y/10);
  14. mas[y][x]=1;
  15. console.log(mas);
  16. drawField();
  17. }
  18. function goLife() {
  19. var n=50, m=50;
  20. for(var i=0; i<m; i++) {
  21. mas[i]=[];
  22. for(var j=0; j<n; j++) {
  23. mas[i][j]=0;
  24. }
  25. }
  26. }
  27. goLife();
  28. function drawField() {
  29. ctx.clearRect(0, 0, 500, 500);
  30. for(var i=0; i<50; i++) {
  31. for(var j=0; j<50; j++) {
  32. if(mas[i][j]==1) {
  33. ctx.fillRect(j*10, i*10, 10, 10);
  34. }
  35. }
  36. }
  37. }
  38. function startLife(){
  39. //моделирование жизни
  40. var mas2 = [];
  41. for (var i=0; i<50; i++){
  42. mas2[i]=[];
  43. for (var j=0; j<50; j++){
  44. var neighbors = 0;
  45. if (mas[fpm(i)-1][j]==1) neighbors++; //up
  46. if (mas[i][fpp(j)+1]==1) neighbors++; //right
  47. if (mas[fpp(i)+1][j]==1) neighbors++; //bottom
  48. if (mas[i][fpm(j)-1]==1) neighbors++; //left
  49. if (mas[fpm(i)-1][fpp(j)+1]==1) neighbors++;
  50. if (mas[fpp(i)+1][fpp(j)+1]==1) neighbors++;
  51. if (mas[fpp(i)+1][fpm(j)-1]==1) neighbors++;
  52. if (mas[fpm(i)-1][fpm(j)-1]==1) neighbors++;
  53. (neighbors==2 || neighbors==3) ? mas2[i][j]=1 : mas2[i][j]==0;
  54. }
  55. }
  56. mas = mas2;
  57. drawField();
  58. count++;
  59. document.getElementById('count').innerHTML = count;
  60. timer = setTimeout(startLife, 500);
  61. }
  62. function fpm(i) {
  63. if(i==0) return 50;
  64. else return i;
  65. }
  66. function fpp(i) {
  67. if(i==49) return -1;
  68. else return i;
  69. }
  70. document.getElementById('start').onclick = startLife;