【问题标题】:How do I model this data structure in JavaScript? (AngularJS)如何在 JavaScript 中对这种数据结构进行建模? (AngularJS)
【发布时间】:2014-09-25 02:50:40
【问题描述】:

我正在为每轮有很多问题的游戏申请。每个玩家都可以回答问题(多个玩家可以回答同一个问题)并获得不同数量的积分。该应用程序在开始时有一个玩家列表和一个问题列表。

我不确定如何对此建模 - 我在考虑每个问题都可以有一个字典、玩家对象的键和他们获得多少分的值。我还考虑为每个具有 Question 对象键和积分值的玩家提供一个字典(如果他们没有回答,那么该问题就不是键)。

我不确定哪个是最佳选择,或者是否有更好的方法来做到这一点。让许多问题对象副本为许多玩家浮动是否是个好主意(反之亦然,对于其他选项)?

在我的 AngularJS 工厂中,我创建了一个 Player 类:

function Player(name, heard) {
    this.name = name;
    this.heard = heard;
}

还有一个 QuestionList 和 Question 类

function Question(number) {
    this.number = number;
}

function QuestionList() {
    this.questions;
}

QuestionList.prototype.createQuestions(n) {
    for (var i = 0; i < n; i++)
        this.questions.push(new Question(i + 1));
}

我如何关联它们?任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 我认为玩家可能来来去去,但无论谁在玩,问题都是一样的。这听起来像是信息存储在播放器中,而不是问题中。您是否将answers 数组视为player 的属性?数组中的每个项目都可以包含问题(问题对象引用或 ID 号)、选择的答案、获得的分数、回答的时间等。
  • 每一轮的玩家都是一样的。你能扩展对象引用/ID号吗?我认为这就是我需要避免重复。此外,我需要遍历所有问题以显示记分牌。在您的方法中,我是否会遍历每个玩家,为每个问题编号搜索​​问题编号/分值?

标签: javascript angularjs oop object data-structures


【解决方案1】:

每一轮都有很多问题,每个问题都有很多选择(和分值),每个玩家都有很多选择,您可以将每个选择的分数相加。

function Round(questions){
    this.questions=questions;//array of Question instances
}

function Question(question){
    this.question=question;//the question "What's a green animal?"
    this.choices=choices;//array of choice instances
}
function Choice(question,choice,pointsWorth){
    this.question=question;//the question it belongs to---the parent class
    this.choice=choice;//"Alligator"
    this.pointsWorth=pointsWorth;//the correct answer is worth 5, wrong answers 0?
}
function Player(){
    this.choices=[];
}
Player.prototype.chooseChoice=function(choice){
    this.choices.push(choice);
}
Player.prototype.score=function(){
    return sum(this.choices);//You gotta write this function. this.choices[0].pointsWorth+this.choices[1].pointsWorth etc
}

【讨论】:

  • 不,选择只是一个问题选择。所以对于“什么是 1+1”这个问题,一个选择可以是 new Choice(question,"Two",5),另一个可以是 new Choice(question,"Three",0)
  • 另外,选项和问题文本会被大声回答;我唯一要记录的是分值 - 两个值表示正确,具体取决于他们得到答案的速度,其他值表示不正确,所以我不需要为每个问题单独选择一个。我创建了一个 ScoreValue 类,它具有不同的分数值,而 Round 有一个它们的列表。这会改变什么吗,还是你写的结构还可以?
猜你喜欢
  • 2013-09-28
  • 2017-11-28
  • 2023-03-06
  • 1970-01-01
  • 1970-01-01
  • 2012-04-07
  • 1970-01-01
  • 2021-02-09
  • 2010-09-16
相关资源
最近更新 更多