我最近一直在做一個在 JS 控制臺中制作石頭剪刀布游戲的專案。現在,正如您在下面的代碼中所看到的,我只是用石頭和剪刀測驗水域,一旦我解決了這個錯誤,就會很快添加紙張。我想在隨機生成的選擇(變數 b)和用戶的選擇(變數 a)之間玩這個游戲六輪。
我希望 for 回圈運行 6 次以播放六輪。目前沒有任何計分器。當我運行 for 回圈時,我希望將隨機生成的選擇登錄到控制臺,然后將要求用戶進行選擇,然后將記錄他/她的選擇。然后,我希望 do-while 回圈中的 if 陳述句評估 a 和 b 的當前兩個值,并在記錄兩個回應后立即給出我要記錄的結果(例如,巖石壓碎剪刀!你松了!) . 然后將生成并記錄另一個隨機選擇,依此類推....
現在發生的事情是,我只在 for 回圈的第六次迭代之后才對 if 陳述句進行評估,而它應該在每次迭代后從 if 條件中給我記錄的陳述句。
這是代碼:
var arr = ['rock', 'scissor']
let win = false
function play(arr){
do{
for(let i=0; i<=5;i ){
var a = prompt('Enter choice:')
console.log(a)
var b = arr[(Math.floor(Math.random()*2))]
console.log(b)
if(a==="rock" && b==="scissor"){
console.log("Rock crushes Scissor! You win!")
win=true
}
else if(b==="rock" && a==="scissor"){
console.log("Rock crushes Scissor! You lose!")
win=true
}
}
}
while(!win);
check_winner(win)
}
function check_winner(win){
if(win===true){
console.log("gamne over")
}
else{
prompt("Enter again")
}
}
play(arr)
我是 JS 新手,很難處理這個錯誤。也許你們真誠的人可以讓我擺脫這種困境。任何幫助將不勝感激。謝謝!
uj5u.com熱心網友回復:
干得好 :
let arr = ['R', 'P', 'S']
let win = false
function play(arr){
let BotScore = 0;
let UserScore = 0;
let round = 1;
alert('use R as Rock ,P as Paper and S as Scissor')
while(round<=5){
let UserChoice = prompt('round_' round ' Enter choice:')
let BotChoice = Math.floor(Math.random() * 3)
BotChoice = arr[BotChoice];
if(UserChoice == 'S' && BotChoice == 'R'){
BotScore ;
round ;
alert('Bot Won')
}else if(UserChoice == 'S' && BotChoice == 'P'){
UserScore ;
round ;
alert('You Won')
}else if(UserChoice == 'S' && BotChoice == 'S'){
alert('Draw')
}else if(UserChoice == 'R' && BotChoice == 'P'){
BotScore ;
round ;
alert('Bot Won')
}else if(UserChoice == 'R' && BotChoice == 'S'){
UserScore ;
round ;
alert('You Won')
}else if(UserChoice == 'R' && BotChoice == 'R'){
alert('Draw')
}else if(UserChoice == 'P' && BotChoice == 'R'){
UserScore ;
round ;
alert('You Won')
}else if(UserChoice == 'P' && BotChoice == 'S'){
BotScore ;
round ;
alert('Bot Won')
}else if(UserChoice == 'P' && BotChoice == 'P'){
alert('Draw')
}
}
let Result = UserScore > BotScore ? 'You Won' : 'Bot Won'
alert('Your Score : ' UserScore ' Bot Score : ' BotScore '[' Result ']')
}
play(arr)
uj5u.com熱心網友回復:
除了評論中提到的事情
- 贏=假如果輸了
- check_winner(win) 在 do while 回圈之外,所以只有在 win=true 時才執行
你可能想要
- 在for回圈中使用alerts而不是console.logs,所以結果是直接可見的
- 在這種情況下包括對“null”的檢查并結束游戲(如果按“取消”或“esc”,則“a”為空)
- 請注意,內部 for 回圈將運行直到完成,即使同時將 win 設定為 true
do{
for(let i=0; i<=5;i ){
console.log(i)
if(i === 3) {
win = true
console.log('win is true, get out of here?!?')
}
}
}
while(!win);
console.log('----------------------------- next round');
do{
for(let i=0; i<=5;i ){
console.log(i)
if(i === 3) {
win = true
console.log("win is true, get out with 'break")
break;
}
}
}
while(!win);
它可能有助于描述游戲應該具有的邏輯,以找到可能的編碼方式
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/338333.html
上一篇:無法使用Bootstrap折疊
