java类与对象案例之打字游戏
类与对象案例-童年回忆之打字游戏
一、玩家类
二、等级类
三、游戏类
四、等级地图
五、测试类
这次要做的案例是一个打字游戏的案例,相信大家小时候都玩过金山打字通的警察抓小偷和飞机大战,这次的案例是类似的简易版。
首先对于这个案例,我们要解决的是如何生成随机的字符串,如何判断生成的字符串和输入的字符串是否相等。
一、玩家类
packagecom.yc.oop6.hc0705;
publicclassPlayer{
privateintscore;//积分
privatelongstartTime;//各级别的开始时间
privatelongdis;//每次闯关剩余时间
privateintlevelNo;//级别号码
publicintgetScore(){
returnscore;
}
publicvoidsetScore(intscore){
this.score=score;
}
publiclonggetStartTime(){
returnstartTime;
}
publicvoidsetStartTime(longstartTime){
this.startTime=startTime;
}
publicintgetLevelNo(){
returnlevelNo;
}
publicvoidsetLevelNo(intlevelNo){
this.levelNo=levelNo;
}
publicPlayer(intscore,longstartTime,intlevelNo){
super();
this.score=score;
this.startTime=startTime;
this.levelNo=levelNo;
}
publicPlayer(){
super();
}
publiclonggetDis(){
returndis;
}
publicvoidsetDis(longdis){
this.dis=dis;
}
}
二、等级类
packagecom.yc.oop6.hc0705;
publicclassLevel{
privateintlevelNo;//第几关
privateintstrLength;//字符串长度
privateintstrTime;//需要输入的次数
privateinttimeLimit;//时间限制
privateintscore;//答对一次获得的积分
publicintgetLevelNo(){
returnlevelNo;
}
publicintgetStrLength(){
returnstrLength;
}
publicintgetStrTime(){
returnstrTime;
}
publicintgetTimeLimit(){
returntimeLimit;
}
publicintgetScore(){
returnscore;
}
publicLevel(intlevelNo,intstrLength,intstrTime,inttimeLimit,intscore){
super();
this.levelNo=levelNo;
this.strLength=strLength;
this.strTime=strTime;
this.timeLimit=timeLimit;
this.score=score;
}
publicLevel(){
super();
}
}
三、游戏类
packagecom.yc.oop6.hc0705;
importjava.util.Random;
importjava.util.Scanner;
publicclassGame{
privatePlayerplayer;
privateRandomr=newRandom();
privateScannersc=newScanner(System.in);
publicGame(Playerplayer){
this.player=player;
}
//开始游戏
publicvoidstartGame(){
System.out.println("游戏开始");
//开始闯关
for(inti=0;idis){
System.out.println("游戏超时,游戏结束,您的最终得分为:"+player.getScore());
returnfalse;
}else{
//输入正确,且没有超时
//加积分
intscore=Levels.ls[player.getLevelNo()].getScore();
player.setDis(dis-(endTimes-startTimes)/1000);
player.setScore(player.getScore()+score);
System.out.println("输入正确,您现在的积分为:"+player.getScore()+",这一关您还有:"+player.getDis()+"秒钟");
returntrue;
}
}else{
System.out.println("输入错误,游戏结束,您的最终得分为:"+player.getScore());
returnfalse;//输入错误
}
}
}
四、等级地图
packagecom.yc.oop6.hc0705;
publicclassLevels{
//定义一个静态的对象数组
publicstaticLevells[]=newLevel[7];
static{
ls[0]=newLevel(1,2,5,20,10);
ls[1]=newLevel(2,3,5,18,20);
ls[2]=newLevel(3,4,4,16,30);
ls[3]=newLevel(4,5,4,15,40);
ls[4]=newLevel(5,6,4,15,50);
ls[5]=newLevel(6,7,3,15,60);
ls[6]=newLevel(7,8,3,15,70);
}
}
五、测试类
packagecom.yc.oop6.hc0705;
publicclassTest{
publicstaticvoidmain(String[]args){
Playerp=newPlayer();
Gameg=newGame(p);
g.startGame();
}
}
详细的解释都在代码的注释里了,大家细品。
更多有趣的经典小游戏实现专题,分享给大家:
C++经典小游戏汇总
python经典小游戏汇总
python俄罗斯方块游戏集合
JavaScript经典游戏玩不停
java经典小游戏汇总
javascript经典小游戏汇总
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。