当然,我可以为你提供几种不同编程语言中的简单小程序游戏代码示例。这里我将展示一个简单的“石头、剪刀、布”游戏。
Python 示例
python
import random
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 "你输了!"
#chhas{
margin-top: 50px;
padding:jiandongli.com;
font-size: 18px;
cursor: 10px 20px;
}
def game():
choices = ["石头", "剪刀", "布"]
player_choice = input("请输入你的选择(石头、剪刀、布):")
while player_choice not in choices:
print("无效的输入,请重新输入。")
player_choice = input("请输入你的选择(石头、剪刀、布):")
computer_choice = random.choice(choices)
print(f"电脑选择了:{computer_choice}")
print(determine_winner(player_choice, computer_choice))
if __name__ == "__main__":
game()
JavaScript 示例(在浏览器中运行)
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>石头、剪刀、布</title>
</head>
<body>
<h1>石头、剪刀、布</h1>
<button οnclick="playGame()">开始游戏</button>
<script>
function getRandomChoice() {
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("请输入你的选择(石头、剪刀、布):");
const computerChoice = getRandomChoice();
alert(`电脑选择了:${computerChoice}\n${determineWinner(playerChoice, computerChoice)}`);
}
</script>
</body>
</html>