Assignment 3: Sudoku using OOP

Concept

For this assignment, I decided to generate one of my favorite games, Sudoku. The board is generated, styled, and displayed with the help of the ‘Cell’ class and using loops.

Code highlight

// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function setup() {
  createCanvas(500, 500);

//populating the board
  board = [];
  
  grid = [ [3, '', 6, 5, '', 8, 4, '', ''], 
         [5, 2, '', '', '', '', '', '', ''], 
         ['', 8, 7, '', '', '', '', 3, 1], 
         ['', '', 3, '', 1, '', '', 8, ''], 
         [9, '', '', 8, 6, 3, '', '', 5], 
         ['', 5, '', '', 9, '', 6, '', ''], 
         [1, 3, '', '', '', '', 2, 5, ''], 
         ['', '', '', '', '', '', '', 7, 4], 
         ['', '', 5, 2, '', 6, 3, '', ''] ]


  for (let i = 0; i < 9; i++) {
    for (let j = 0; j < 9; j++) {
      board.push([]);
      board[i].push(new Cell(i, j, grid[i][j]));
    }
  }

// 9x9 board, text size, and text location
  scl = width / 9;
  textSize(30);
  textAlign(CENTER, CENTER);
}


function draw() {
  for (let i = 0; i < 9; i++) {
    for (let j = 0; j < 9; j++) {
      board[i][j].display();
    }
  }
}

//cell class and display options
class Cell {
  constructor(i, j, value) {
    this.i = i;
    this.j = j;
    this.value = value; //value will be taken later from the grid array
  }

  display() {
    stroke(0);
    fill("#f2eecb");
    rect(scl * this.i, scl * this.j, scl, scl); // dividing the grid 9x9     with rectangles
    fill(0);
    text(this.value, scl * this.i, scl * this.j, scl, scl);
  }
}
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Embedded sketch:

Reflection and ideas for future work or improvements:

The next step would be modifying the code such that it generates [solvable] Sudoku boards instead of manually placing numbers in the board matrix. And then the next step would be adding another button that actually solves the board. This might be what I’ll be working on for the midterm.

Leave a Reply