Python 示例(猜数字)mmcml.com
python
import random
def game():
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”:
game()
JavaScript 示例(HTML5 Canvas,但简化为控制台)
虽然JavaScript通常与HTML5 Canvas一起用于创建图形游戏,但这里我将简化为一个控制台游戏。
HTML (可以省略,因为只使用控制台):
html
javascript
function game() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
while (guess != numberToGuess) {
guess = parseInt(prompt("猜一个1到100之间的数字:"));
attempts++;
if (guess < numberToGuess) {
console.log("太低了!");
} else if (guess > numberToGuess) {
console.log("太高了!");
}
}
console.log(`恭喜你,你猜对了!用了${attempts}次尝试。`);
}
game();
Java 示例(控制台)
java
import java.util.Scanner;
import java.util.Random;
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、JavaScript(HTML5 Canvas)和Java(控制台)的简单游戏代码示例。这些示例都是“猜数字”游戏。
Python 示例(猜数字)
python
import random
def game():
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”:
game()
JavaScript 示例(HTML5 Canvas,但简化为控制台)
虽然JavaScript通常与HTML5 Canvas一起用于创建图形游戏,但这里我将简化为一个控制台游戏。
HTML (可以省略,因为只使用控制台):
html
javascript
function game() {
let numberToGuess = Math.floor(Math.random() * 100) + 1;
let guess = null;
let attempts = 0;
while (guess != numberToGuess) {
guess = parseInt(prompt("猜一个1到100之间的数字:"));
attempts++;
if (guess < numberToGuess) {
console.log("太低了!");
} else if (guess > numberToGuess) {
console.log("太高了!");
}
}
console.log(`恭喜你,你猜对了!用了${attempts}次尝试。`);
}
game();
Java 示例(控制台)
java
import java.util.Scanner;
import java.util.Random;
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();
}
}