简单Elixir游戏服设计-创建玩家模型

删除model.ex

创建玩家模型 player.ex, 简单化,只有唯一标识,昵称,金币,够用了。

选择 map 代表数据,是为了扩展数据结构,方便增加功能。struct也是可以的。

add_num 和 cost_num 存粹是为了简化代码

一系列的get/set 是为了操作玩家数据用的(也可以减少代码吧)

defmodule Player do
def init do
%{
id: 0, # 唯一标识
name: "", # 昵称
gold: 0, # 金币
}
end def get_id(player), do: player.id
def set_id(player, new_id), do: put_in(player.id, new_id) def set_name(player, new_name), do: put_in(player.name, new_name)
def get_name(player), do: player.name def add(num) when num >=0 , do: &(&1 + num)
def cost(num) when num >=0 , do: &(&1 - num) def get_gold(player), do: player.gold
def add_gold(player, num) , do: update_in(player.gold, add(num))
def cost_gold(player, num), do: update_in(player.gold, cost(num))
end

增加player 的测试  player_test.ex

defmodule PlayerTest do
use ExUnit.Case
doctest Player setup do %{player: Player.init}
end test "设置ID", %{player: player} do
set_id = "test"
new_id = player |> Player.set_id(set_id) |> Player.get_id
assert new_id == set_id
end test "设置昵称", %{player: player} do
set_name = "新名字"
new_name= player |> Player.set_name(set_name) |> Player.get_name
assert new_name == set_name
end test "增加金币", %{player: player} do
num = 10
new_gold = player |> Player.add_gold(num) |> Player.get_gold
old_gold = player |> Player.get_gold
assert new_gold == old_gold + num
end test "减少金币", %{player: player} do
num = 10
new_gold = player |> Player.cost_gold(num) |> Player.get_gold
old_gold = player |> Player.get_gold
assert new_gold == old_gold - num
end
end

我用的sublime,安装elixr包,然后tools ==》 build system ==》 elixr mix test

ctrl + B 就可以测试了。

上一篇:Excel中最精确的计算年龄的公式


下一篇:MySQL CURTIME() 函数