Python
python
import random
def game():
number_to_guess = random.randint(1, 100) 0512px.cn
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 (在浏览器控制台或HTML文件中运行)
HTML文件 (index.html):
html
javascript
function startGame() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
function guessNumber() {
guess = prompt('猜一个1到100之间的数字:');
attempts++;
if (guess < numberToGuess) {
alert('太小了!');
guessNumber();
} else if (guess > numberToGuess) {
alert('太大了!');
guessNumber();
} else {
alert(`恭喜你,你猜对了!你用了${attempts}次尝试。`);
}
}
guessNumber();
}
C++ (使用控制台输入/输出)
cpp
#include
#include
#include
int main() {
std::srand(static_cast(std::time(0))); // 使用当前时间作为随机数种子
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);
std::cout << "恭喜你,你猜对了!你用了" << attempts << "次尝试。" << std::endl;
return 0;
}
由于不同电脑语言具有不同的特性和用途,我会为你展示三种常见编程语言(Python、JavaScript、C++)的简单小游戏代码示例。这里我们将创建一个简单的“猜数字”游戏。
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 (在浏览器控制台或HTML文件中运行)
HTML文件 (index.html):
html
javascript
function startGame() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
function guessNumber() {
guess = prompt('猜一个1到100之间的数字:');
attempts++;
if (guess < numberToGuess) {
alert('太小了!');
guessNumber();
} else if (guess > numberToGuess) {
alert('太大了!');
guessNumber();
} else {
alert(`恭喜你,你猜对了!你用了${attempts}次尝试。`);
}
}
guessNumber();
}
C++ (使用控制台输入/输出)
cpp
#include
#include
#include
int main() {
std::srand(static_cast(std::time(0))); // 使用当前时间作为随机数种子
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);
std::cout << "恭喜你,你猜对了!你用了" << attempts << "次尝试。" << std::endl;
return 0;
}