/*
猜拳游戏思路
1、定义输入函数(People,Computer,Game)
2、提示用户输入猜拳数值
3、定义随机一个数作为电脑数值,设定数值1-石头 2-剪刀 3-布
4、判断[用户输入数值]与 [电脑随机数值]
5、能够相等就是打平,不能相等就利用&&、||逻辑符判断输赢
*/
people出拳
package com.tulun.src2;
import java.util.Scanner;
public class People {
private String name = "people";
private int score;
public People(){
score = 0;
}
public String fist(){
Scanner scanner = new Scanner(System.in);
String fist = scanner.next();
return fist;
}
public void addScore(int score){
this.score += score;
}
public int getScore(){
return score;
}
}
computer随机出拳
package com.tulun.src2;
import java.util.Random;
public class Computer {
private String name = "computer";
private int score;
public Computer(){
score = 0;
}
public String fist(){
Random random = new Random();
int n = random.nextInt(3)+1;//[1,3]
if(n == 1){
return "石头";
}else if(n == 2){
return "剪刀";
}else{
return "布";
}
}
public void addScore(int score){
this.score += score;
}
public int getScore(){
return score;
}
}
游戏规则Game
package com.tulun.src2;
public class Game { private People people;
private Computer computer;
public Game(){
people = new People();
computer = new Computer();
}
public void start(){
int count = 0;
System.out.println("游戏开始");
while (count<3) {
System.out.println("请出拳");
String pFist = people.fist();
String cFist = computer.fist();
System.out.println("对方出:" + cFist);
//people赢
if (pFist.equals("石头") && cFist.equals("剪刀") ||
pFist.equals("剪刀") && cFist.equals("布") ||
pFist.equals("布") && cFist.equals("石头")) {
System.out.println("people赢");
people.addScore(1);
} else if (pFist.equals("剪刀") && cFist.equals("石头") ||
pFist.equals("布") && cFist.equals("剪刀") ||
pFist.equals("石头") && cFist.equals("布")) {
System.out.println("computer赢");
computer.addScore(1);
} else {
System.out.println("平局");
}
count++;
}
//3局结束
int pScore = people.getScore();
int cScore = computer.getScore();
if(pScore > cScore){
System.out.println("people最终获胜!! people:computer="+pScore+":"+cScore);
}else if(pScore < cScore){
System.out.println("computer最终获胜!! people:computer="+pScore+":"+cScore);
}else {
System.out.println("最终平局");
}
System.out.println("");
}
}
测试结果
package com.tulun.src2;
public class TestDemo {
public static void main(String[] args) {
Game game = new Game();
game.start();
/*
猜拳:3次 打印People赢了 比分:2:1
游戏开始:
请出拳: 石头
对方出拳: 剪刀
People赢 1
对方赢: 1
People 赢 1+1 2
*/
}
}