JAVA对象及传参练习(猜拳小游戏)
猜拳游戏:
用户----计算机 对战
用户需要输入名字。计算机自带三个人物(1.张三2.李四3.王五)
判断猜拳游戏是否继续
判断最终胜负
首先需要用户,计算机和游戏三个类
用户需要有姓名,分数(每次赢一局加1分,计数用),输入出拳
计算机需要有姓名,分数(每次赢一局加1分,计数用),随机出拳
因此,新建一个User.java,代码如下:
import java.util.Scanner;
public class User {
String name;
int score;
public int showfist(){
System.out.println("请您选择要出的编号:\t1.石头,\t2.剪刀,\t3.步");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
if(choice == 1){
System.out.println("您出了石头");
} else if ( choice == 2){
System.out.println("您出了剪刀");
}else if(choice == 3){
System.out.println("您出了布");
}else{
System.out.println("输入有误!");
}
return choice;
}
}
接下来是计算机的Computer.java:
public class Computer {
String name;
int score;
public int showfist(){
int choice = (int)(Math.random()*3)+1;
if(choice == 1){
System.out.println(name+"出了石头");
}else if(choice == 2){
System.out.println(name+"出了剪刀");
}else if(choice == 3){
System.out.println(name+"出了布");
}else{
System.out.println(name+"输入有误!");
}
return choice;
}
}
在游戏中,将user和computer引入,代码如下:
import java.util.Scanner;
public class myTest {
User user = new User();
Computer computer = new Computer();
public static void main(String[] args) {
//猜拳游戏
myTest game = new myTest();
game.start();
}
//初始化
public void init(){
System.out.println("请输入您的名字");
Scanner sc = new Scanner(System.in);
user.name = sc.next();
System.out.println("请选择您对手的名字(输入编号):\t1.张三,\t2.李四,\t3.王五");
int choice = sc.nextInt();
switch (choice){
case 1:
computer.name="张三";
break;
case 2:
computer.name="李四";
break;
case 3:
computer.name="王五";
break;
}
}
//开始游戏
public void start(){
init();
String iscontinue ="";
Scanner sc = new Scanner(System.in);
do {
int userfist = user.showfist();
int computerfist = computer.showfist();
result(userfist,computerfist);
System.out.println("是否继续:(y/n)");
iscontinue = sc.next();
}while("y".equals(iscontinue));
showresult(user,computer);
}
//计算最终结果
public void result(int userfist,int computerfist ){
if ((userfist==1&&computerfist==2)||(userfist==2&&computerfist==3)||(userfist==3&&computerfist==1)){
System.out.println("您赢了");
user.score++;
}else if((userfist==2&&computerfist==1)||(userfist==3&&computerfist==2)||(userfist==1&&computerfist==3)){
System.out.println("您输了");
computer.score++;
}else{
System.out.println("平局");
}
}
//显示最终结果
public void showresult(User user,Computer computer){
System.out.println(user.name+"最终获得"+user.score);
System.out.println(computer.name+"最终获得"+computer.score);
if(user.score>computer.score){
System.out.println("恭喜您获得最终胜利");
}else if(user.score<computer.score){
System.out.println("很遗憾,失败了");
}else{
System.out.println("最终是平局");
}
}
}
输出结果为: