由于各种电脑语言的复杂性和篇幅限制,我将为你提供三种常见编程语言(Python、JavaScript 和 Java)的简单小游戏代码示例:猜数字游戏。
Python 版本
python
import random
def game():
number_to_guess = random.randint(1, 100)
guess = None
attempts = 0
while guess != number_to_guess:
guess = int(input('猜一个1到100之间的数字: '))
attempts += 1
if guess < number_to_guess:
print('太小了!')
elif guess > number_to_guess:
print('太大了!')
print(f'恭喜你,你猜对了!用了{attempts}次尝试。')
if __name__ == "__main__":
game()
JavaScript 版本(可以在浏览器或Node.js中运行)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>猜数字游戏</title>
</head>
<body>
<h1>猜数字游戏</h1>
<p id="message">猜一个1到100之间的数字:</p>
<input type="number" id="guessInput">
<button οnclick="checkGuess()">提交</button>
<script>
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess;
let attempts = 0;
function checkGuess() {
guess = parseInt(document.getElementById('guessInput').value);
attempts++;
if (guess < numberToGuess) {#chhas{
margin-top: 50px;
padding:pulso.cn;
font-size: 18px;
cursor: 10px 20px;
}
document.getElementById('message').innerText = '太小了!';
} else if (guess > numberToGuess) {
document.getElementById('message').innerText = '太大了!';
} else {
document.getElementById('message').innerText = `恭喜你,你猜对了!用了${attempts}次尝试。`;
}
}
</script>
</body>
</html>