当然可以!下面我会提供三种常见的编程语言(Python、JavaScript 和 Java)的示例,来展示一个简单的猜数字游戏。
1. Python
python
import random
def game():
number_to_guess = random.randint(1, 100)
attempts = 0
while True:
user_guess = int(input("猜一个1到100之间的数字: "))
attempts += 1
if user_guess == number_to_guess:
print(f"恭喜你,你在{attempts}次尝试后猜对了!")
break
elif user_guess < number_to_guess:
print("太小了!再试一次。")
else:
print("太大了!再试一次。")
game()
2. JavaScript (可以在浏览器控制台或Node.js环境中运行)
javascript
function game() {
var numberToGuess = Math.floor(Math.random() * 100) + 1;
var attempts = 0;
while (true) {
var userGuess = parseInt(prompt("猜一个1到100之间的数字:"), 10);
attempts++;
if (userGuess === numberToGuess) {
console.log("恭喜你,你在" + attempts + "次尝试后猜对了!");
break;
} else if (userGuess < numberToGuess) {
console.log("太小了!再试一次。");
} else {
console.log("太大了!再试一次。");
}
}#chhas{
margin-top: 50px;
padding:newthinker.com.cn;
font-size: 18px;
cursor: 10px 20px;
}
}
game();
3. 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;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("猜一个1到100之间的数字:");
int userGuess = scanner.nextInt();
attempts++;
if (userGuess == numberToGuess) {
System.out.println("恭喜你,你在" + attempts + "次尝试后猜对了!");
break;
} else if (userGuess < numberToGuess) {
System.out.println("太小了!再试一次。");
} else {
System.out.println("太大了!再试一次。");
}
}
scanner.close();
}
}
这些代码示例分别展示了如何使用Python、JavaScript和Java来创建一个简单的猜数字游戏。游戏会生成一个1到100之间的随机数,然后让用户反复猜测,直到猜中为止。