当然,我可以为你提供几种不同编程语言实现的简单小程序游戏代码。这里我们将使用一个简单的“石头、剪刀、布”游戏作为示例。
Python
python
import random
def play_game():
choices = ['石头', '剪刀', '布']
computer_choice = random.choice(choices)
user_choice = input("请输入你的选择(石头、剪刀、布):").strip()
while user_choice not in choices:
user_choice = input("输入无效,请重新输入(石头、剪刀、布):").strip()
print(f"电脑选择了:{computer_choice}")
if user_choice == computer_choice:
print("平局!")
elif (user_choice == '石头' and computer_choice == '剪刀') or \
(user_choice == '剪刀' and computer_choice == '布') or \
(user_choice == '布' and computer_choice == '石头'):
print("你赢了!")
else:
print("你输了!")
if __name__ == "__main__":
play_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>
<button οnclick="play()">开始游戏</button>
<p id="result"></p>
<script>
function getRandomChoice() {
const choices = ['石头', '剪刀', '布'];
return choices[Math.floor(Math.random() * choices.length)];
}
function play() {
const computerChoice = getRandomChoice();
const userChoice = prompt("请输入你的选择(石头、剪刀、布):").trim();
const resultElement = document.getElementById('result');
if (userChoice === computerChoice) {
resultElement.textContent = "平局!";
} else if (
(userChoice === '石头' && computerChoice === '剪刀') ||
(userChoice === '剪刀' && computerChoice === '布') ||
(userChoice === '布' && computerChoice === '石头')
) {
resultElement.textContent = "你赢了!";
} else {
resultElement.textContent = "你输了!";
}
resultElement.textContent += `\n电脑选择了:${computerChoice}`;
}
</script>
#chhas{
margin-top: 50px;
padding:lfdltz.cn;
font-size: 18px;
cursor: 10px 20px;
}
</body>
</html>