JavaScript小测验3
剪刀,石头,布小游戏(使用自定义函数创建)
答案
<!DOCTYPE html>
<html>
<head>
<title>剪刀 石頭 布</title>
<style>
p{
font-size: 30px;
}
button{
font-size: 30px;
margin-right: 20px;
width: 100px;
}
</style>
</head>
<body>
<p>請選擇 剪刀 石頭 布</p>
<button onclick='
playgame("剪刀",computerChoice());
'>剪刀</button>
<button onclick='
playgame("石頭",computerChoice());
'>石頭</button>
<button onclick='
playgame("布",computerChoice());
'>布</button>
<script>
function playgame (userChoice,computerChoice) {
if (userChoice ==="剪刀") {
if (computerChoice === userChoice) {
alert(`你出${userChoice} 電腦出${computerChoice},此局平手!`);
} else if (computerChoice === "石頭") {
alert(`你出${userChoice} 電腦出${computerChoice},此局你輸了!`);
} else {
alert(`你出${userChoice} 電腦出${computerChoice},此局你贏了!`);
}
}else if (userChoice ==="石头") {
if (computerChoice === userChoice) {
alert(`你出${userChoice} 電腦出${computerChoice},此局平手!`);
} else if (computerChoice === "布") {
alert(`你出${userChoice} 電腦出${computerChoice},此局你輸了!`);
} else {
alert(`你出${userChoice} 電腦出${computerChoice},此局你贏了!`);
}
}else{
if (computerChoice === userChoice) {
alert(`你出${userChoice} 電腦出${computerChoice},此局平手!`);
} else if (computerChoice === "石頭") {
alert(`你出${userChoice} 電腦出${computerChoice},此局你輸了!`);
} else {
alert(`你出${userChoice} 電腦出${computerChoice},此局你贏了!`);
}
}
}
function computerChoice (){
const randomNum = Math.random()*3;
let computerChoice = "";
console.log(randomNum);
if (0<=randomNum && randomNum<1) {
computerChoice = "剪刀";
} else if (1<=randomNum && randomNum<2) {
computerChoice = "石頭";
} else {
computerChoice = "布";
}
return computerChoice;
}
</script>
</body>
</html>