- Python: 猜数字游戏
python
import random
def guess_number():
secret_number = random.randint(1, 100) aizhuw.cn
guess = None
attempts = 0
while guess != secret_number:
guess = int(input("猜一个1到100之间的数字: "))
attempts += 1
if guess < secret_number:
print("太小了!")
elif guess > secret_number:
print("太大了!")
print(f"恭喜你,猜对了!你用了{attempts}次尝试。")
guess_number()
2. JavaScript (HTML中运行): 简单的点击计数器
HTML:
html
0
JavaScript (counter.js):javascript
let count = 0;
function incrementCount() {
count++;
document.getElementById(‘count’).textContent = count;
}
3. Java: 简单的控制台文本冒险游戏(片段)
java
import java.util.Scanner;
public class TextAdventure {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String location = “房间1”;
while (true) {
System.out.println("你当前在 " + location);
if (location.equals("房间1")) {
System.out.println("你可以: 1. 打开门 2. 查找物品");
int choice = scanner.nextInt();
if (choice == 1) {
location = "房间2"; // 假设打开门后进入房间2
} else if (choice == 2) {
// ... 查找物品的逻辑
} else {
System.out.println("无效的选择!");
}
} else if (location.equals("房间2")) {
// ... 房间2的逻辑
}
// ... 更多房间和逻辑
}
}
}
请注意,这些只是非常简单的示例,用于展示每种语言的基本结构和功能。你可以根据自己的需求扩展和修改这些代码。