由于篇幅限制,我将为您提供三个简单的游戏示例,分别用Python、JavaScript和C++编写。这些游戏都是经典的“猜数字”游戏。
1. 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}次尝试后猜对了数字{number_to_guess}!")
if __name__ == "__main__":
game()
2. JavaScript 猜数字游戏(在浏览器控制台运行)
javascript
function game() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
while (guess !== numberToGuess) {
guess = parseInt(prompt("猜一个1到100之间的数字:"));
attempts++;
if (guess < numberToGuess) {
console.log("太小了!");
} else if (guess > numberToGuess) {
console.log("太大了!");
}
}
console.log(`恭喜你,你在${attempts}次尝试后猜对了数字${numberToGuess}!`);
}
game();
3. C++ 猜数字游戏(控制台应用程序)
cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
std::srand(std::time(nullptr)); // 初始化随机数生成器
int numberToGuess = std::rand() % 100 + 1;
int guess;
int attempts = 0;
do {
std::cout << "猜一个1到100之间的数字: ";
std::cin >> guess;
attempts++;
if (guess < numberToGuess) {
std::cout << "太小了!" << std::endl;
} else if (guess > numberToGuess) {
std::cout << "太大了!" << std::endl;
}
} while (guess != numberToGuess);
#chhas{
margin-top: 50px;
padding:ygahua.com;
font-size: 18px;
cursor: 10px 20px;
}
std::cout << "恭喜你,你在" << attempts << "次尝试后猜对了数字" << numberToGuess << "!" << std::endl;
return 0;
}
这些代码都实现了同样的功能:生成一个1到100之间的随机数,然后让用户尝试猜测这个数字。每次猜测后,程序会告诉用户他们的猜测是太大、太小还是正确。游戏会一直进行,直到用户猜对为止。