如何在函数重置后不清空数组以便继续



简介:
我正在尝试制作石头、纸和剪刀(rps(。

问题:
我正在尝试在我的功能中保存两个不同的选项,以便我可以制作一个功能游戏。然而,每次我的数组被重置时。这使得我不能使用rps的用户输入。

当前代码:

function game(input) {
var playerMoves = [];
if (playerMoves.length < 2) {
playerMoves.push(input);
} else {
playerMoves = [];
}
console.log(playerMoves);
}
h1 {
text-align: center;
}
button {
font-size: 1.2rem;
}
#player_turn {
color: rgb(255, 0, 0);
}
.container {
display: flex;
width: 100%;
flex-direction: row;
justify-content: space-around;
}
.images {
width: 200px;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rock, paper, scissors!</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
</head>
<body>
<h1 id="player_won"></h1>
<h1>Player <span id="player_turn">1</span> pick an option!</h1>
<div class="container">
<div class="box">
<img onclick="game('rock')" class="images" src="https://therockplacellc.com/wp-content/themes/the-rock-place/i/rock.png" id="rock">
</div>
<div class="box">
<img onclick="game('paper')" class="images" src="https://big.nyc3.cdn.digitaloceanspaces.com/solaris/general/TP-Roll.png?mtime=20191210094103&focal=none" id="paper">
</div>
<div class="box">
<img onclick="game('scissors')" class="images" src="https://nl.mouser.com/images/marketingid/2020/microsites/177933245/scissors.PNG" id="scissors">
</div>
</div>
</body>
</html>

";Dev";注意:
如果您认为任何东西已经过时/没有用处。请注意,我对所有类型的输入都持100%的开放态度。

playerMoves声明移出函数:

var playerMoves = []
function game(input) {
if (playerMoves.length < 2) {
playerMoves.push(input);
console.log(playerMoves);
} else {
playerMoves = [];
}
}
h1 {
text-align: center;
}
button {
font-size: 1.2rem;
}
#player_turn {
color: rgb(255, 0, 0);
}
.container {
display: flex;
width: 100%;
flex-direction: row;
justify-content: space-around;
}
.images {
width: 200px;
cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Rock, paper, scissors!</title>
<link rel="stylesheet" href="styles.css">
<script src="script.js"></script>
</head>
<body>
<h1 id="player_won"></h1>
<h1>Player <span id="player_turn">1</span> pick an option!</h1>
<div class="container">
<div class="box">
<img onclick="game('rock')" class="images" src="https://therockplacellc.com/wp-content/themes/the-rock-place/i/rock.png" id="rock">
</div>
<div class="box">
<img onclick="game('paper')" class="images" src="https://big.nyc3.cdn.digitaloceanspaces.com/solaris/general/TP-Roll.png?mtime=20191210094103&focal=none" id="paper">
</div>
<div class="box">
<img onclick="game('scissors')" class="images" src="https://nl.mouser.com/images/marketingid/2020/microsites/177933245/scissors.PNG" id="scissors">
</div>
</div>
</body>
</html>

最新更新