termtris

A text-based game inspired by tetris.

  • 所有者: tylerneylon/termtris
  • 平台:
  • 许可证: The Unlicense
  • 分类:
  • 主题:
  • 喜欢:
    0
      比较:

Github星跟踪图

--[[

termtris: A Game like Tetris in Ten Functions

This is a literate implementation of a
tetris-like game called termtris.
You may be reading this as an html-ified version -
but the original,
termtris.lua,
is simultaneously a Lua file and a markdown file.
In the original file,
all the text between the --[​[ and --]​] comment delimiters are markdown
while everything else is code.

-- This is an example of a code block. Taken together, all the code
-- blocks in this document compose the complete termtris game.

This code has been written with an emphasis on readability
and learn-from-ability. I hope these comments are useful to anyone
interested in how a game like tetris can be made.
I've put some effort into making
this document friendly to coders who are new to Lua.

On github.com, the readme.md is a symbolic link to termtris.lua
to enable easy reading from
the repo's home page.
A nonliterate version of the code is in the file
plain_termtris.lua.

I'll tell you how you can download and play termtris, and
then we'll dive into the code.

Playing the game

You can play termtris on Mac OS X or linux/unix using a Lua interpreter.

On macOS, you can install Lua via brew install lua; for any OS,
you can download Lua here.
Download the luarocks package manager here.
From there:

  • sudo luarocks install luaposix
  • sudo luarocks install lcurses
  • Ensure Lua can see your installed modules.
    On macOS, you can do this via (from your shell) eval $(luarocks path)
  • git clone https://github.com/tylerneylon/termtris.git
  • lua termtris/termtris.lua

Here are the game controls:, key, action, --------------------, ----------------------------------, left, right arrows, move the piece left or right, up arrow, rotate the piece, down arrow, drop and lock the piece in place, p, pause or unpause, q, quit, ## Reading Lua

Even if you're new to Lua, I think you'll find it easy to understand
the code. I'll mention a few things that may not be obvious:

  • Block comments are between --[​[ and --]​]. Line-tail comments start with --.
  • An assignment like a, b, c = f() calls f and assigns all of f's
    return values to a, b, and c in order — not just to c.
  • The token ~= is the not-equal-to operator.
  • The only compound data structure is called a table. It's an associative
    array that can map any non-nil Lua value to any other.
  • Things inside curly braces {} are table literals.
    The literal a = {x, y} has values a[1] == x and a[2] == y.
    Table literals can be nested: if a = {{x}, {y}}, then a[2][1] == y.
  • If pi == 3.141, then the literal b = {w = 1, [pi] = 2} results in
    b.w == b['w'] == 1 and b[pi] == 2; that is, identifiers to the left of =
    are string keys and
    keys inside brackets [] are treated as general expressions.
  • Using an undefined table key is not an error — it just returns nil, which is falsy.
    For example, if a = {key1 = 'hi', key2 = 'there'}, then a.key3 is a valid
    expression with value nil.
  • We can iterate over the keys and values of table t with the pattern
    for k, v in pairs(t) do my_fn(k, v) end. If t is treated as an array —
    if it has sequential integer keys starting at 1 — then ipairs can be used
    instead of pairs to ensure the keys are given in order:
    for i, v in ipairs(t) do my_fn(i, v) end.

Armed with that lightning flash of a Lua introduction, I believe you can understand
all of the code. For a tad more depth, some crazy guy claims you can
learn the language in 15 minutes.

The Code

This code has been written to maximize readability. This is hard to measure.
We can get a quantifiable hint that the code is not too daunting by consider its
line count and function count.

The code we'll examine has a total of 10 functions, and a little over
200 non-blank, non-comment lines of code:

$ # (This is a bash line, not part of the Lua code!)
$ egrep -v '^\s*(--, $)' nonliterate/plain_termtris.lua, wc -l
231

This is small for a game. We could have used even fewer functions or fewer lines, but
beyond a certain point the compressed code becomes more cryptic than simple.
The trick is to find a balance between brevity and clarity.

Overview

Here's the complete call graph for termtris:

The main function initializes our data and then enters a game loop
in which we consistently check for input, drop the moving piece if the time
is right, and update what is drawn on the screen.

We'll understand the full code by looking at the libraries used for drawing and
timing, then going through the code more-or-less in the order that it's
executed.

Libraries

curses:
Tetris is a visually-oriented game, so we need a way to draw. A simple and
somewhat-portable way to do this is to draw colored space characters in
the terminal. We can do this using a time-tested library called curses.

posix:
We also need accurate timing information. Lua comes with functions like
os.clock() and os.time(), but neither of these are appropriate for a
game clock. The os.clock() function returns cpu time, rather than wall-clock
time; the difference is that cpu time only passes when our process is actually
running on the cpu, while wall-clock marches on no matter what process is
running. Users think in wall-clock time, so that's what we want.

The os.time() function gives us the wall-clock time, but only in seconds.
We'd like pieces to move faster than once per second! To achieve this, we
import the posix library, which gives us access to more advanced posix
functions, including higher-resolution timestamps.

Both of these libraries are installed together by running
the luarocks install luaposix command mentioned in the installation
section above.

Below are our module imports. This is the first "real"
code block, unlike the non-running example code sections above.
From here till the end, all code blocks are part of
the official program.

--]]

local curses = require 'curses'
local posix  = require 'posix'

--

function main()
  local stats, fall, colors, next_piece = init()

  while true do  -- Main loop.
    handle_input(stats, fall, next_piece)
    lower_piece_at_right_time(stats, fall, next_piece)
    draw_screen(stats, colors, next_piece)

    -- Don't poll for input much faster than the display can change.
    local sec, nsec = 0, 5e6  -- 0.005 seconds.
    posix.nanosleep(sec, nsec)
  end
end

--[[

Shape data

Next let's set up all possible shape pieces.
We'll use a global table called shapes for this.

There are seven possibilities:

The shapes table will be indexed first by shape number (1-7), and
then by a rotation number (1-4). So s = shapes[5][1] represents shape number 5 in its
first rotation orientation. This variable s represents the shape so that s[x][y] is
either 0 or 1; its value is 1 if the shape exists in the given (x, y) cell.

There are 7 shapes and 4 rotated orientations for each, giving 28 possible shape grids.
Instead of initializing all of them by hand, we'll set up one orientation of each shape,
and include some code in init that expands the shapes variable to include all
28 possibilities.

Even though the shape variable - and others defined below - are global to this file, we declare
them with the local keyword so that any other Lua code importing this file won't have
these variables in scope. In a sense, they become 'locally global.'

--]]

-- Set up one orientation of each shape.

local shapes = {
  { {0, 1, 0},
    {1, 1, 1}
  },
  { {0, 1, 1},
    {1, 1, 0}
  },
  { {1, 1, 0},
    {0, 1, 1}
  },
  { {1, 1, 1, 1}
  },
  { {1, 1},
    {1, 1}
  },
  { {1, 0, 0},
    {1, 1, 1}
  },
  { {0, 0, 1},
    {1, 1, 1}
  }
}

--

local game_state = 'playing'  -- Could also be 'paused' or 'over'.

--[[

What's on the board

We'll use an 11x20 board size. Traditional tetris games are usually 10x20, but I'm purposefully
putting in some differences in hopes of not getting sued.

The game area where pieces may live is represented by values in board[x][y] where
1 ≤ x ≤ board_size.x and 1 ≤ y ≤ board_size.y. The board variable also includes a U-shaped
border with board[x][y] == -1 when any of the following are true:

  • x == 0,
  • x == board_size.x + 1, or
  • y == board_size.y + 1.

When a shape is locked in place — that is, after it's done falling — we update the affected
cells in board by setting them to the shape number. This works since our shape numbers
are all > 0, so that 0 itself can represent empty cells.

It's very handy to keep the border of -1 values in the board itself since it simplifies
testing to see if a potential piece placement might go off the edge of the playing area.

We actually start with an empty board table that is filled in by the init function below.

The val variable exists so we can write code like board[x][y] == val.border instead
of the more cryptic board[x][y] == -1; and similarly for val.empty instead of 0.

--]]

local board_size = {x = 11, y = 20}
local board = {}                      -- board[x][y] = shape_num; 0=empty; -1=border.
local val = {border = -1, empty = 0}  -- Shorthand to avoid magic numbers.

--

local stdscr = nil  -- This will be the standard screen from the curses library.
local moving_piece = {}  -- Keys will be: shape, rot_num, x, y.

--

function init()
  -- Use the current time's microseconds as our random seed.
  math.randomseed(posix.gettimeofday().usec)

