Monday, January 29, 2018

xna - How should I structure my Tetris clone's code?


I programmed my first game (a Tetris clone in XNA) and all my code is in a Game1.cs file with 730+ SLOC. It's fairly well-commented, and each piece of functionality has its own subroutine, but I have a feeling that I'll have to move toward a more organized approach as my games increase in complexity.


To offer some background, my current approach separates the "view" (the tetrimino sprites visible on the board) from the underlying "data" (represented by an 18x10 bool array), which determines if there is a block at some point on the grid. In other words, my "data" determines my "view." Also, here's a list of all my subroutines:


Game1()

Initialize()
LoadContent()
UnloadContent()
GetBlockType()
IsFreeBlock()
IsPossibleMovement()
GetXInBlocks()
GetYInBlocks()
StorePiece()
DeleteLine()

DeletePossibleLines()
IsGameOver()
ResetBoard()
Update()
Draw()

I hear a lot about game components in XNA, which sounds like something that could make my code more organized and extensible. Are there any organizing features of XNA that I could incorporate into my future games?



Answer



I like the component architecture, but for a Tetris-clone it might be overkill. Instead I would just move away from the monolithic Game-class to separate classes. Here's an idea how you could separate into several classes and what methods/properties they could have:


Board

- reset()
- checkCollision(Tetromino)
- canRotate(Tetromino)
- commit(Tetromino)

Tetromino
- get/set position
- rotate()

GameController

- spawnBrick()
- processUserInput()
- increaseSpeed()
- updateBoard()

Renderer
- RenderBoard(Board)

You could also use messaging or events to attach other subsystems. Eg. your Board could send a message when a row was cleared. Then a "SoundController" could listen to this message and play a sound, or your "ScoreManager" could update the score. etc.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...