我正在尝试创建一个宾果游戏。
这是给我们的任务。我编写了我需要的所有函数,但是运行整个程序的“ main”函数有一个不会停止的循环。我似乎不知道是什么使它无限的,因为我给了它最终停止的条件。
代码有点长。希望您能帮助我。
var gNums = []
var gPlayers = [
{
name: 'player1',
hitCounts: 0,
board: creatBingoBoard()
},
{
name: 'player2',
hitCounts: 0,
board: creatBingoBoard()
}
]
// var check=gPlayers[0].board[0][0].isHit = true
// console.table(printBingoBoard(gPlayers[0].board))
// console.table(printBingoBoard(gPlayers[1].board))
// var check = gPlayers[0].board[0][0].isHit = true
playBingo()
// console.table(gPlayers[0].board)
function playBingo() {
// debugger
resetNums()
var isVictory = false
while (!isVictory) {
// console.log('still running!')
var calledNum = drawNum(gNums)
// console.log(calledNum)
for (var i = 0; !isVictory && i < gPlayers.length; i++) {
var player = gPlayers[i]
markBoard(player, calledNum)
isVictory = checkBingo(player)
}
}
}
function creatBingoBoard() {
resetNums()
var board = [];
const SIZE = 5;
for (var i = 0; i < SIZE; i++) {
board[i] = [];
for (var j = 0; j < SIZE; j++) {
board[i][j] = {
value: getRandomIntInclusive(0, 25),
isHit: false
}
}
}
return board;
}
function printBingoBoard(board) {
var bingoBoardCopy = []
var size = board.length
for (var i = 0; i < size; i++) {
bingoBoardCopy[i] = []
for (var j = 0; j < size; j++) {
if (board[i][j].isHit === true) {
bingoBoardCopy[i][j] = board[i][j].value + 'v'
} else bingoBoardCopy[i][j] = board[i][j].value
}
}
return bingoBoardCopy
}
function resetNums() {
gNums = []
for (var i = 0; i < 25; i++) {
gNums.push(i)
}
return gNums
}
function drawNum(nums) {
var index = getRandomIntInclusive(0, nums.length);
var num = nums[index];
nums.splice(index, 1);
return num;
}
function markBoard(player, calledNum) {
for (var i = 0; i < player.board.length; i++) {
for (var j = 0; j < player.board.length; j++) {
var cell = player.board[i][j]
if (cell === calledNum) {
player.hitCounts++
cell.isHit = true
}
}
}
printBingoBoard(player.board)
}
function checkBingo(player) {
// for (var i = 0; i < player.length; i++) {
// if (player.hitsCount === 25) return true
if (player.hitCounts === 25) {
return true
}
return false;
}
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive
}