gpt4 book ai didi

javascript - 井字棋游戏,玩家 2 在 if 语句中放置棋子时出错

转载 作者:行者123 更新时间:2023-12-01 02:10:25 27 4
gpt4 key购买 nike

我正在尝试使用浏览器控制台一步一步地制作井字游戏,并最终改进我的功能。然而,我被困在玩家2回合(ttt_player2_turn()),我必须检查箱子是否为空。看来我在这个例子中的论证有问题。感谢您的建议(有lodash功能)。编辑:现在函数中的问题是它没有验证 is_case_free 语句。

// to have a printed board
function ttt_print_board(array){
return ('\n' +
' ' + array[0] + ' | ' + array[1] + ' | ' + array[2] + '\n' +
' ---------\n' +
' ' + array[3] + ' | ' + array[4] + ' | ' + array[5] + '\n' +
' ---------\n' +
' ' + array[6] + ' | ' + array[7] + ' | ' + array[8] + '\n')
}

//display things
function ttt_display(stuff){
console.log(stuff)
}

//ask something
function ttt_ask(question) {
return prompt(question)
}

// to verify if the answers is between 1-9
function ttt_verify_response(response) {
var integer_response = _.toInteger(response)
if(integer_response < 10 && integer_response > 0 && _.isInteger(integer_response)){
return true
} else {
return false
}
}

// this is my function to verify if case empty or not, at the moment just for 'x'
function ttt_verify_case (board, response) {
if(board[response] === 'x' ){
return false
} else{
return true
}
}

// return the player 1 choice
function ttt_player1_turn() {
var response = 0;
var is_correct_response = false
while(! is_correct_response){
response = ttt_ask("player 1 it's your turn (play 1 to 9)")
is_correct_response = ttt_verify_response(response)
}
return response
}

//return the player 2 choice and have to check if the case is empty from 'x', it seems like it doesn't go through the 2nd if condition
function ttt_player2_turn(board) {
var is_correct_response = false
var is_case_free = false
while(!is_correct_response || !is_case_free){
var response_player2 = ttt_ask("player 2 it's your turn, play 1 to 9");
is_correct_response = ttt_verify_response(response_player2)
if (!is_correct_response) {
console.log("incorrect response")
continue
}
is_case_free = ttt_verify_case(board, response_player2);
if(!is_case_free) {
console.log("player 1 already put a piece on this case")
}
}
return response_player2
}


//main function
function ttt_new_game() {
var board = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
var printed_board = ttt_print_board(board)
ttt_display(printed_board)
board[_.toInteger(ttt_player1_turn()) - 1] = 'x'
ttt_display(ttt_print_board(board))
board[_.toInteger(ttt_player2_turn()) - 1] = 'o'
ttt_display(ttt_print_board(board))
}

最佳答案

我发现了我的错误,因为它是一个数组,我在 ttt_verify_case 中忘记了 -1 响应。

// this is my function to verify if case empty or not, at the moment just for 'x'
function ttt_verify_case (board, response) {
if(board[response - 1] === 'x' ){
return false
} else{
return true
}
}

关于javascript - 井字棋游戏,玩家 2 在 if 语句中放置棋子时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49793219/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com