1
1
module Main exposing (..)
2
2
3
3
import Browser
4
+ import Browser.Events exposing (onKeyDown )
4
5
import Html exposing (Html , button , div , text )
5
6
import Html.Events exposing (onClick )
7
+ import Json.Decode as Decode
6
8
import List exposing (map , range )
7
9
import String exposing (fromInt )
8
10
import Svg
@@ -156,9 +158,14 @@ init _ =
156
158
157
159
158
160
type Msg
159
- = Left
160
- | Right
161
- | GravityTick Time . Posix
161
+ = GravityTick Time . Posix
162
+ | KeyDown Key
163
+ | Noop
164
+
165
+
166
+ type Key
167
+ = LeftArrow
168
+ | RightArrow
162
169
163
170
164
171
update : Msg -> Model -> ( Model , Cmd Msg )
@@ -169,25 +176,52 @@ update msg model =
169
176
, Cmd . none
170
177
)
171
178
172
- Left ->
173
- ( model
179
+ KeyDown key ->
180
+ ( movePiece key model
174
181
, Cmd . none
175
182
)
176
183
177
- Right ->
184
+ Noop ->
178
185
( model
179
186
, Cmd . none
180
187
)
181
188
182
189
190
+ movePiece : Key -> Model -> Model
191
+ movePiece key ( { currentPiece } as model) =
192
+ let
193
+ ( x, y ) =
194
+ currentPiece. position
195
+
196
+ newPosition =
197
+ case key of
198
+ LeftArrow ->
199
+ ( x - 1 , y )
200
+
201
+ RightArrow ->
202
+ ( x + 1 , y )
203
+
204
+ movedPiece =
205
+ { currentPiece | position = newPosition }
206
+ in
207
+ { model | currentPiece = movedPiece }
208
+
209
+
183
210
dropCurrentPiece : Model -> Model
184
211
dropCurrentPiece ( { currentPiece } as model) =
185
212
let
186
213
( x, y ) =
187
214
currentPiece. position
188
215
216
+ nextRow =
217
+ if y == 0 then
218
+ 20
219
+
220
+ else
221
+ y - 1
222
+
189
223
droppedPiece =
190
- { currentPiece | position = ( x, y - 1 ) }
224
+ { currentPiece | position = ( x, nextRow ) }
191
225
in
192
226
{ model | currentPiece = droppedPiece }
193
227
@@ -198,17 +232,40 @@ dropCurrentPiece ({ currentPiece } as model) =
198
232
199
233
subscriptions : Model -> Sub Msg
200
234
subscriptions model =
201
- Time . every 1000 GravityTick
235
+ Sub . batch
236
+ [ Time . every 1000 GravityTick
237
+ , onKeyDown keyDecoder
238
+ ]
239
+
240
+
241
+ keyDecoder : Decode .Decoder Msg
242
+ keyDecoder =
243
+ Decode . map toKey ( Decode . field " key" Decode . string)
244
+
245
+
246
+ toKey : String -> Msg
247
+ toKey string =
248
+ case string of
249
+ " ArrowLeft" ->
250
+ KeyDown LeftArrow
251
+
252
+ " ArrowRight" ->
253
+ KeyDown RightArrow
254
+
255
+ _ ->
256
+ Noop
202
257
203
258
204
259
260
+ -- Decode.succeed KeyDown
205
261
-- VIEW
206
262
207
263
208
264
view : Model -> Html Msg
209
265
view model =
210
266
div []
211
- [ div [] [ text " LOOK MUM, NO SERVER" ]
267
+ [ div [] [ text " Developing a Web Tetris in Elm" ]
268
+ , div [] [ text " Continuing TONIGHT at 7PM (EST)" ]
212
269
, boardView model. board model. currentPiece
213
270
]
214
271
0 commit comments