The code just written above seems more convenient for the user to play the game..
But the code is a bit long. ( Relative to what is needed...)
Using the global variable approach we saw earlier, we can reduce three separate function definitions
to just one.
|
|
<!DOCTYPE html> |
|
|
<html> |
|
|
<head> |
|
|
<meta charset="utf-8" /> |
|
|
<title></title> |
|
|
<script type="text/javascript"> |
|
|
//<![CDATA[ |
|
|
function process(user) { |
|
|
var result = 0; |
|
|
var computer = parseInt((Math.random() * (3 - 1 + 1)) + 1); |
|
|
switch(user-computer) { |
|
|
case -2: case 1: result = 1; break; |
|
|
case -1: case 2: result = -1; break; |
|
|
case 0: result = 0; break; |
|
|
default: break; |
|
|
} |
|
|
document.write("<p />You: "); |
|
|
document.write((user==1)?"Scissors":(user==2)?"Rock":"Paper"); |
|
|
|
|
|
document.write("<p />Opponent: "); |
|
|
document.write((computer==1)?"Scissors":(computer==2)?"Rock":"Paper"); |
|
|
|
|
|
document.write("<p />Result: "); |
|
|
document.write((result==1)?"Win": (result==0)?"Draw":"Loss"); |
|
|
} |
|
|
|
|
|
//]]]]> |
|
|
</script> |
|
|
</head> |
|
|
<body> |
|
|
<input type="button" value="Scissors" onclick="process(1)" /> |
|
|
<input type="button" value="Rock" onclick="process(2)" /> |
|
|
<input type="button" value="Paper" onclick="process(3)" /> |
|
|
</body> |
|
|
</html> |
