]> gitweb.factorcode.org Git - factor.git/blob - extra/tetris/piece/piece.factor
Switch to https urls
[factor.git] / extra / tetris / piece / piece.factor
1 ! Copyright (C) 2006, 2007, 2008 Alex Chapman
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: accessors arrays kernel math math.vectors sequences
4 tetris.tetromino lists.lazy ;
5 IN: tetris.piece
6
7 ! The rotation is an index into the tetromino's states array,
8 ! and the position is added to the tetromino's blocks to give
9 ! them their location on the tetris board. If the location is f
10 ! then the piece is not yet on the board.
11
12 TUPLE: piece
13     { tetromino tetromino }
14     { rotation integer initial: 0 }
15     { location array initial: { 0 0 } } ;
16
17 : <piece> ( tetromino -- piece )
18     piece new swap >>tetromino ;
19
20 : (piece-blocks) ( piece -- blocks )
21     ! rotates the piece
22     [ rotation>> ] [ tetromino>> states>> ] bi nth ;
23
24 : piece-blocks ( piece -- blocks )
25     ! rotates and positions the piece
26     [ (piece-blocks) ] [ location>> ] bi [ v+ ] curry map ;
27
28 : piece-width ( piece -- width )
29     piece-blocks blocks-width ;
30
31 : set-start-location ( piece board-width -- piece )
32     over piece-width [ 2 /i ] bi@ - 0 2array >>location ;
33
34 : <random-piece> ( board-width -- piece )
35     random-tetromino <piece> swap set-start-location ;
36
37 : <piece-llist> ( board-width -- llist )
38     [ [ <random-piece> ] curry ] keep [ <piece-llist> ] curry lazy-cons ;
39
40 : (rotate-piece) ( rotation inc n-states -- rotation' )
41     [ + ] dip rem ;
42
43 : rotate-piece ( piece inc -- piece )
44     over tetromino>> states>> length
45     [ (rotate-piece) ] 2curry change-rotation ;
46
47 : move-piece ( piece move -- piece )
48     [ v+ ] curry change-location ;