/* Tetris by Ben Hoyt, April 2008 */ #include #include "tio.h" /* falling speed, 1 is slow, 10 is fast */ #define SPEED 5 /* width and height of board (board has 3-square wide border so we don't have to worry about edge detection */ #define WIDTH 10 #define HEIGHT 20 #define BORDER 3 #define TOTAL_WIDTH (WIDTH+BORDER*2) #define TOTAL_HEIGHT (HEIGHT+BORDER*2) #define SQUARE(x, y) board[BORDER+y][BORDER+x] /* board and game state */ static char board[TOTAL_HEIGHT][TOTAL_WIDTH]; static int curpiece, currote; static int curx, cury; static int gameover; /* piece definitions (all pieces in all their rotations) */ extern int starts[7]; extern char pieces[7][4][4][4]; /* return a random piece number in the range 0..6 */ int randpiece(void) { return rand() % 7; } /* tell main loop the game has ended */ void endgame(void) { gameover = 1; } /* check if current piece fits at given x,y and rotation */ int fits(int tryx, int tryy, int tryrote) { int x, y; /* for each position in the 4x4 piece, if the board has a square there or the piece has a square there, it won't fit */ for (y=0; y<4; y++) { for (x=0; x<4; x++) { if (SQUARE(tryx+x, tryy+y) && pieces[curpiece][tryrote][y][x]) return 0; } } return 1; } /* place piece on board at current location (assumes it fits) */ void place(void) { int x, y; /* for each non-empty position in the 4x4 piece, place square on board */ for (y=0; y<4; y++) { for (x=0; x<4; x++) { if (pieces[curpiece][currote][y][x]) SQUARE(curx+x, cury+y) = curpiece+1; } } } /* show piece or hide piece (show if "show" is nonzero) */ void _showpiece(int show) { int x, y; /* for each non-empty position in the 4x4 piece, show or hide square */ for (y=0; y<4; y++) { for (x=0; x<4; x++) { if (pieces[curpiece][currote][y][x]) putsquare(curx+x+1, cury+y+1, show ? curpiece+1 : 0); } } } /* show current piece at current location */ void showpiece(void) { _showpiece(1); } /* erase current piece at current location */ void hidepiece(void) { _showpiece(0); } /* generate a new piece and show it, end game if it doesn't fit */ void newpiece(void) { curpiece = randpiece(); currote = 0; curx = WIDTH/2 - 2; cury = starts[curpiece]; if (fits(curx, cury, currote)) showpiece(); else endgame(); } /* show the current board on the screen, including the border */ void showboard(void) { int x, y; for (y=-1; y=BORDER && x=BORDER && y=1; y--) { for (x=0; x=1; y--) { for (x=0; x= 11-SPEED) { down(); ticks = 0; } } teardown(); }