Python
python
import random
def guess_number(): cottonzone.com.cn
secret_number = random.randint(1, 100)
attempts = 0
while True:
try:
guess = int(input("猜一个1到100之间的数字: "))
attempts += 1
if guess < secret_number:
print("太小了!")
elif guess > secret_number:
print("太大了!")
else:
print(f"恭喜你,猜对了! 你用了{attempts}次尝试。")
break
except ValueError:
print("请输入一个整数!")
guess_number()
JavaScript (浏览器控制台或Node.js)
javascript
function guessNumber() {
let secretNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
let guess;
do {
guess = prompt("猜一个1到100之间的数字:");
attempts++;
if (guess < secretNumber) {
console.log("太小了!");
} else if (guess > secretNumber) {
console.log("太大了!");
}
} while (guess != secretNumber);
console.log(`恭喜你,猜对了! 你用了${attempts}次尝试。`);
}
guessNumber();
Java
java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Random rand = new Random();
int secretNumber = rand.nextInt(100) + 1;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("猜一个1到100之间的数字: ");
int guess = scanner.nextInt();
attempts++;
if (guess < secretNumber) {
System.out.println("太小了!");
} else if (guess > secretNumber) {
System.out.println("太大了!");
} else {
System.out.println("恭喜你,猜对了! 你用了" + attempts + "次尝试。");
break;
}
}
scanner.close();
}
}
以上代码都是“猜数字”游戏的简单实现,你可以根据需要进行扩展和修改。由于篇幅限制,我无法为每一种电脑语言都提供完整的游戏代码,但我可以为你提供几种常见编程语言(如Python, JavaScript, Java)的“猜数字”游戏的基础框架。
Python
python
import random
def guess_number():
secret_number = random.randint(1, 100)
attempts = 0
while True:
try:
guess = int(input("猜一个1到100之间的数字: "))
attempts += 1
if guess < secret_number:
print("太小了!")
elif guess > secret_number:
print("太大了!")
else:
print(f"恭喜你,猜对了! 你用了{attempts}次尝试。")
break
except ValueError:
print("请输入一个整数!")
guess_number()
JavaScript (浏览器控制台或Node.js)
javascript
function guessNumber() {
let secretNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
let guess;
do {
guess = prompt("猜一个1到100之间的数字:");
attempts++;
if (guess < secretNumber) {
console.log("太小了!");
} else if (guess > secretNumber) {
console.log("太大了!");
}
} while (guess != secretNumber);
console.log(`恭喜你,猜对了! 你用了${attempts}次尝试。`);
}
guessNumber();
Java
java
import java.util.Random;
import java.util.Scanner;
public class GuessNumberGame {
public static void main(String[] args) {
Random rand = new Random();
int secretNumber = rand.nextInt(100) + 1;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("猜一个1到100之间的数字: ");
int guess = scanner.nextInt();
attempts++;
if (guess < secretNumber) {
System.out.println("太小了!");
} else if (guess > secretNumber) {
System.out.println("太大了!");
} else {
System.out.println("恭喜你,猜对了! 你用了" + attempts + "次尝试。");
break;
}
}
scanner.close();
}
}
以上代码都是“猜数字”游戏的简单实现,你可以根据需要进行扩展和修改。