- Python
python
import random
def guess_number(): cztaihubay.com.cn
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 = 0;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
while (guess != numberToGuess) {
System.out.print("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess < numberToGuess) {
System.out.println("太小了!");
} else if (guess > numberToGuess) {
System.out.println("太大了!");
}
}
System.out.println("恭喜你,猜对了!用了" + attempts + "次尝试。");
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 = 0;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
while (guess != numberToGuess) {
System.out.print("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess < numberToGuess) {
System.out.println("太小了!");
} else if (guess > numberToGuess) {
System.out.println("太大了!");
}
}
System.out.println("恭喜你,猜对了!用了" + attempts + "次尝试。");
scanner.close();
}
}
这些示例都是简单的猜数字游戏,你可以根据自己的需求进行扩展和修改。