Answer the question
In order to leave comments, you need to log in
Why is the variable not available in the post method?
The essence of the question is reflected in more detail in the comments in the code. I don’t understand why the winner field of the state object is undefined/undefined in the app.post method (in the makeMove(column) method, the variable is declared and initialized successfully), and there are no problems with all other fields (field, currentPlayer). Obviously I missed something in the scopes ....
const express = require('express');
let cors = require("cors");
let bodyParser = require("body-parser");
const app = express();
app.use(cors());
app.use(bodyParser.json());
let state = {
field: [
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0],
],
currentPlayer: 1
}
function findWinner(field, column, row){
const player = state.currentPlayer;
for(let iColumn = 0; iColumn <= field[column].length ; iColumn++){
if(field[iColumn][row] === player){
let winCounter = 0;
for(let step = iColumn; step <= field[column].length; step++){
if(field[step][row] === player){
winCounter++;
if(winCounter === 4) {
console.log('player:' + player);
state.winner = player;
console.log('state.winner:' + JSON.stringify(state)); // тут state.winner !== undefined
}
} else break;
}
}
}
}
function makeMove(column) {
const newField = [...state.field];
const player = state.currentPlayer;
const lastZeroInex = newField[column].lastIndexOf(0);
if (lastZeroInex !== -1) {
newField[column][lastZeroInex] = player;
}
findWinner(newField, column, lastZeroInex)
console.log('state.winner:' + state.winner); // здесь state.winner !== undefined
const newPlayer = player === 1 ? 2 : 1;
state = {
field: newField,
currentPlayer: newPlayer
};
}
app.post('/move', (req, res) => {
console.log(req.body.column);
makeMove(req.body.column); //а вот тут уже state.winner === undefined
res.send( state);
});
app.listen(5000);
Answer the question
In order to leave comments, you need to log in
Well, you completely rewrite the object:
state = {
field: newField,
currentPlayer: newPlayer
};
Object.assign(state, { ... })
.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question