用JS编写一个数字游戏 有如下要求
发布网友
发布时间:2022-04-21 18:35
我来回答
共1个回答
热心网友
时间:2022-04-07 07:06
<!DOCTYPE HTML>
<html>
<head>
<title>Number game</title>
<style>
body{text-align : center}
.Win{color : green}
.Fail{color : red}
</style>
</head>
<body>
<div id="Title">规则...</div>
<div id="Control">
<input id="Input">
<button id="Go">Go</button>
</div>
<div id="Log"></div>
<script type="text/javascript" >
~function(window,document)
{
var
MessageWin = function(I,R){return '胜利: 输入为' + I + ', 随机为' + R + ', 相加结果为' + (I + R) + ', 在目标范围内'},
MessageFaill = function(I,R){return '失败: 输入为' + I + ', 随机为' + R + ', 相加结果为' + (I + R) + ', 不在在目标范围内'},
MessageError = function(){return '输入有误, 请输入范围为[-' + Range + ',' + Range + ']的数字'},
Range = 50,
RangeRnd = 80,
RangeWin = 30,
$ = function(Q){return document.getElementById(Q)},
Hint = function(Q,C)
{
var LogElement = document.createElement('div');
LogElement.innerText = Q
C && LogElement.setAttribute('class',C)
LogLast ?
Log.insertBefore(LogElement,LogLast) :
Log.appendChild(LogElement)
LogLast = LogElement
},
Input = $('Input'),
Button = $('Go'),
Log = $('Log'),
LogLast;
Button.addEventListener('click',function()
{
var
I = parseFloat(Input.value),
R = -RangeRnd + parseInt(2 * Math.random() * RangeRnd + 1);
if (I !== I || Math.abs(I) > Range) return Hint(MessageError())
Math.abs(I + R) <= RangeWin ?
Hint(MessageWin(I,R),'Win') :
Hint(MessageFaill(I,R),'Fail')
})
}(window,document)
</script>
</body>
</html>