游戏的资源和设计参考了C#Windows游戏设计书中的案例,没有太复杂的算法,适合入门者学习,就直接贴上资源文件和相关代码了。
游戏资源:
在项目的bin/Debug文件夹下新建两个文件夹GamePictures和GameSounds,分别保存项目的图片和声音资源,如下图:
具体代码:
主窗体类FrmBlock.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace ShotBlock
{
public partial class FrmBlock : Form
{
Bitmap bmpBackground;
Bitmap bmpPaddle;
Bitmap bmpBlock;
Bitmap bmpBall;
static readonly Rectangle GamePaddleRect = new Rectangle(39, 1, 93, 23); //GamePaddleRect对应挡板在位图Break,bmp中的位置和大小
static readonly Rectangle GameBlockRect = new Rectangle(136, 1, 62, 27);
static readonly Rectangle GameBallRect = new Rectangle(1, 1, 36, 36);
static Rectangle PaddleRect;
Point centerOfPaddle;
int GameLevel = 1;//游戏关卡数
int GameLives = 4;//玩家有5条命
BlockClass[,] Blocks = new BlockClass[12, 14];
[DllImport("winmm")]
public static extern bool PlaySound(string szSound, int hMod, int i);
bool isGameOver = false;
bool bSounding = false;
private void LoadPictures()
{
bmpBackground = LoadBitmap.LoadBmp("Background");
Bitmap bmpBreak = LoadBitmap.LoadBmp("Break");
bmpPaddle = bmpBreak.Clone(GamePaddleRect, bmpBreak.PixelFormat);
bmpBlock = bmpBreak.Clone(GameBlockRect, bmpBreak.PixelFormat);
bmpBall = bmpBreak.Clone(GameBallRect, bmpBreak.PixelFormat);
}
private void DrawGame(Graphics graphic)
{
//画背景图
graphic.DrawImage(bmpBackground, new Rectangle(0, 0, this.ClientRectangle.Width - 1, this.ClientRectangle.Height - 1));
//显示挡板
graphic.DrawImage(bmpPaddle, new Rectangle(centerOfPaddle.X - 93 / 2, centerOfPaddle.Y, 93, 23));
for(int row=0;row<12;row++)
for (int col = 0; col < 14; col++)
{
if (Blocks[row, col]