Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Connect Four Game Question

Eftn

New Coder
I am trying to learn how to code by looking a solutions for previous codes and finding out what each part is doing to learn how to use them. I want to become a developer but I do not want to copy and paste everything , I want to actually know what is happening so I can code this myself. I can watch 100 videos but I have questions and I need help, hope someone out there can help me ....

I was wondering if someone could explain to me what is going on in the code below.

* Player 1 and 2 alternate turns. On each turn, a piece is dropped down a
* column until a player gets four-in-a-row (horiz, vert, or diag) or until
* board fills (tie)
*/

class Game {
constructor(p1, p2, height = 6, width = 7) {
this.players = [p1, p2];
this.height = height;
this.width = width;
this.currPlayer = p1;
this.makeBoard();
this.makeHtmlBoard();
this.gameOver = false;
}

/** makeBoard: create in-JS board structure:
* board = array of rows, each row is array of cells (board[y][x])
*/

**Question: So I believe that this is creating a board and making it empty by looping through it?**

makeBoard() {
this.board = [];
for (let y = 0; y < this.height; y++) {
this.board.push(Array.from({ length: this.width }));
}
}

**Question: Is this grabbing the board element from the HTML Page? board.innerHtml is blank, however
didnt we just make a blank a board? Why do we need this?**

makeHtmlBoard() {
const board = document.getElementById('board');
board.innerHTML = '';

// make column tops (clickable area
// for adding a piece to that column)
const top = document.createElement('tr');
top.setAttribute('id', 'column-top');

// store a reference to the handleClick bound function
// so that we can remove the event listener correctly later
this.handleGameClick = this.handleClick.bind(this);

top.addEventListener("click", this.handleGameClick);

for (let x = 0; x < this.width; x++) {
const headCell = document.createElement('td');
headCell.setAttribute('id', x);
top.append(headCell);
}

board.append(top);

// make main part of board
for (let y = 0; y < this.height; y++) {
const row = document.createElement('tr');

for (let x = 0; x < this.width; x++) {
const cell = document.createElement('td');
cell.setAttribute('id', `${y}-${x}`);
row.append(cell);
}

board.append(row);
}
}

/** findSpotForCol: given column x, return top empty y (null if filled) */

**Question: I have no idea what this line is doing**

findSpotForCol(x) {
for (let y = this.height - 1; y >= 0; y--) {
if (!this.board[y][x]) {
return y;
}
}
return null;
}

/** placeInTable: update DOM to
* place piece into HTML board */

**Question: Im not sure what place in table is doing, however I know the second line is creating a DIV on
the table , third line is styling it, however the last three lines i need help with it.**

placeInTable(y, x) {
const piece = document.createElement('div');
piece.classList.add('piece');
piece.style.backgroundColor = this.currPlayer.color;
piece.style.top = -50 * (y + 2);

const spot = document.getElementById(`${y}-${x}`);
spot.append(piece);
}

/** endGame: announce game end */

endGame(msg) {
alert(msg);
const top = document.querySelector("#column-top");
top.removeEventListener("click", this.handleGameClick);
}

/** handleClick: handle click of column top to play piece */

handleClick(evt) {
// get x from ID of clicked cell
const x = +evt.target.id;

The lines below, I have no idea how I could even think of this logic , please help.

****// get next spot in column (if none, ignore click)
const y = this.findSpotForCol(x);
if (y === null) {
return;**
}
// place piece in board and add to HTML table
this.board[y][x] = this.currPlayer;
this.placeInTable(y, x);
// check for tie
if (this.board.every(row => row.every(cell => cell))) {
return this.endGame('Tie!');
}
// check for win
if (this.checkForWin()) {
this.gameOver = true;
return this.endGame(`The ${this.currPlayer.color} player won!`);
}
// switch players
this.currPlayer =
this.currPlayer === this.players[0] ? this.players[1] : this.players[0];**
}

/** checkForWin: check board cell-by-cell for "does a win start here?" */

checkForWin() {
// Check four cells to see if they're all color of current player
// - cells: list of four (y, x) cells
// - returns true if all are legal coordinates & all match currPlayer
const _win = cells =>
cells.every(
([y, x]) =>
y >= 0 &&
y < this.height &&
x >= 0 &&
x < this.width &&
this.board[y][x] === this.currPlayer
);

for (let y = 0; y < this.height; y++) {
for (let x = 0; x < this.width; x++) {
// get "check list" of 4 cells (starting here) for each of the different
// ways to win
const horiz = [[y, x], [y, x + 1], [y, x + 2], [y, x + 3]];
const vert = [[y, x], [y + 1, x], [y + 2, x], [y + 3, x]];
const diagDR = [[y, x], [y + 1, x + 1], [y + 2, x + 2], [y + 3, x + 3]];
const diagDL = [[y, x], [y + 1, x - 1], [y + 2, x - 2], [y + 3, x - 3]];

// find winner (only checking each win-possibility as needed)
if (_win(horiz) || _win(vert) || _win(diagDR) || _win(diagDL)) {
return true;
}
}
}
}
}

class Player {
constructor(color) {
this.color = color;
}
}

document.getElementById('start-game').addEventListener('click', () => {
let p1 = new Player(document.getElementById('p1-color').value);
let p2 = new Player(document.getElementById('p2-color').value);
new Game(p1, p2);
});
 
Hi there,

Welcome to Code Forum! :)

Unfortunately, I'm still learning JavaScript as well. However, I'll see if I can find the answer as well. Also for future reference, just remember to use our BBCode when placing code into threads. Please review this here.
 
I'd recommend getting some introductory books on programming for beginners. There you will start from simple examples, and than compose what you've learned into more complex ones. With longer code listings, those books usually break them apart, thoroughly theorizing what which part does, which is exactly what you are asking for.

You can find out which languages are the most widespread by percent of programmers (this is important for support resources when you run into problems), and investigate which language is supposed to aim for which purpose. You can search things like "which language is the best for programming games","which language is the best for business programming", "which language is the best for programming databases", "which language is the best for web programming", or maybe even "which language is the best for learning programming". Then you have to pick a language of your choice (Although I never used it, I hear Python is very modern and simple, and very widespread general programming language) and search a little bit for a book with nice recommendations.

Unfortunately, I couldn't recommend any specific book, as it was three decades ago since I started programming and learned mostly from paper materials scattered around me, and a lot of experimenting. I started with Commodore Basic, moved onto PC Quick Basic, then Pascal, then C++, then Clipper, then Visual Basic and SQL, then Java, then HTML, Javascript, and ASP, and touched a bit of C#. But then I hooked of the grid, and started researching logic, theorem proving and lastly, computability theory. Right now I'm in a process of developing my own programming language.

A lot of things happened while I was off the grid, languages like Rust, Go and Python appeared, but I was able to understand their concepts after fast skimming over a few pages tutorials, except maybe Haskell which was something entirely new to me. In short, business programming haven't changed much for more than 20 years, while experiments like Haskell didn't spread too much.

A while ago, discovering ancient Lisp was so refreshing experience for me. It is such an underrated language that kept being pushed aside all these years in a favor of corporative initiatives that always found their user base, no matter how unimaginative the initiatives were. Well, what can we do, money runs the world, while people are generally afraid to give a chance to something other than usual.

Anyway, for a start, I'd recommend sticking with mainstream languages and introductory books purposed for learning programming. Good luck.
 
Last edited:
Back
Top Bottom