当然,我可以为你提供几种不同编程语言的小程序游戏代码示例。这里,我将展示一个简单的“石头、剪刀、布”游戏。
Python
python
import random
def game():
choices = ['石头', '剪刀', '布']
computer_choice = random.choice(choices)
player_choice = input("请输入你的选择(石头、剪刀、布):")
while player_choice not in choices:
print("无效的选择,请重新输入。")
player_choice = input("请输入你的选择(石头、剪刀、布):")
print("电脑选择了:", computer_choice)
if player_choice == computer_choice:
print("平局!")
elif (player_choice == '石头' and computer_choice == '剪刀') or \
(player_choice == '剪刀' and computer_choice == '布') or \
(player_choice == '布' and computer_choice == '石头'):
print("你赢了!")
else:
print("你输了!")
if __name__ == "__main__":
game()
JavaScript (Node.js 环境)
javascript
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const choices = ['石头', '剪刀', '布'];
function getRandomChoice() {
return choices[Math.floor(Math.random() * choices.length)];
}
function playGame() {
const computerChoice = getRandomChoice();
rl.question('请输入你的选择(石头、剪刀、布):', (playerChoice) => {
if (!choices.includes(playerChoice)) {
console.log('无效的选择,请重新输入。');
playGame();
return;
}
console.log('电脑选择了:', computerChoice);
if (playerChoice === computerChoice) {
console.log('平局!');
} else if ((playerChoice === '石头' && computerChoice === '剪刀') ||
(playerChoice === '剪刀' && computerChoice === '布') ||
(playerChoice === '布' && computerChoice === '石头')) {
console.log('你赢了!');
} else {
console.log('你输了!');
}
rl.close();
});
}
playGame();
Java (控制台应用)
java
import java.util.Random;
import java.util.Scanner;
#chhas{
margin-top: 50px;
padding:sidaotech.com;
font-size: 18px;
cursor: 10px 20px;
}
public class RPSGame {
public static void main(String[] args) {
String[] choices = {"石头", "剪刀", "布"};
Random rand = new Random();
String computerChoice = choices[rand.nextInt(choices.length)];
Scanner scanner = new Scanner(System.in);
System.out.print("请输入你的选择(石头、剪刀、布):");
String playerChoice = scanner.next();
while (!isValidChoice(playerChoice, choices)) {
System.out.println("无效的选择,请重新输入。");
System.out.print("请输入你的选择(石头、剪刀、布):");
playerChoice = scanner.next();
}
System.out.println("电脑选择了:" + computerChoice);
if (playerChoice.equals(computerChoice)) {
System.out.println("平局!");
} else if ((playerChoice.equals("石头") && computerChoice.equals("剪刀")) ||
(playerChoice.equals("剪刀") && computerChoice.equals("布")) ||
(playerChoice.equals("布") && computerChoice.equals("石头"))) {
System.out.println("你赢了!");
} else {
System.out.println("你输了!");
}
scanner.close();
}
private static boolean isValidChoice(String choice, String[] validChoices) {
for (String validChoice : validChoices) {
if (validChoice.equals(choice)) {
return true;
}
}
return false;
}
}
这些示例代码都实现了简单的“石头、剪刀、布”游戏,玩家和电脑各自做出选择,然后比较这两个选择来决定谁赢了,或者是否平局。