您的位置:首页 > 其它

WPF游戏 菜鸟版俄罗斯方块

2010-09-20 15:08 176 查看
在以前的MFC、winform中实现一个游戏程序是一件相当困难的事情,自从WPF诞生后,富客户端设计工作变得相对简单。本人刚学WPF不久,写写劣质代码望大侠莫见笑。自于这个游戏本身的实现方式我并未去研究,这里只是根据自己的理解来做。

代码下载:http://files.cnblogs.com/lipan/WpfGame1.rar

主要思想:

一、提供一个容器类(Container),用来作为方块活动的网格状区域。由于WPF自带Grid控件支持网格,因此就直接利用了。


1.Container类需要关联到Grid,活动区域;和waitingGrid等候区域(下一个出现的方块)

2.在Container类中实现消层的逻辑


二、提供一个方块基类(Box),7中方块全部从其派生。


1.每个方块包含4个Rectangle(小方格)



2.通过一个工厂类随机产生某个方块的实例



3.基类实现方块移动、变形、等逻辑、子类定义方块颜色、初始化方式,确定每个方格相对坐标。

4.在方块下降到底部触发OnBottom事件,Container接受此事件触发消行逻辑。Container类中OnGameover事件被界面层接受处理。


运行效果:

Result类

/// <summary>
/// 记录分数和级别
/// </summary>
class Result : INotifyPropertyChanged
{
Result()
{
Score = 0;
Level = 1;
}

//单例模式
private static Result instance;
private static readonly object syncRoot = new object();
public static Result GetInstance()
{
if (instance == null)
{

lock (syncRoot)
{

if (instance == null)
{
instance = new Result();
}
}
}
return instance;
}

int score;
int level;

public int Score
{
get { return score; }
set { score = value; Notify("Score"); }
}
public int Level
{
get { return level; }
set { level = value; Notify("Level"); }
}

public void CalculateScore(int Lines)
{
switch (Lines)
{
case 1: Score += 5;
break;
case 2: Score += 15;
break;
case 3: Score += 30;
break;
case 4: Score += 50;
break;
default: Score += 0;
break;
}

if (Score < 20) Level = 1;
else if (Score < 100) Level = 2;
else if (Score < 300) Level = 3;
else if (Score < 500) Level = 4;
else if (Score < 1000) Level = 5;
else if (Score < 3000) Level = 6;
else if (Score < 5000) Level = 7;
else Level = 8;

}

void Notify(string propName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}

public event PropertyChangedEventHandler PropertyChanged;
}


在该类中用单例模式控制产生单一实例,并通过实现接口绑定到界面分数展示台。

界面XAML如下:

<Grid Grid.Column="1" Grid.Row="1" Height="65" HorizontalAlignment="Left" Margin="5,6,0,0" Name="grid4" VerticalAlignment="Top" Width="100">
<Label Content="积分:" Height="28" Name="label1" Margin="0,5,0,32" HorizontalAlignment="Left" Width="38" />
<Label  Content="{Binding Path=Score}" Height="28" Name="label2" Margin="35,5,0,32" />
<Label Content="级别:" Height="28" Name="label3" Margin="0,34,0,3" HorizontalAlignment="Left" Width="38" />
<Label Content="{Binding Path=Level}" Height="28" Name="label4" Margin="0,0,0,4" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="65" />
</Grid>


这样,代码中对Result赋值,直接影响界面控件展示数值的变化:

/// <summary>
/// 活动方块到达底部时触发
/// </summary>
static public void ActivityBox_OnBottom(object sender, EventArgs e)
{
Result.GetInstance().CalculateScore(RemoveLine());
NewBoxReadyToDown();
}


这里根据消行函数返回值此处对result实例进行修改,界面数值(分数、级别)也同步变化。

最后,界面添加功能按钮,实现Window_KeyDown事件 OnGameover事件,游戏完成。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