JavaScript 猜数字小游戏
在1~10中随机抽取一个数字,(抽取的数字可以在控制台查看)只有十次机会
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>wangwang</title>
</head>
<body>
<script type="text/javascript">
function getRandom(min,max) {
return Math.floor(Math.random()*(max-min+1))+min;
}
// 猜数字
var num=getRandom(1,10);
// 在控制台查看答案
console.log('答案:'+num);
var i=0;
do {
var n=prompt('欢迎来到猜数字游戏\n系统已自动生成一个1~10的整数,请输入你猜的数字:');
if (n>num) {
alert('你猜大了,继续猜');
}else if (n<num) {
alert('你猜小了,继续猜');
}
i++;
var cishu=10-i;
alert('已使用'+i+'次机会,还剩'+cishu+'次机会');
}while (n !=num && i <10) {
if(n==num){
alert('恭喜你!猜对了!')
}else if (i==10){
alert('你的十次机会已达上限,游戏失败,欢迎下次再来~');
}
}
</script>
</body>
</html>