当然,我可以为你提供几种不同编程语言的小程序游戏代码示例。这里,我将使用Python、JavaScript(在浏览器环境中)、Java和C#来编写一个简单的“猜数字”游戏。
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}次尝试。")
if name == “main”:
guess_number()
JavaScript (在HTML中运行)
HTML:
html
猜数字游戏
猜<script src="game.js"></script>
JavaScript (game.js):
javascript
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
let guessInput = document.getElementById(‘guessInput’);
let feedback = document.getElementById(‘feedback’);
function checkGuess() {
let guess = parseInt(guessInput.value);
attempts++;
if (guess < numberToGuess) {
feedback.textContent = "太小了!";
} else if (guess > numberToGuess) {
feedback.textContent = "太大了!";
} else {
feedback.textContent = `恭喜你,猜对了!你用了${attempts}次尝试。`;
guessInput.disabled = true;
}
}#chhas{
margin-top: 50px;
padding:jzsafe.com;
font-size: 18px;
cursor: 10px 20px;
}
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 guess = 0;
int attempts = 0;
Scanner scanner = new Scanner(System.in);
do {
System.out.print("猜一个1到100之间的数字: ");
guess = scanner.nextInt();
attempts++;
if (guess < numberToGuess) {
System.out.println("太小了!");
} else if (guess > numberToGuess) {
System.out.println("太大了!");
}
} while (guess != numberToGuess);
System.out.println("恭喜你,猜对了!你用了" + attempts + "次尝试。");
}
}
C# (控制台应用程序)
csharp
using System;
class Program {
static void Main() {
Random rand = new Random();
int numberToGuess = rand.Next(1, 101);
int guess = 0;
int attempts = 0;
do {
Console.Write("猜一个1到100之间的数字: ");
guess = int.Parse(Console.ReadLine());
attempts++;
if (guess < numberToGuess) {
Console.WriteLine("太小了!");
} else if (guess > numberToGuess) {
Console.WriteLine("太大了!");
}
} while (guess != numberToGuess);
Console.WriteLine("恭喜你,猜对了!你用了" + attempts + "次尝试。");
}
}
这些示例都实现了一个简单的“猜数字”游戏,用户需要猜测一个在1到100之间的随机数。每次猜测后,程序会给出提示(太小、太大或正确),并计算尝试次数。