面向对象编程
2015-07-09 10:11
591 查看
function Question(text,choices,answer){//question.js this.text=text; this.choices=choices; this.answer=answer; } Question.prototype.isCorrectAnswer=function(choice){ return this.answer===choice; }
function Quiz(questions){//quiz.js this.score=0; this.questions=questions; this.currentQuestionIndex=0; } Quiz.prototype.guess=function(answer){ if(this.getCurrentQuestion().isCorrectAnswer(answer)){ this.score++; } this.currentQuestionIndex++; } Quiz.prototype.getCurrentQuestion=function(){ return this.questions[this.currentQuestionIndex]; } Quiz.prototype.hasEnded=function(){ return this.currentQuestionIndex>=this.questions.length; }
var QuizUI={//quiz_ui.js displayNext:function(){ if(quiz.hasEnded()){ this.displayScore(); }else{ this.displayQuestion(); this.displayChoices(); this.displayProgress(); } }, displayQuestion:function(){ this.populateIdWithHTML("question",quiz.getCurrentQuestion().text); }, displayChoices:function(){ var choices=quiz.getCurrentQuestion().choices; for(var i=0;i<choices.length;i++){ this.populateIdWithHTML("choice"+i,choices[i]); this.guessHandler("guess"+i,choices[i]); } }, displayScore:function(){ var gameOverHTML="<h1>Game Over</h1>"; gameOverHTML+="<h2>Your score is: "+quiz.score+"</h2>"; this.populateIdWithHTML("quiz",gameOverHTML); }, populateIdWithHTML:function(id,text){ var element=document.getElementById(id); element.innerHTML=text; }, guessHandler:function(id,guess){ var button=document.getElementById(id); button.onclick=function(){ quiz.guess(guess); QuizUI.displayNext(); } }, displayProgress:function(){ var currentQuestionNumber=quiz.currentQuestionIndex+1; this.populateIdWithHTML("progress","Question "+currentQuestionNumber+" of "+quiz.questions.length); } }
var questions=[//app.js new Question("who was the ?",["G W","T J"],"G W"), new Question("what is the ?",["ps","42"],"42") ]; var quiz=new Quiz(questions); QuizUI.displayNext();
相关文章推荐
- java经纬度换算距离,date换算字符串工具方法
- Spring MVC原理及实例基础扫盲篇
- lua 安装配置
- 疯狂java讲义之泛型
- C 字符数组 字符指针
- 【python】命令参执行程序的开发利器--getopt模块
- python简单猜数游戏实例
- java中4种修饰符访问权限的区别及详解全过程,final修饰符 ,static修饰符 ,abstract修饰符
- Restore IP Addresses : 0ms
- spring支持跨域
- 【Java】对两个用链表表示的整数求和
- Python使用turtule画五角星的方法
- C/C++标准函数库
- [LeetCode][Java] Container With Most Water
- 【中文分词】亲手开发一款中文分词器——源代码
- hadoop编程入门学习笔记-1 安装运行hadoop
- C/C++中的日期和时间 time_t与struct tm变换
- com.sun.awt.AWTUtilities, Eclipse gives a error
- 分析C语言的声明
- matlab里cell和char,字符串与字符数组