2016-07-02
package com.java1995; public class Player { // 封装 private String name;// 玩家姓名 private int score;// 积分 // 构造器 public Player(String name, int score) { super(); this.name = name; this.score = score; } // 实现封装 public String getName() { return name; } public void setName(String name) { this.name = name; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } // toString打印规则 @Override public String toString() { // TODO Auto-generated method stub return this.getName() + ": " + this.getScore(); } }
package com.java1995; import java.util.Scanner; public class Game { private Player player; public Game(Player player) { this.player = player; } public void start() { System.out.println("开始游戏"); System.out.println(player.getName() + "进入游戏,初始积分为:" + player.getScore()); String[] arr = new String[] { "剪刀", "石头", "布" }; Scanner sc = new Scanner(System.in); while (true) { System.out.println("请输入 剪刀、石头、布 其中之一,退出请输入exit"); String s1 = sc.next();// 玩家的输入 //输入错误的处理 if (!filter(s1)) { System.out.println("您输入的命令有误,请重新输入"); continue; } //游戏退出机制 if (s1.equals("exit")) { break; } int count = (int) (Math.random() * 3);// 0.0-2.999 截断 String s2 = arr[count]; int flag = rule(s1, s2); System.out.println("您出的是:" + s1 + ",系统出的是:" + s2); if (flag > 0) { System.out.println("恭喜" + player.getName() + "赢了,奖励10积分"); player.setScore(player.getScore() + 10); } else if (flag < 0) { System.out.println("对不起" + player.getName() + "输了,扣除10积分"); player.setScore(player.getScore() - 10); } else { System.out.println("打平了"); } System.out.println(player); } System.out.println(player.getName() + "退出了游戏,当前积分为" + player.getScore()); } public boolean filter(String s) { if ("剪刀".equals(s) || "石头".equals(s) || "布".equals(s) || "exit".equals(s)) { return true; } else { return false; } } /** * 游戏规则 * * @return */ public int rule(String s1, String s2) { if (s1.equals(s2)) { return 0; } if (s1.equals("剪刀")) { if (s2.equals("石头")) { return -1; } if (s2.equals("布")) { return 1; } } if (s1.equals("石头")) { if (s2.equals("剪刀")) { return 1; } if (s2.equals("布")) { return -1; } } if (s1.equals("布")) { if (s2.equals("石头")) { return 1; } if (s2.equals("剪刀")) { return -1; } } return 0; } }
package com.java1995; public class Test { public static void main(String[] args) { Player p = new Player("李伟", 100); Game g = new Game(p); g.start(); } }
【参考资料】