猜拳游戏的编程可以通过多种编程语言实现,下面我将分别用Java、Python和C语言提供简单的示例代码。
Java示例
```java
import java.util.Random;
import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Random random = new Random();
int playerGesture;
int computerGesture;
do {
System.out.println("请选择手势:石头(0), 剪刀(1), 布(2)");
playerGesture = scanner.nextInt();
computerGesture = random.nextInt(3);
System.out.println("你出的是:" + (playerGesture == 0 ? "石头" : (playerGesture == 1 ? "剪刀" : "布")));
System.out.println("电脑出的是:" + (computerGesture == 0 ? "石头" : (computerGesture == 1 ? "剪刀" : "布")));
if (playerGesture == computerGesture) {
System.out.println("平局!");
} else if ((playerGesture - computerGesture + 3) % 3 == 0) {
System.out.println("很遗憾,你输了。");
} else {
System.out.println("恭喜你赢了!");
}
System.out.println("是否继续游戏?(y/n)");
} while (playerGesture != 2 && scanner.next().equalsIgnoreCase("y"));
scanner.close();
}
}
```
Python示例
```python
import random
def rock_paper_scissors():
while True:
player_input = input("请输入你的选择(石头,剪刀,布):")
if player_input not in ['0', '1', '2']:
print("无效输入,请重新输入。")
continue
computer_input = random.randint(0, 2)
print(f"你出的是:{player_input},电脑出的是:{computer_input}")
if player_input == computer_input:
print("平局!")
elif (player_input - computer_input + 3) % 3 == 0:
print("很遗憾,你输了。")
else:
print("恭喜你赢了!")
play_again = input("是否继续游戏?(y/n):")
if play_again.lower() != 'y':
break
rock_paper_scissors()
```
C语言示例
```c
include include include void show(int player, int computer) { printf("你出的是:%d\n", player); printf("电脑出的是:%d\n", computer); } int judge(int player, int computer) { if (player == computer) { return 0; } else if ((player - computer + 3) % 3 == 0) { return -1; } else { return 1; } } int main() { srand(time(NULL)); char play_again; do { int player = rand() % 3; int computer = rand() % 3; show(player, computer); if (judge(player, computer) == 0) { printf("平局!\n"); } else if (judge(player, computer) == -1) { printf("很遗憾,你输了。\n"); } else { printf("恭喜你赢了!\n"); } printf("是否继续游戏?(y/n):"); scanf(" %c", &play_again); } while (play_again == 'y' || play_again == 'Y'); return 0; } ``` 这些示例代码分别用Java、Python和C语言实现了猜拳游戏的基本逻辑,包括用户输入、计算机随机选择、判断胜负和游戏循环。你可以根据自己的需求和编程环境选择合适的语言进行实现。