Coder Social home page Coder Social logo

tetris's Introduction

Tetris Game Engine

This game engine is part of a larger project where I'm implementing a version of Tetris playable on WS2812B LED matrices via an ESP-Now remote.

The game was branched off to its own repository because the embedded project source tree only needs tetris.h and tetris.c, but all the other driver and testing files take up a lot of space.

About

  • One of the main goals of this project is to gain experience developing and debugging components on a workstation that can then be easily ported to MCU platforms. As such, the linux driver for this game is filled with debugging features to make hunting bugs in the game logic as easy as possible, since that same process will be much more difficult when in the resource-constrained environment of an MCU.
  • Some debugging features include
    • Saving entire game state to a file at any point by pressing p. Game state can then be restored, but these saves are largely used for unit testing purposes since having a start point of a game that you know preceded a crash can be very helpful when trying to force the game into invalid states.
    • Some of these files can be found in test/files/
    • Game state is also saved to a file on gameover, which was done to debug issues that cause premature gameover conditions.
    • Debug sub-window in game enableable via -DDEBUG_WINDOW=ON during cmake build. This shows current game state information, so weird behavior is easier to spot.
  • Everything is written from scratch, with the exception of the graphics library (ncurses), Unit test harness (Unity), and .ini file parser, inih.

Project Goals

This project has several goals.

  • Game needs to be runnable on low-powered devices using interrupts. Memory and compute requirements should be as minimal as possible.
  • Driver code needed to make a given display or controller work should be kept as minimal as possible. Currently, the game exposes a 2D array of int8_t values representing different piece colors, and all the display implementation needs to do is render that to a grid of the board size.
  • Teach myself embedded test-driven development and embedded unit testing using techniques from James Greening's "Test-Driven Development for Embedded C" (link)
  • Set up CI from scratch for an embedded project
  • Learn CMake and set up the build system from scratch

This game is my first attempt at writing a component of medium complexity, and one of my primary goals is bettering my understanding of development best practices to accelerate my work on future projects.

Compilation

Game Driver (runs in terminal on Linux workstations)

cmake . -B build && cmake --build build
./build/tetris_driver

Unit Tests

cmake . -B build -DTARGET_GROUP=test && cmake --build build
./build/test_tetris

Debugging

If debugging flags are enabled, two game state files will show up in the current directory when the game is finished: game.log and final-gamestate.ini. The game.log is a log of actions taken during the game to speed up tracing logic problems; final-gamestate.ini contains a human & machine readable save of the entire game state at gameover, allowing easier debugging of premature exit conditions (which was one of the bigger bugs I had to find). The log file automatically updates during gameplay, so a live log of what's happening in-game can be watched in a separate terminal session by doing tail -f game.log.

One of the main reasons I set up the .ini file saving functionality was for unit testing. This can be seen in the test_clearRowsDumpedGame() functions inside test/suite_1.c. The game state is restored and then used to test edge cases and look for weird behavior, all starting from an actual state reached in-game.

Implementation and Controls

  • For your own microcontroller implementation, see src/driver_tetris.c as an example; it shows you everything that's needed for a complete implementation. The game is designed to be as self-contained as possible, so past passing along inputs and rendering the board array there's not much you need to do.

Essentially, this is it:

// start game, define player_move variable, and create first piece
TetrisGame *tg = create_game();
enum player_move move = T_NONE;
create_rand_piece(tg);     

while([game not over]) {
    // do game tick
    tg_tick(tg, move);

    // process player input
    // wait for 10 ms before doing it again
}

The game board itself is rendered to a 2D array int8_t board[TETRIS_ROWS][TETRIS_COLS] accessible via tg->active_board.board. All your display implementation needs to do is render this array into the associated colors for whatever display format is desired.

The code is documented using Doxygen style comments. Custom types are documented in tetris.h, and functions are preceded by short explanations in tetris.c. On inclusion into your project, your IDE's LSP server should automatically show these descriptions on hover.

Linux Game Controls

These are the controls for my implementation (driver_tetris.c) for POSIX terminals via ncurses.

←/→ - Move left/right
↑ - Rotate piece
↓ - Move piece down
SPACE - pause game
'q' - quit
'p' prints current game state to `gamestate.ini` (for debugging purposes)

Flags

  • There are many compilation flags to enable/disable features, mostly for debugging. I've also created several compilation flags that enable extra output on CI builds so it's easier to see what went wrong from the build report console. The default options should be fine, but for finer tuning you can see the options available to you across the project's CMakeLists.txt files.

Options:

OPTION(TETRIS_UNIT_TEST_MACRO "Print gamelog to stdout (for CI)" OFF) # disabled by default
OPTION(TETRIS_UNIT_TEST_CI "CI-specific path options" OFF) # disabled by default
OPTION(TETRIS_DEBUG_T_MACRO "Enable Debug logging from inside tetris" OFF)
OPTION(INI_LIB_INCLUDE_OPTION "Include inih library for saving game state to disk" ON)

For example, to enable DEBUG_T you would do

cmake -B build -DTARGET_GROUP=test -DTETRIS_DEBUG_T_MACRO=ON
Other

I have these aliases in my ~/.zshrc to make the testing process more fluid.

alias cmakeclean='rm -rf CMakeCache.txt cmake_install.cmake Makefile CMakeFiles build'
alias cmakeregen='cmake . -B build && cmake --build build'
alias cmaketest='cmake . -B build -DTARGET_GROUP=test && cmake --build build'

TODO:

  • fix duplicate colors
    • this is an ncurses color issue with TERM, the game logic is setting it correctly
  • maybe rewrite render_active_board to no-copy to increase speed?

fixed

  • fix J piece rotation
  • Set up CI/CD with GH actions
  • fix full lines not being removed
  • fix crash on trying to clear line
  • fix gameover state detected prematurely, causing crash Issue #1
  • fix score not incrementing on line clear
  • maybe fixed: figure out why check_and_clear being called on rows at very top of board
    • this preceeds premature gameover, this crash seems to happen on another piece clear
  • figure out what's causing a bunch of out-of-bounds numbers to show up in row 1 of board - i think this is a type issue with uint & int types!
  • add play/pause functionality
  • Finish tetris game logic
  • fix gameover state not detected
  • add confirmation on quit to driver

Some of what I've learned

mostly for myself to not forget

  • CI build options in CMake, so that CI can build a different version depending on paths and such
  • static variables inside functions can be useful, but generally make unit testing more difficult.

tetris's People

Contributors

0xjmux avatar

Watchers

 avatar

tetris's Issues

Minor memory leak in tetris.c

I'm testing out using issues to track bugs as I fix them. This is another one of those

Running test_tetris through valgrind, the result is:

$ valgrind --track-origins=yes ./build/test_tetris
==341505== Memcheck, a memory error detector                                                                                                                
==341505== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.                                                                                  
==341505== Using Valgrind-3.18.1 and LibVEX; rerun with -h for copyright info                                                                               
==341505== Command: ./build/test_tetris                                                                                                                     
==341505==                                                                                                                                                  
==== RUNNING UNIT TESTS ON TETRIS =====                             
[path]/tetrisgame/test/suite_1.c:476:test_checkValidMove:PASS                                                     
[path]/tetrisgame/test/suite_1.c:477:test_T_testPieceRotate:PASS                                                  
[path]/tetrisgame/test/suite_1.c:478:test_clearRows:PASS                                                          
[path]/tetrisgame/test/suite_1.c:479:test_checkSpawnNewPiece:PASS                                                 
[path]/tetrisgame/test/suite_1.c:482:test_arr_helpers:PASS                                                        
Config loaded from ./test/files/gamestate-full-row-not-detected.ini!
==341505== Conditional jump or move depends on uninitialised value(s)
==341505==    at 0x10DEA2: val_in_arr (tetris.c:646)          
==341505==    by 0x10DBDF: check_and_clear_rows (tetris.c:527)                
==341505==    by 0x10A9E6: test_clearRowsDumpedGame_1 (suite_1.c:269)                                                                                       
==341505==    by 0x110F71: UnityDefaultTestRun (unity.c:2202)      
==341505==    by 0x10B5E2: main (suite_1.c:483)                                                                                                             
==341505==  Uninitialised value was created by a stack allocation
==341505==    at 0x10DB2F: check_and_clear_rows (tetris.c:502)
==341505==                                                                                                                                                  
[path]/tetrisgame/test/suite_1.c:483:test_clearRowsDumpedGame_1:PASS                                              
Config loaded from ./test/files/gamestate-J-lined-up-dbl-clear.ini!
==341505== Conditional jump or move depends on uninitialised value(s)
==341505==    at 0x10DEA2: val_in_arr (tetris.c:646)             
==341505==    by 0x10DBDF: check_and_clear_rows (tetris.c:527)
==341505==    by 0x10DDFC: check_and_spawn_new_piece (tetris.c:609)           
==341505==    by 0x10AD27: test_clearRowsDumpedGame_2 (suite_1.c:325)                                                                                       
==341505==    by 0x110F71: UnityDefaultTestRun (unity.c:2202)                 
==341505==    by 0x10B600: main (suite_1.c:484)                               
==341505==  Uninitialised value was created by a stack allocation             
==341505==    at 0x10DB2F: check_and_clear_rows (tetris.c:502)                
==341505==                                                                    
[path]/tetrisgame/test/suite_1.c:484:test_clearRowsDumpedGame_2:PASS                                              
                                                                              
-----------------------                                                                                                                                     
7 Tests 0 Failures 0 Ignored                                                  
OK                                   
==341505==                                                                    
==341505== HEAP SUMMARY:                                                                                                                                    
==341505==     in use at exit: 36 bytes in 2 blocks
==341505==   total heap usage: 14 allocs, 12 frees, 17,756 bytes allocated
==341505==                                                                    
==341505== LEAK SUMMARY:                                                      
==341505==    definitely lost: 36 bytes in 2 blocks                           
==341505==    indirectly lost: 0 bytes in 0 blocks                    
==341505==      possibly lost: 0 bytes in 0 blocks                       
==341505==    still reachable: 0 bytes in 0 blocks                                                                                                          
==341505==         suppressed: 0 bytes in 0 blocks
==341505== Rerun with --leak-check=full to see details of leaked memory       
==341505==                                                                                                                                                  
==341505== For lists of detected and suppressed errors, rerun with: -s
==341505== ERROR SUMMARY: 3 errors from 2 contexts (suppressed: 0 from 0)

Premature gameover on line clear

I'm going to try out issues for bug resolution just to get the hang of it.

So far, this seems to happen most with I_PIECE, but idk if that's a necessary part of it.

game.log from a game where this happened:

Global piece locations are: {[24, 7] [25, 7] [26, 7] [27, 7] }
Gravity tick activated systime=200069, last tick=16: piece moved down
display_board()
display_board()
display_board()
display_board()
display_board()
display_board()
display_board()
display_board()
Global piece locations are: {[25, 7] [26, 7] [27, 7] [28, 7] }
Gravity tick activated systime=400097, last tick=200069: piece moved down
display_board()
display_board()
display_board()
display_board()
display_board()
display_board()
display_board()
display_board()
Global piece locations are: {[26, 7] [27, 7] [28, 7] [29, 7] }
Gravity tick activated: move down failed
Piece stopped falling at loc row=26, col=7
check_and_clear: checking row 26
check_and_clear: checking row 27
check_and_clear: checking row 28
check_and_clear: checking row 29
smallest value in array {26, 28, 29, } is 26!
clearing 3 rows with top_row=26
Score updated for 3 lines cleared. Score = 4300, Level = 3     Lines cleared since last level=2
Global piece locations are: {[1, 9] [2, 8] [2, 9] [3, 8] }

Gravity tick activated: move down failed

Piece stopped falling at loc row=1, col=8
check_and_clear: checking row 1
check_and_clear: checking row 2
check_and_clear: checking row 2
check_and_clear: checking row 3
smallest value in array {2, 2, } is 2!
clearing 2 rows with top_row=2
Score updated for 2 lines cleared. Score = 5200, Level = 3     Lines cleared since last level=4
game over detected, returning false from tg_tick
Deallocating tetris game

The first sign of a problem is that "Gravity tick activated" line - for some reason it thinks it can't move the piece down when it's at the top of the board, and that causes the crash.

That print statement is in check_do_piece_gravity(), but the source of the problem has to be at/near check_valid_move(tg, T_DOWN).

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.