iT邦幫忙

2021 iThome 鐵人賽

DAY 5
0
Modern Web

連線網頁卡牌遊戲(Elixir, Phoenix, Liveview)系列 第 5

5 開始把結構寫成程式吧!

昨天我們使用這兩個 struct 來代表整個遊戲的狀態,那我們今天就實際的來定義他們

在開始之前

在開始之前,我來快速講一下 struct 是什麼:
在開始講 struct 之前,我來快速講一下 map 是什麼XD

map

elixir 的 map 長這樣 %{"key" => "value"}
用法跟 ruby 的 hash 幾乎一樣,只差前面有%

如果前面的 key 是 atom 的話 %{:key => "value"}
則可以縮寫成 %{key: "value"}
常常這樣子用 apple = %{size: "large", color: "green", prize: 99}

struct

struct 的話是被定義在 module 底下的特殊 map ,
我們可以幫他設定固定的 key 與 預設 value。

假如我們幫 Apple module 定義一個 struct :

defmodule Apple do
  defstruct size: "normal", color: "red", prize: 5
end

在我們呼叫 %Apple{} 的時候,就會得到 %Apple{size: "normal", color: "red", prize: 5}

從 Game module 開始

我們開始把這些結構寫一寫吧

%Game{
  rounds: [%Round{...}]
  host_hand: [],
  guest_hand: [],
  round: 1,
  winner: nil
}

%Round{
  host_desk: [], 
  guest_desk: [], 
  winner: nil
}

我們先新增一個檔案叫 game.ex 來裝這些東西,暫時先都寫在裡面就好,之後再搬。

首先定義 Game module 與 Round module,

# game.ex 檔案
defmodule Game do
end

defmodule Round do
end

再幫他們定義昨天設計好的 struct

# game.ex 檔案
defmodule Game do
  defstruct rounds: [], host_hand: [], guest_hand: [], round: 1, winner: nil
end

defmodule Round do
  defstruct host_desk: [], guest_desk: [], winner: nil
end

執行看看

完成之後打開我們可以在 iex 打開 game.ex 看看
(iex 是 elixir 附贈的互動模式)

$ iex game.ex
Erlang/OTP 24 [erts-12.0.3] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1]

Interactive Elixir (1.12.2) - press Ctrl+C to exit (type h() ENTER for help)

iex(1)> %Game{}
%Game{guest_hand: [], host_hand: [], round: 1, rounds: [], winner: nil}
iex(2)> %Round{}
%Round{guest_desk: [], host_desk: [], winner: nil}
iex(3)>

在我們打出 %Game{} 他就回傳給我們整包預設的狀態了
也可以直接指定裡面的內容給他

iex(3)> %Game{guest_hand: ["黑魔導", "神聖彗星反射力量"]}
%Game{
  guest_hand: ["黑魔導", "神聖彗星反射力量"],
  host_hand: [],
  round: 1,
  rounds: [],
  winner: nil
}

明天我們就可以開始寫遊戲本身了

什麼!你說你沒有 iex ,因為你還沒裝 elixir

elixir 官網的安裝頁面

我推薦使用 asdf 這個多語言版本管理工具 來安裝 elixir 與 erlang (elixir 需要 erlang)
在這篇文章的當下 elixir 是 1.12.3 erlang 是 24.0.6

安裝有問題可以留言,我看看能不能幫上忙,有時候裝環境真的很難搞。


上一篇
4 遊戲狀態結構
下一篇
6 用 GenServer 做 server?
系列文
連線網頁卡牌遊戲(Elixir, Phoenix, Liveview)32
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言