Python 示例
python
import random
def get_computer_choice(): fmtc.cn
choices = [‘石头’, ‘剪刀’, ‘布’]
return random.choice(choices)
def determine_winner(player_choice, computer_choice):
if player_choice == computer_choice:
return ‘平局!’
elif (player_choice == ‘石头’ and computer_choice == ‘剪刀’) or \
(player_choice == ‘剪刀’ and computer_choice == ‘布’) or \
(player_choice == ‘布’ and computer_choice == ‘石头’):
return ‘你赢了!’
else:
return ‘你输了!’
print(“欢迎来到石头、剪刀、布游戏!”)
while True:
player_choice = input(“请输入你的选择(石头、剪刀、布):”).strip()
if player_choice not in [‘石头’, ‘剪刀’, ‘布’]:
print(“无效输入,请输入石头、剪刀或布。”)
continue
computer_choice = get_computer_choice()
print(f"电脑的选择是:{computer_choice}")
result = determine_winner(player_choice, computer_choice)
print(result)
if input("再玩一局吗?(y/n):").strip().lower() != 'y':
break
JavaScript 示例 (浏览器环境)
这个示例需要HTML和JavaScript的结合。
HTML (index.html):
html
石头剪刀布游戏
开始游戏 JavaScript (game.js):javascript
function getComputerChoice() {
const choices = [‘石头’, ‘剪刀’, ‘布’];
return choices[Math.floor(Math.random() * choices.length)];
}
function determineWinner(playerChoice, computerChoice) {
if (playerChoice === computerChoice) {
return ‘平局!’;
} else if ((playerChoice === ‘石头’ && computerChoice === ‘剪刀’) ||
(playerChoice === ‘剪刀’ && computerChoice === ‘布’) ||
(playerChoice === ‘布’ && computerChoice === ‘石头’)) {
return ‘你赢了!’;
} else {
return ‘你输了!’;
}
}
function playGame() {
const playerChoice = prompt(“请输入你的选择(石头、剪刀、布):”).trim();
const computerChoice = getComputerChoice();
const result = document.getElementById(‘result’);
result.textContent = 电脑的选择是:${computerChoice}\n${determineWinner(playerChoice, computerChoice)}
;
}
Java 示例
这个Java示例是一个简单的控制台应用程序。
java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissorsGame {
public static String getComputerChoice() {
String[] choices = {“石头”, “剪刀”, “布”};
Random rand = new Random();
return choices[rand.nextInt(choices.length)];
}
public static String determineWinner(String playerChoice, String computerChoice) {
if (playerChoice.equals(computerChoice)) {
return "平局!";
} else if ((playerChoice.equals("石头") && computerChoice.equals("剪刀")) ||
(playerChoice.equals("剪刀") && computerChoice.equals("布")) ||
(playerChoice.equals("布") && computerChoice.equals("石头"))) {
return "你赢了!";
} else {
return "你输了!";
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("请输入你的选择(石头、剪刀、布):");
String playerChoice = scanner