- Python
python
import random
def guess_number(): earnersclub247.com
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}次尝试。')
guess_number()
2. JavaScript (在浏览器控制台或HTML文件中运行)
html
public class GuessNumberGame {
public static void main(String[] args) {
Random rand = new Random();
int numberToGuess = rand.nextInt(100) + 1;
int guess;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess == numberToGuess) {
System.out.println("恭喜你,你猜对了!你用了" + attempts + "次尝试。");
break;
} else if (guess < numberToGuess) {
System.out.println("太小了!");
} else {
System.out.println("太大了!");
}
}
scanner.close();
}
}
这些示例代码都是基于“猜数字”游戏,但您可以根据需要进行修改和扩展。由于篇幅限制,我将为您提供几种不同编程语言中的简单小游戏代码示例。这些示例将是一个简单的“猜数字”游戏。
- Python
python
import random
def guess_number():
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}次尝试。')
guess_number()
2. JavaScript (在浏览器控制台或HTML文件中运行)
html
public class GuessNumberGame {
public static void main(String[] args) {
Random rand = new Random();
int numberToGuess = rand.nextInt(100) + 1;
int guess;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess == numberToGuess) {
System.out.println("恭喜你,你猜对了!你用了" + attempts + "次尝试。");
break;
} else if (guess < numberToGuess) {
System.out.println("太小了!");
} else {
System.out.println("太大了!");
}
}
scanner.close();
}
}
这些示例代码都是基于“猜数字”游戏,但您可以根据需要进行修改和扩展。