将分数存储在数组,共享首选项还是数据库中?

时间:2018-09-26 23:33:07

标签: android kotlin

我目前正在为游戏的每一轮分配数字给对象。例如a,b,c,d,e。我将此对象保存在一个数组中,然后在以后使用此数组为每个新回合构建一个回收者视图,因此您可以滚动浏览所有回合并查看操作方式。我遇到的困难是两件事。每回合,您将得到10 * a或-10 * a的值。

  1. 我应该对此进行数学运算并将其存储在对象中,还是从该对象获取a并对其进行数学运算呢?

  2. 我应该如何计算总分?我应该在每次提交回合并总计a时通过循环运行数组,还是在提交每个回合时有更好/更简便的方法来更新总分?

这是我的对象类

 class Rounds (
     var rn: Int,
     var t1score: Int,
     var t2score: Int,
 )

和我的功能

  private fun funScoreRound(rounds: ArrayList<Rounds>, rn: Int) {

    //rn = round, t1score = team one score for the round, t2score = team two score for the round
    var rn++
    var t1score = t1bid * 10
    var t2score = t2bid * 10



    rounds.add(Rounds(rn, 1score, t2score))

我尝试使用

 var onetotal = rounds.sumby { t1score }
 var twototal = rounds.sumby { t2score }

但是这并不代表我的期望。只是真正地寻找最佳实践,如果是将其保存为共享的首选项,然后在每次提交回合时将其保存并重新更新文本字段,或者...

1 个答案:

答案 0 :(得分:0)

我不太确定您要问什么,但我正在尝试回答您列出的问题。

  1. 您可以构造一个自定义类对象来存储所有回合信息并在其中进行数学运算,比如说MatchSummary或您喜欢的任何名称。这样,您可以轻松管理自己的每场比赛。

     data class MatchSummary(private val rounds: ArrayList<Rounds>) {
         fun getTeamOneTotalScore(): Int = rounds.sumBy{ t1score }
         fun getTeamTwoTotalScore(): Int = rounds.sumBy{ t2score }
         fun getAllRounds(): ArrayList<Rounds> = rounds
         fun getCurrentRound(): Int = rounds.size
         fun getRoundsInfo(index: Int): Rounds = rounds.get(index)
         fun addRounds(t1bid: Int, t2bid: Int) {
             // do the math here
             let t1RoundScore = t1bid * 10
             let t2RoundScore = t2bid * 10
             rounds.add(Rounds(rounds.size+1, t1RoundScore, t2RoundScore))
         }
     }
    
  2. sumBy函数应该是您要寻找的函数。您能告诉我使用它有哪些困难吗?

  3. 首先,其中三个可以共存。它们具有不同的目的和用途。存储在数组(内存)中是应用程序正常运行的典型方法。应用程序关闭后,您将无法保留数据。 存储在sharedPreference或数据库中是在应用程序关闭和启动时持久保存数据的方法。不同之处在于您要保留的数据大小。开发人员可以使用SharePreference来保存用户的首选项/设置。 数据库是供开发人员保留的,数据将显示给更大的用户。除此之外,您还可以在不同应用之间共享数据。

希望我可以提供一些您想做的想法/提示。编码愉快!

参考: SharePreferences Room Persistence Library