由于涵盖多种编程语言可能会非常冗长,我将为你展示三种常见编程语言(Python、Java、JavaScript)中的简单小游戏代码示例:猜数字游戏。
- 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} 次尝试。')
game()
2. Java 版本
java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Random rand = new Random();
int numberToGuess = rand.nextInt(100) + 1;
Scanner scanner = new Scanner(System.in);
int guess = 0;
int attempts = 0;
while (guess != numberToGuess) {
System.out.println("猜一个 1 到 100 之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess < numberToGuess) {#chhas{
margin-top: 50px;
padding:supero.com.cn;
font-size: 18px;
cursor: 10px 20px;
}
System.out.println(“太小了!”);
} else if (guess > numberToGuess) {
System.out.println(“太大了!”);
}
}
System.out.println("恭喜你,你猜对了!用了 " + attempts + " 次尝试。");
}
}
3. JavaScript 版本(在浏览器中使用)
html
猜数字游戏
猜一个 1 到 100 之间的数字:
提交<script>
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = 0;
let attempts = 0;
function checkGuess() {
guess = parseInt(document.getElementById('guess').value);
attempts++;
if (guess < numberToGuess) {
document.getElementById('message').textContent = '太小了!';
} else if (guess > numberToGuess) {
document.getElementById('message').textContent = '太大了!';
} else {
document.getElementById('message').textContent = `恭喜你,你猜对了!用了 ${attempts} 次尝试。`;
document.getElementById('guess').disabled = true;
document.getElementById('message').style.color = 'green';
}
}
</script>
以上三个示例都是简单的猜数字游戏,你可以根据自己的需求进行修改和扩展。