Advertisement
Guest User

GameOfLife @ GPT-4

a guest
Mar 14th, 2023
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 5 1.66 KB | Software | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <body>
  4.  
  5. <h2>GameOfLife</h2>
  6.  
  7. <p id="demo"></p>
  8.  
  9. <script>
  10.  
  11. class GameOfLife {
  12.   constructor(w, h) {
  13.     this.w = w;
  14.     this.h = h;
  15.     this.board = Array.from({ length: h }, () => Array(w).fill(0).map(() => Math.random() > 0.8 ? 1 : 0));
  16.   }
  17.  
  18.   setCell(x, y, v) { this.board[y][x] = v; }
  19.   getCell(x, y) { return x < 0 || x >= this.w || y < 0 || y >= this.h ? 0 : this.board[y][x]; }
  20.   countNeighbors(x, y) {
  21.     let count = 0;
  22.     for (let j = -1; j <= 1; j++) for (let i = -1; i <= 1; i++) count += j || i ? this.getCell(x + i, y + j) : 0;
  23.    return count;
  24.  }
  25.  
  26.  step() {
  27.    this.board = this.board.map((row, y) => row.map((cell, x) => {
  28.       const n = this.countNeighbors(x, y);
  29.       return cell ? (n === 2 || n === 3 ? 1 : 0) : (n === 3 ? 1 : 0);
  30.     }));
  31.   }
  32.  
  33.   draw(canvas) {
  34.     const ctx = canvas.getContext('2d');
  35.     const cellSize = Math.min(canvas.width / this.w, canvas.height / this.h);
  36.     ctx.clearRect(0, 0, canvas.width, canvas.height);
  37.     for (let y = 0; y < this.h; y++) {
  38.      for (let x = 0; x < this.w; x++) {
  39.        if (this.getCell(x, y)) {
  40.          ctx.fillRect(x * cellSize, y * cellSize, cellSize, cellSize);
  41.        }
  42.      }
  43.    }
  44.  }
  45. }
  46.  
  47. // Пример использования
  48. const gol = new GameOfLife(50, 50);
  49.  
  50. // Создаем и настраиваем canvas
  51. const canvas = document.createElement('canvas');
  52. canvas.width = 600;
  53. canvas.height = 600;
  54. document.body.appendChild(canvas);
  55.  
  56. // Отображаем клетки на canvas
  57. function update() {
  58.  gol.draw(canvas);
  59.  gol.step();
  60.  setTimeout(update, 200);
  61. }
  62. update();
  63.  
  64. </script>
  65.  
  66. </body>
  67. </html>
  68.  
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement