Hero.class.php文件中
<?php
class Hero
{
public $blood;
public $gongji;
public $jineng = array();
public $level;
public $name;
public $money;
//构造函数,初始化成员
function __construct($n)
{
$this->blood = 100;
$this->gongji = 10;
$this->jingyan = 0;
$this->level = 1;
$this->money = 100;
$this->name = $n;
}
//打怪函数
function DaGuai()
{
//获取经验
//$jy = Math.floor(rand(10,100));
$jy = floor(rand(10,100));
if($jy>=30)
{
//将该英雄经验增加
$this->jingyan = $this->jingyan+$jy;
//判断是否要升级
if($this->jingyan >= 50)
{
$this->level +=1;
$this->jingyan = 0;
$this->gongji +=5;
$this->blood +=20;
}
echo $this->name."打死了一个怪物,获得了{$jy}点经验";
}
else
{
if($this->level = 1)
{}
else
{
$this->level -=1;
}
echo "你被怪物打死了,等级减一,等级降为{$this->level}";
}
}
//学习技能
function XueXi()
{
//花钱
$hf = floor(rand(0,20));
$n = floor(rand(0,5));
// 技能哭里选择技能
switch($n)
{
case 0:
array_push($this->jineng,"冲锋");
break;
case 1:
array_push($this->jineng,"嘲讽");
break;
case 2:
array_push($this->jineng,"突刺");
break;
case 3:
array_push($this->jineng,"沉默");
break;
case 4:
array_push($this->jineng,"变羊");
break;
case 5:
array_push($this->jineng,"加血");
break;
}
}
//查看英雄信息
function Show()
{
echo "英雄的名称:{$this->name}<br />";
echo "英雄的血量:{$this->blood}<br />";
echo "英雄的公鸡:{$this->gongji}<br />";
echo "英雄的经验:{$this->jingyan}<br />";
echo "英雄的等级:{$this->level}<br />";
echo "技能为:";
//不可以echo "技能为:{$this->jineng}<br />";因为jineng是数组,需要foreach遍历
foreach($this->jineng as $v)
{
echo $v.",";
}
}
}
?>
play.php文件中(同一文件夹)
<?php
include "Hero.class.php";
$r = new Hero("赵大牛");
$r->DaGuai();
$r->XueXi();
$r->Show();
$r->DaGuai();
$r->XueXi();
$r->Show();
$r->DaGuai();
$r->XueXi();
$r->Show();
$r->DaGuai();
$r->XueXi();
$r->Show();
$r->DaGuai();
$r->XueXi();
$r->Show();
?>
结果