--[[

Set up the shapes table

Before this code, shapes[shape_index][rot_num] exists only when
rot_num == 1. So we have to take shapes[shape_index][1] and rotate it
into shapes[shape_index][i] for i = 2, 3, 4.

A simple mathematical way to perform a 90 degree rotation is to treat the point
(x, y) as the value rotated from (y, -x). In our case, these coordinates are
table indexes, such as shapes[shape_index][rot_num][x][y], so x and y are only
meaningful when they're positive integers. Instead of starting at (y, -x) to rotate
to (x, y), we'll start at (y, max_x + 1 - x). Mathematically, this is
like a rotation around (0, 0) followed by a translation to keep us in positive
(x, y) space.

This rotation method is
captured in the line new_shape[x][y] = s[y][x_end - x] in the loop below.

--]]

  -- Set up the shapes table.
  for s_index, s in ipairs(shapes) do
    shapes[s_index] = {}
    for rot_num = 1, 4 do
      -- Set up new_shape as s rotated by 90 degrees.
      local new_shape = {}
      local x_end = #s[1] + 1  -- Chosen so that x_end - x is in [1, x_max].
      for x = 1, #s[1] do      -- Coords x & y are indexes for the new shape.
        new_shape[x] = {}
        for y = 1, #s do
          new_shape[x][y] = s[y][x_end - x]
        end
      end
      s = new_shape
      shapes[s_index][rot_num] = s
    end
  end

--

  -- Start up curses.
  curses.initscr()    -- Initialize the curses library and the terminal screen.
  curses.cbreak()     -- Turn off input line buffering.
  curses.echo(false)  -- Don't print out characters as the user types them.
  curses.nl(false)    -- Turn off special-case return/newline handling.
  curses.curs_set(0)  -- Hide the cursor.

--

  -- Set up colors.
  curses.start_color()
  if not curses.has_colors() then
    curses.endwin()
    print('Bummer! Looks like your terminal doesn\'t support colors :\'(')
    os.exit(1)
  end
  local colors = { white = 1, blue = 2, cyan = 3, green = 4,
                   magenta = 5, red = 6, yellow = 7, black = 8 }
  for k, v in pairs(colors) do
    curses_color = curses['COLOR_' .. k:upper()]
    curses.init_pair(v, curses_color, curses_color)
  end
  colors.text, colors.over = 9, 10
  curses.init_pair(colors.text, curses.COLOR_WHITE, curses.COLOR_BLACK)
  curses.init_pair(colors.over, curses.COLOR_RED,   curses.COLOR_BLACK)

--

  -- Set up our standard screen.
  stdscr = curses.stdscr()
  stdscr:nodelay(true)  -- Make getch nonblocking.
  stdscr:keypad()       -- Correctly catch arrow key presses.

--

  -- Set up the board.
  local border = {x = board_size.x + 1, y = board_size.y + 1}
  for x = 0, border.x do
    board[x] = {}
    for y = 1, border.y do
      board[x][y] = val.empty
      if x == 0 or x == border.x or y == border.y then
        board[x][y] = val.border  -- This is a border cell.
      end
    end
  end

