Simple Rock Paper Scissors Game

To create a simple rock paper scissors game in HTML, we'll need to use JavaScript to add functionality to the buttons. Here's an example of how you can do it:

<!DOCTYPE html>
<html>
<head>
	<title>Rock Paper Scissors Game</title>
	<script>
		function play(userChoice) {
			var computerChoice = Math.random();
			if (computerChoice < 0.34) {
				computerChoice = 'rock';
			} else if (computerChoice <= 0.67) {
				computerChoice = 'paper';
			} else {
				computerChoice = 'scissors';
			}
			
			var result = compare(userChoice, computerChoice);
			document.getElementById('result').innerHTML = result;
		}

		function compare(choice1, choice2) {
			if (choice1 === choice2) {
				return 'It's a tie!';
			} else if (choice1 === 'rock') {
				if (choice2 === 'scissors') {
					return 'Rock wins!';
				} else {
					return 'Paper wins!';
				}
			} else if (choice1 === 'paper') {
				if (choice2 === 'rock') {
					return 'Paper wins!';
				} else {
					return 'Scissors wins!';
				}
			} else if (choice1 === 'scissors') {
				if (choice2 === 'paper') {
					return 'Scissors wins!';
				} else {
					return 'Rock wins!';
				}
			}
		}
	</script>
</head>
<body>
	<h1>Rock Paper Scissors Game</h1>
	<button onclick='play('rock')'>Rock</button>
	<button onclick='play('paper')'>Paper</button>
	<button onclick='play('scissors')'>Scissors</button>
	<div id='result'></div>
</body>
</html>

In this example, we have three buttons, one for each choice. When the user clicks on a button, the play function is called with the corresponding choice as the parameter. The play function generates a random choice for the computer and passes both choices to the compare function, which determines the winner and returns the result. The play function then displays the result on the page.

That's it! You now have a simple rock paper scissors game in HTML.

How to Create a Simple Rock Paper Scissors Game in HTML

原文地址: https://www.cveoy.top/t/topic/lmnN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录