C# 委托事件简单示例
【摘要】 使用C#语言进行编写:设计一个战士对象基础防御为50,基础经验值0,每间隔3秒(时间可以调整)经验会提升10,当经验到到达100时升级,升级时自己基础防御力提升%0.5,友军(防御是40)提升%0.1,敌人(防御是30)会下降%0.2,使用事件委托的概念完成升级时的需求。
using System;using System.Collections.Generic;...
使用C#语言进行编写:设计一个战士对象基础防御为50,基础经验值0,每间隔3秒(时间可以调整)经验会提升10,当经验到到达100时升级,升级时自己基础防御力提升%0.5,友军(防御是40)提升%0.1,敌人(防御是30)会下降%0.2,使用事件委托的概念完成升级时的需求。
-
using System;
-
using System.Collections.Generic;
-
using System.Linq;
-
using System.Text;
-
using System.Threading.Tasks;
-
-
namespace Second
-
{
-
//定义升级委托
-
public delegate void ShengJi();
-
-
class Program
-
{
-
static void Main(string[] args)
-
{
-
Warrior wat = new Warrior();
-
Allies all = new Allies();
-
Enemy ene = new Enemy();
-
//注册方法
-
wat.shengji += all.AddDefend;
-
wat.shengji += ene.ReDefend;
-
//游戏开始
-
wat.Upgrade();
-
-
///注销方法
-
wat.shengji -= all.AddDefend;
-
wat.shengji -= ene.ReDefend;
-
-
Console.Read();
-
}
-
}
-
/// <summary>
-
/// 战士类
-
/// </summary>
-
public class Warrior
-
{
-
public event ShengJi shengji; //定义事件
-
public float defend = 50; //基础防御值和,经验值
-
public int exp = 0;
-
private int time = 1;
-
int count = 1; //战士等级
-
public void Upgrade()
-
{
-
while ( count < 30) //人物满级了
-
{
-
if ((time % 3) == 0) //假装是3秒
-
{
-
exp+=10; //经验增长10
-
}
-
time++;
-
//Console.WriteLine(exp);
-
if (exp == 100)
-
{
-
exp = 0;
-
count++;
-
Console.WriteLine();
-
Console.WriteLine("=======当前等级为{0}:=======",count);
-
-
defend *= (1 + 0.05f); //战士防御值增加
-
Console.WriteLine("自己的防御值:" + defend);
-
//调用事件
-
shengji();
-
}
-
}
-
}
-
}
-
/// <summary>
-
/// 友军类
-
/// </summary>
-
class Allies
-
{
-
public float defend = 40; //初始防御值
-
public void AddDefend()
-
{
-
defend *= (1 + 0.01f); //提升防御值的0.01
-
Console.WriteLine("友军的防御值:" + defend);
-
}
-
}
-
-
/// <summary>
-
/// 敌军类
-
/// </summary>
-
class Enemy
-
{
-
public float defend = 30; //初始防御值
-
public void ReDefend()
-
{
-
defend *= (1 - 0.02f); //降低防御值的0.02
-
Console.WriteLine("敌人的防御值:" + defend);
-
}
-
}
-
}
文章来源: czhenya.blog.csdn.net,作者:陈言必行,版权归原作者所有,如需转载,请联系作者。
原文链接:czhenya.blog.csdn.net/article/details/77775819
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)