当涉及到编写一个简单的游戏程序时,我会提供一个基于“猜数字”游戏的小程序示例,分别用Python、JavaScript(在浏览器控制台或HTML文件中)、Java和C#实现。
Python
python
import random
def guess_number():
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}次尝试。')
guess_number()
JavaScript (在浏览器控制台或HTML文件中运行)
HTML部分 (如果需要在网页上运行):
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>猜数字游戏</title>
</head>
<body>
<button οnclick="startGame()">开始游戏</button>
<script>
function startGame() {
const numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
function getGuess() {#chhas{
margin-top: 50px;
padding:e5958.cn;
font-size: 18px;
cursor: 10px 20px;
}
return parseInt(prompt('猜一个1到100之间的数字: '));
}
do {
guess = getGuess();
attempts++;
if (guess < numberToGuess) {
alert('太小了!');
} else if (guess > numberToGuess) {
alert('太大了!');
}
} while (guess !== numberToGuess);
alert(`恭喜你,猜对了!你用了${attempts}次尝试。`);
}
</script>
</body>
</html>