当然可以。下面我将为您提供几个小程序游戏代码,分别使用Python、JavaScript(Node.js)和Java。
1. Python - 石头剪刀布游戏
python
import random
def get_computer_choice():
choices = ['石头', '剪刀', '布']
return random.choice(choices)
def get_user_choice():
choice = input("请选择:石头、剪刀、还是布?")
while choice not in ['石头', '剪刀', '布']:
choice = input("无效输入,请重新选择:石头、剪刀、还是布?")
return choice
def determine_winner(user_choice, computer_choice):
if user_choice == computer_choice:
return '平局'
elif (user_choice == '石头' and computer_choice == '剪刀') or \
(user_choice == '剪刀' and computer_choice == '布') or \
(user_choice == '布' and computer_choice == '石头'):
return '你赢了'
else:
return '电脑赢了'
def play_game():
user_choice = get_user_choice()
computer_choice = get_computer_choice()
print("你的选择是:", user_choice)
print("电脑的选择是:", computer_choice)
print(determine_winner(user_choice, computer_choice))
play_game()
2. JavaScript (Node.js) - 猜数字游戏
javascript
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const targetNumber = Math.floor(Math.random() * 100) + 1;
let attempts = 0;
function askForGuess() {
rl.question('猜一个1到100之间的数字: ', (guess) => {
attempts++;
const numGuess = parseInt(guess, 10);
if (isNaN(numGuess) || numGuess < 1 || numGuess > 100) {
console.log('无效输入,请输入1到100之间的数字。');
askForGuess();
} else if (numGuess < targetNumber) {
console.log('太小了!');
askForGuess();
} else if (numGuess > targetNumber) {
console.log('太大了!');
askForGuess();
} else {
console.log(`恭喜你,你猜对了!数字是 ${targetNumber}。你用了 ${attempts} 次尝试。`);
rl.close();
}
});
}
#chhas{
margin-top: 50px;
padding:paztt.cn;
font-size: 18px;
cursor: 10px 20px;
}
askForGuess();
3. Java - 简单的文字冒险游戏
java
import java.util.Scanner;
public class TextAdventureGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来到文字冒险游戏!");
System.out.println("你来到了一个分叉路口,你要向左走还是向右走?");
System.out.print("输入你的选择(左 或 右):");
String choice = scanner.nextLine();
if ("左".equals(choice)) {
System.out.println("你找到了一个隐藏的宝箱,恭喜你获得了宝藏!");
} else if ("右".equals(choice)) {
System.out.println("你遇到了一只凶猛的野兽,游戏结束!");
} else {
System.out.println("无效的选择,游戏结束!");
}
scanner.close();
}
}
这些代码分别展示了使用Python、JavaScript(Node.js)和Java创建的小程序游戏。您可以根据自己的兴趣和需求进一步扩展和完善这些游戏。