Advertisement
Guest User

Minesweeper cover

a guest
Jun 20th, 2019
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let size = 40
  2. let edge = 3
  3. let cells = []
  4.  
  5. class Cell {
  6.   constructor(x, y) {
  7.     this.x = x
  8.     this.y = y
  9.     this.hidden = true
  10.   }
  11.   draw() {
  12.     if (this.hidden) {
  13.       fill(200, 200, 200)
  14.       triangle(this.x, this.y,
  15.                this.x + size, this.y,
  16.                this.x, this.y + size)
  17.       fill(150, 150, 150)
  18.       triangle(this.x + size, this.y + size,
  19.                this.x + size, this.y,
  20.                this.x, this.y + size)
  21.       fill(175, 175, 175)
  22.       square(this.x + edge, this.y + edge,
  23.              size - 2 * edge)
  24.     } else {
  25.       noFill()
  26.       stroke(175)
  27.       strokeWeight(0.5)
  28.       square(this.x, this.y,
  29.             size)
  30.       noStroke()
  31.     }
  32.   }
  33.   show() {
  34.     this.hidden = false
  35.   }
  36. }
  37.  
  38. class Mine extends Cell {
  39.   constructor(x, y) {
  40.     super(x, y)
  41.     this.observers = []
  42.   }
  43.   addObserver(obs) {
  44.     this.observers.push(obs)
  45.   }
  46.   show() {
  47.     super.show()
  48.     for (let obs of this.observers) {
  49.       if (obs.hidden)
  50.         obs.show()
  51.     }
  52.   }
  53. }
  54.  
  55. class Model {
  56.   constructor(w, h, n=10) {
  57.     this.cells = []
  58.     this.mines = []
  59.     for (let i = 0; i < w; i+=size) {
  60.       this.cells.push([])
  61.       for (let j = 0; j < h; j+=size)
  62.         this.cells[i / size].push(new Cell(i, j))
  63.     }
  64.     let i = 0
  65.     while (i < n) {
  66.       let x = Math.floor(random() * w / size)
  67.       let y = Math.floor(random() * h / size)
  68.       let bx = x * size
  69.       let by = y * size
  70.       if (!(this.cells[x][y] instanceof Mine)) {
  71.         this.cells[x][y] = new Mine(bx, by)
  72.         for (let mine of this.mines) {
  73.           mine.addObserver(this.cells[x][y])
  74.           this.cells[x][y].addObserver(mine)
  75.         }
  76.         this.mines.push(this.cells[x][y])
  77.         i++
  78.       }
  79.     }
  80.   }
  81. }
  82.  
  83. let modelo
  84.  
  85. function mousePressed() {
  86.   let x = Math.floor(mouseX / size)
  87.   let y = Math.floor(mouseY / size)
  88.   if (x < modelo.cells.length && y < modelo.cells[0].length)
  89.     modelo.cells[x][y].show()
  90. }
  91.  
  92. function setup() {
  93.   createCanvas(400, 400);
  94.   noStroke()
  95.   modelo = new Model(width, height)
  96. }
  97.  
  98. function draw() {
  99.   background(205)
  100.   for (let row of modelo.cells) {
  101.     for (let cell of row)
  102.       cell.draw()
  103.   }
  104. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement