C # edition Tetris

Source: Internet
Author: User

C ++ is the preferred language for game programming, but I believe that C # can also do what C ++ can do.

This article describes how to use C # To compile a Tetris program and how to play the sound and save the game settings in C.

Game interface preview:

Menu preview:

Customize the color interface of each small square:

The game consists of four main components: Square, Block, gameField, and game engine.

Square:
The object described in this class is a small square entity in a large square.
Class Design:
Class Square
{
Public Point location; // coordinates of small squares
Public Size size; // small block Size
Public Color foreColor; // The foreground Color of a small square
Public Color backColor; // the background Color of the small square.
Public Square (Size initSize, Color initForeColor, Color initBackColor) // Constructor
{......}
Public void Draw (System. IntPtr winHandle) // Draw a square on the specified device
{...... }
Public void Erase (System. IntPtr winHandle) // Erase the square
{...... }
}

Block class:
The object described in this class is the entity of a large square. Each square is composed of four small squares. There are 7 combination methods. This class needs to implement all attributes and actions of a large block object. Including the shape, position, Left Movement, right movement, downward movement, and rotation of the square.
Class Design:
Class Block
{
Public Square square1; // The four blocks that constitute the block
Public Square square2;
Public Square square3;
Public Square square4;

Private const int squareSize = GameField. SquareSize; // The side length of the small square
Public enum BlockTypes
{
Undefined = 0,
Square = 1,
Line = 2,
J = 3,
L = 4,
T = 5,
Z = 6,
S = 7
}; // A total of 7 shapes
Public BlockTypes blockType; // block shape
// Color array of seven small squares
Private Color foreColor;
Private Color backColor;
// Direction of the square
Public enum RotateDirections ctions
{
North = 1,
East = 2,
South = 3,
West = 4
};
Public RotateDirections myRotation = RotateDirections. North;

Public Block (Point thisLocation, BlockTypes bType)
{......}
// Overload with custom colors
Public Block (Point thisLocation, BlockTypes bType, Color fc, Color bc)
{......}

/* Draw a square */
Public void Draw (System. IntPtr winHandle)
{...... }
/* Square wipe */
Public void Erase (System. IntPtr winHandle)
{...... }

/* Move */
Public bool down ()
{......}
Public bool left ()
{......}
Public bool right ()
{......}
/* Rotate the block */
Public void Rotate ()
{......}
/* Check whether it reaches the top */
Public int Top ()
{......}
}

GameField class:
This class describes the game scene entity, including the background color, size, whether the square can be moved, and the detection of filling a row in the scene.
Class Design:
Class GameField
{
Public const int width = 20; // The width of the scenario, in the unit of number of squares
Public const int height = 30;
Public const int SquareSize = 15; // The side length of each 1/4 small square
Public static Color BackColor; // background Color of the scenario
Public static System. IntPtr winHandle; // handle of the scenario
Public static Color [] BlockForeColor = {Color. Blue, Color. Beige, Color. DarkKhaki, Color. DarkMagenta, Color. DarkOliveGreen, Color. DarkOrange, Color. DarkRed };
Public static Color [] BlockBackColor = {Color. LightCyan, Color. DarkSeaGreen, Color. Beige, Color. Beige };
Public static bool isChanged = false; // sets whether the flag is changed.
Public static SoundPlayer sound = new SoundPlayer (); // playback sound

Public static Square [,] arriveBlock = new Square [width, height]; // Save the blocks that cannot be dropped any more.
Public static int [] arrBitBlock = new int [height]; // Bit Array: when there is a square at a position, this bit of this row is 1
Private const int bitEmpty = 0x0; // 0000 0000 0000 0000
Private const int bitFull = 0 xFFFFF; // 1111 1111 1111 1111 1111

/* Check whether a location is empty */
Public static bool isEmpty (int x, int y)
{......}
/* Stop blocks */
Public static void stopSquare (Square sq, int x, int y)
{......}
/* Check whether the row is full
* Return: number of rows successfully eliminated and (to facilitate the score statistics)
*/
Public static int CheckLines ()
{......}
/* Play the sound */
Public static void PlaySound (string soundstr)
{......}
/* Redraw */
Public static void Redraw ()
{...... }
// End
}

Game Engine:
The game engine, just like a single engine, keeps the game running continuously. In this game, the square falls at a certain speed. Respond to Keyboard Events and implement the left and right movement and downward acceleration functions. (For the code, see the source code)

Sound playback:

Sound effects are an indispensable part of the game. In. Net2.0, a class is provided to play the sound. In using System. Media; namespace.
The code for playing sound in this game is as follows: (in the GameField class)
Using System. Media;

Public static SoundPlayer sound = new SoundPlayer ();

/* Play the sound */
Public static void PlaySound (string soundstr)
{
Switch (soundstr)
{
Case "FinishOneLine": // eliminate the sound of a row
If (! File. Exists ("FinishOneLine.wav") return;
Sound. SoundLocation = "FinishOneLine.wav ";
Break;
Case "CanNotDo": // when the operation fails
If (! File. Exists ("CanNotDo.wav") return;
Sound. SoundLocation = "CanNotDo.wav ";
Break;
}
Sound. Play ();
}
Call the PlaySound () method to play the video.
In fact, the process is very simple. First reference the System. Media space, then create a SoundPlayer object, use the SoundLocation attribute to set the audio file address, and then call the Play () method to Play the video. However, note that only Wav files can be played in this class.

Save game settings:
In games, you often need to save user-defined settings. This game is saved by writing it into the INI file.
The main code is as follows:

/* When loading the form, read the game settings from the configuration file Setting. ini */
Private void getSettings ()
{
If (! File. Exists ("Setting. ini "))
Return;
FileStream fs = new FileStream ("Setting. ini", FileMode. OpenOrCreate, FileAccess. ReadWrite );
StreamReader sr = new StreamReader (fs );
String line1 = sr. ReadLine ();
String line2 = sr. ReadLine ();
String line3 = sr. ReadLine ();
If (line1! = Null & line1.Split ('='). Length> 1)
{
GameField. BackColor = Color. FromArgb (int. Parse (line1.Split ('=') [1]);
PicBackGround. BackColor = GameField. BackColor;
}
If (line2! = Null & line2.Split ('='). Length> 1)
GameField. BlockForeColor = strToColor (line2.Split ('=') [1]);
If (line3! = Null & line3.Split ('='). Length> 1)
GameField. BlockBackColor = strToColor (line3.Split ('=') [1]);
Sr. Close ();
Fs. Close ();
}
/* If the game settings are changed, save the new settings to Setting. ini */
Private void saveSettings ()
{
FileStream fs = new FileStream ("Setting. ini", FileMode. Create, FileAccess. ReadWrite );
StreamWriter sw = new StreamWriter (fs );
Sw. WriteLine ("GameFieldColor =" + GameField. BackColor. ToArgb ());
Sw. WriteLine ("BlockFroeColor =" + colorToStr (GameField. BlockForeColor ));
Sw. WriteLine ("BlockBackColor =" + colorToStr (GameField. BlockBackColor ));
Sw. Flush ();
Sw. Close ();
Fs. Close ();
}

Although the sparrow is small, it is dirty. For more information, see the source code.
Download game source CODE: CODE

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.