JavaScript小测验2
题目:创建一个石头剪刀布的小游戏,电脑会随机生成石头剪刀布,用户选择石头,剪刀,布
考点:if运算符 熟练度,js随机数(见js文档)
<!DOCTYPE html>
<html>
<head>
<title>測驗</title>
<style>
button{
font-size:25px;
margin-right:10px;
}
p{
font-size: 25px;
display: inline-block;
margin-right:10px;
}
img{
height: 200px;
display: block;
margin-top:50px;
}
</style>
</head>
<body>
<button onclick="
//0为石头,1为剪刀,2为布
user = 0;
//随机生成0-3的小数
computer =Math.random()*3;
if(1<computer && computer<2){
alert('你赢了');
}else if(0<computer && computer<1){
alert('平手');
}else{
alert('你輸了');
}
">石头</button>
<button onclick="
user = '1'
computer =Math.random()*3;
if(1<computer && computer<2){
alert('平手');
}else if(0<computer && computer<1){
alert('你赢了');
}else{
alert('你输了');
}
">剪刀</button>
<button onclick="
user = '2';
computer =Math.random()*3;
if(1<computer && computer<2){
alert('你赢了');
}else if(0<computer && computer<1){
alert('你输了');
}else{
alert('平手');
}
">布</button>
<script>
let user = '0';
let computer = '0';
</script>
</body>
</html>
答案
<!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='
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 = "布";
}
if (computerChoice === "剪刀") {
alert(`你出剪刀 電腦出${computerChoice},此局平手!`);
} else if (computerChoice === "石頭") {
alert(`你出剪刀 電腦出${computerChoice},此局你輸了!`);
} else {
alert(`你出剪刀 電腦出${computerChoice},此局你贏了!`);
}
'>剪刀</button>
<button onclick='
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 = "布";
}
if (computerChoice === "剪刀") {
alert(`你出石頭 電腦出${computerChoice},此局你贏了!`);
} else if (computerChoice === "石頭") {
alert(`你出石頭 電腦出${computerChoice},此局平手!`);
} else {
alert(`你出石頭 電腦出${computerChoice},此局你輸了!`);
}
'>石頭</button>
<button onclick='
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 = "布";
}
if (computerChoice === "剪刀") {
alert(`你出布 電腦出${computerChoice},此局你輸了!`);
} else if (computerChoice === "石頭") {
alert(`你出布 電腦出${computerChoice},此局你贏了!`);
} else {
alert(`你出布 電腦出${computerChoice},此局平手!`);
}
'>布</button>
<script>
</script>
</body>
</html>