--

  -- Set up the next and currently moving piece.
  moving_piece = {shape = math.random(#shapes), rot_num = 1, x = 4, y = 0}

  -- Use a table so functions can edit its value without having to return it.
  next_piece = {shape = math.random(#shapes)}

  local stats = {level = 1, lines = 0, score = 0}  -- Player stats.

  -- fall.interval is the number of seconds between downward piece movements.
  local fall = {interval = 0.7}  -- A 'last_at' time is added to this table later.

--

  return stats, fall, colors, next_piece
end

--

function handle_input(stats, fall, next_piece)
  local key = stdscr:getch()  -- Nonblocking; returns nil if no key was pressed.
  if key == nil then return end

  if key == tostring('q'):byte(1) then  -- The q key quits.
    curses.endwin()
    os.exit(0)
  end

  if key == tostring('p'):byte(1) then  -- The p key pauses or unpauses.
    local switch = {playing = 'paused', paused = 'playing'}
    if switch[game_state] then game_state = switch[game_state] end
  end

--

  if game_state ~= 'playing' then return end  -- Arrow keys only work if playing.

  -- Handle the left, right, or up arrows.
  local new_rot_num = (moving_piece.rot_num % 4) + 1  -- Map 1->2->3->4->1.
  local moves = {[curses.KEY_LEFT]  = {x = moving_piece.x - 1},
                 [curses.KEY_RIGHT] = {x = moving_piece.x + 1},
                 [curses.KEY_UP]    = {rot_num = new_rot_num}}
  if moves[key] then set_moving_piece_if_valid(moves[key]) end

  -- Handle the down arrow.
  if key == curses.KEY_DOWN then
    while set_moving_piece_if_valid({y = moving_piece.y + 1}) do end
    lock_and_update_moving_piece(stats, fall, next_piece)
  end
end

--[[


Functions 4 and 5: Working with Pieces

The set_moving_piece_if_valid function accepts a table
that suggests new values for the moving_piece.
If those new values are valid, moving_piece is updated
and the function returns true; otherwise it returns false.

This function is used for all piece movements: left, right,
rotation, dropping, and even when setting up a new piece after
the previous piece has hit the bottom. A new piece may be in
an invalid position if the board has filled to the top, in which
case the game is over.

Because the board's border is included in the board variable,
the only check we have to make is that board[x][y] == val.empty
for every cell occupied by the new piece values.

We'll rely on a function called call_fn_for_xy_in_piece that
helpfully iterates over all (x, y) values occupied by
a given piece.

--]]

-- Returns true if and only if the move was valid.
function set_moving_piece_if_valid(piece)
  -- Use values of moving_piece as defaults.
  for k, v in pairs(moving_piece) do
    if piece[k] == nil then piece[k] = moving_piece[k] end
  end
  local is_valid = true
  call_fn_for_xy_in_piece(piece, function (x, y)
    if board[x] and board[x][y] ~= val.empty then is_valid = false end
  end)
  if is_valid then moving_piece = piece end
  return is_valid
end

--

-- This function calls callback(x, y) for each x, y coord
-- in the given piece. Example use using draw_point(x, y):
-- call_fn_for_xy_in_piece(moving_piece, draw_point)
function call_fn_for_xy_in_piece(piece, callback, param)
  local s = shapes[piece.shape][piece.rot_num]
  for x, row in ipairs(s) do
    for y, val in ipairs(row) do
      if val == 1 then callback(piece.x + x, piece.y + y, param) end
    end
  end
end

--

function lock_and_update_moving_piece(stats, fall, next_piece)
  call_fn_for_xy_in_piece(moving_piece, function (x, y)
    board[x][y] = moving_piece.shape  -- Lock the moving piece in place.
  end)

--[[

Next we look for affected rows of board which have no empty cells;
we call these full lines. Each one is cleared, dropping anything above
it downward by iterating over the line board[x][y] = board[x][y - 1].

We finish by incrementing the line count, the level if appropriate,
and the score.

--]]

  -- Clear any lines possibly filled up by the just-placed piece.
  local num_removed = 0
  local max_line_y = math.min(moving_piece.y + 4, board_size.y)
  for line_y = moving_piece.y + 1, max_line_y do
    local is_full_line = true
    for x = 1, board_size.x do
      if board[x][line_y] == val.empty then is_full_line = false end
    end
    if is_full_line then
      -- Remove the line at line_y.
      for y = line_y, 2, -1 do
        for x = 1, board_size.x do
          board[x][y] = board[x][y - 1]
        end
      end
      -- Record the line and level updates.
      stats.lines = stats.lines + 1
      if stats.lines % 10 == 0 then  -- Level up when lines is a multiple of 10.
        stats.level = stats.level + 1
        fall.interval = fall.interval * 0.8  -- The pieces will fall faster.
      end
      num_removed = num_removed + 1
    end
  end
  if num_removed > 0 then curses.flash() end
  stats.score = stats.score + num_removed * num_removed

--[[

Finally, next_piece begins to fall, and a new next_piece value is set up.

Even though board[x][y] is only valid for y ≥ 1, we want to set up new
pieces with y=0
because call_fn_for_xy_in_piece
uses the expression piece.y + y to determine a piece's y values, and
the y in that expression ranges from 1 up to the height of the piece.
In other words, (moving_piece.x, moving_piece.y) is the coordinate of the cell just
to the upper-left of where the moving piece will be drawn.

--]]

  -- Bring in the waiting next piece and set up a new next piece.
  moving_piece = {shape = next_piece.shape, rot_num = 1, x = 4, y = 0}
  if not set_moving_piece_if_valid(moving_piece) then
    game_state = 'over'
  end
  next_piece.shape = math.random(#shapes)
end

--

function lower_piece_at_right_time(stats, fall, next_piece)
  -- This function does nothing if the game is paused or over.
  if game_state ~= 'playing' then return end

  local timeval = posix.gettimeofday()
  local timestamp = timeval.sec + timeval.usec * 1e-6
  if fall.last_at == nil then fall.last_at = timestamp end  -- Happens at startup.

  -- Do nothing until it's been fall.interval seconds since the last fall.
  if timestamp - fall.last_at < fall.interval then return end

  if not set_moving_piece_if_valid({y = moving_piece.y + 1}) then
    lock_and_update_moving_piece(stats, fall, next_piece)
  end
  fall.last_at = timestamp
end

--

-- Accepts integer values corresponding to the 'colors' table
-- created by init. For example, call 'set_color(colors.black)'.
function set_color(c)
  stdscr:attron(curses.color_pair(c))
end

--

function draw_point(x, y, x_offset, color, point_char)
  point_char = point_char or ' '  -- Space is the default point_char.
  if color then set_color(color) end
  -- Don't draw pieces when the game is paused.
  if point_char == ' ' and game_state == 'paused' then return end
  stdscr:mvaddstr(y, x_offset + 2 * x + 0, point_char)
  stdscr:mvaddstr(y, x_offset + 2 * x + 1, point_char)
end

--[[

The draw_screen function begins by erasing the screen
and recalculating the x coordinates of the left edge of the game board -
which we call the x_margin - and of the stats on the right
side of the board - which we call x_labels.
These are constantly recalculated because it's cheap to do so
and because the player may resize their terminal at any time.

It may be worth explaining this line ahead of time:

  • local win_width = 2 * (board_size.x + 2) + 16

The win_width value represents the width, in characters, that
we may render to. We want it to be smaller than scr_width.
The board_size.x + 2 value is the board width in cells,
plus 2 border cells; this value is converted to characters by
being doubled. The + 16 is meant to give 16 characters of room
in which to render the player stats and next piece. The updated
screen dimensions are illustrated here:

--]]

function draw_screen(stats, colors, next_piece)
  stdscr:erase()

  -- Update the screen dimensions.
  local scr_width = curses.cols()
  local win_width = 2 * (board_size.x + 2) + 16
  local x_margin = math.floor((scr_width - win_width) / 2)
  local x_labels = x_margin + win_width - 10

--

  -- Draw the board's border and non-falling pieces if we're not paused.
  local color_of_val = {[val.border] = colors.text, [val.empty] = colors.black}
  local char_of_val = {[val.border] = ', '}  -- This is the border character.
  if game_state == 'over' then color_of_val[val.border] = colors.over end
  for x = 0, board_size.x + 1 do
    for y = 1, board_size.y + 1 do
      local board_val = board[x][y]
      -- Draw ' ' for shape & empty points; ', ' for border points.
      local pt_char = char_of_val[board_val] or ' '
      draw_point(x, y, x_margin, color_of_val[board_val] or board_val, pt_char)
    end
  end

--

  -- Write 'paused' if the we're paused; draw the moving piece otherwise.
  if game_state == 'paused' then
    set_color(colors.text)
    local x = x_margin + board_size.x - 1  -- Slightly left of center.
    stdscr:mvaddstr(math.floor(board_size.y / 2), x, 'paused')
  else
    set_color(moving_piece.shape)
    call_fn_for_xy_in_piece(moving_piece, draw_point, x_margin)
  end

--

  -- Draw the stats: level, lines, and score.
  set_color(colors.text)
  stdscr:mvaddstr( 9, x_labels, 'Level ' .. stats.level)
  stdscr:mvaddstr(11, x_labels, 'Lines ' .. stats.lines)
  stdscr:mvaddstr(13, x_labels, 'Score ' .. stats.score)
  if game_state == 'over' then
    stdscr:mvaddstr(16, x_labels, 'Game Over')
  end

--

  -- Draw the next piece.
  stdscr:mvaddstr(2, x_labels, '----------')
  stdscr:mvaddstr(7, x_labels, '---Next---')
  local piece = {shape = next_piece.shape, rot_num = 1, x = board_size.x + 5, y = 3}
  set_color(piece.shape)
  call_fn_for_xy_in_piece(piece, draw_point, x_margin)

  stdscr:refresh()
end

--

main()

--[[

That's the whole game.

Learning More

If you enjoyed this, you might like further exploration of Lua and
my favorite 2D game engine, Löve, which adds modern 2D graphics capabilities
to Lua. Here are some diving boards into more
game-making goodness:

One More Thing

I'm working on an original large-scale game called Apanga.
If you're interested in independently-developed games, you
could send me your email addy to
find out more about Apanga. I'm looking for early-stage
testers and any help/interest would be greatly appreciated!

--]]

主要指标

概览
名称与所有者tylerneylon/termtris
主编程语言Lua
编程语言Lua (语言数: 1)
平台
许可证The Unlicense
所有者活动
创建于2014-09-23 08:44:13
推送于2019-12-09 23:45:55
最后一次提交2019-06-14 13:20:55
发布数0
用户参与
星数454
关注者数17
派生数41
提交数109
已启用问题?
问题数4
打开的问题数1
拉请求数0
打开的拉请求数1
关闭的拉请求数0
项目设置
已启用Wiki?
已存档?
是复刻?
已锁定?
是镜像?
是私有?