全方位站长技能、SEO优化学习平台
当前位置:网站首页 > PHP笔记 > 正文

PHP网页小游戏分享:如何用PHP写一个简单的网页小游戏?

作者:admin发布时间:2024-05-02分类:PHP笔记浏览:115


温馨提示:手机扫码可阅读当前文章!
文章简介:好几天没有更新了,主要是不知道写什么?那么今天我就来分享一个我用PHP写的一个网页小游戏吧。该小游戏使用PHP和html混编来完成的,代码看起来有点乱,太多判断句,一不小心,把我自己都能搞蒙圈!没办法,为了方便分享代码,我只好写到一个PHP...

好几天没有更新了,主要是不知道写什么?那么今天我就来分享一个我用PHP写的一个网页小游戏吧。该小游戏使用PHP和html混编来完成的,代码看起来有点乱,太多判断句,一不小心,把我自己都能搞蒙圈!没办法,为了方便分享代码,我只好写到一个PHP脚本里面,直接贴出完整代码,就可以给喜欢该代码的朋友直接使用了。

PHP网页小游戏分享:如何用PHP写一个简单的网页小游戏?  第1张

下面我们先分享代码,以供大家研究参考!本代码大概400多行,脚本文件大小大概是12KB。代码涉及了读取和写入TXT文件、数组排序、SESSION、数组和JSON数据的转换、数组循环输出、if...else语句、get数据与post数据的使用、自定义函数和switch()函数的使用等。如果你想要看懂该代码,还是很容易的,但是要想理解代码逻辑那估计得用点心了,毕竟我自己都得慢慢分析!也可能因为自学的PHP,没有系统的学些过PHP课程,导致我写代码的习惯不是太好吧,到底不够精通和专业。然而我觉得,小白学习PHP,看我写的代码,应该更容易接受一点!

代码运行效果图片预览

PHP网页小游戏分享:如何用PHP写一个简单的网页小游戏?  第2张

index.php:

<?php
session_start();
// 检查变量是否已设置,未设置则设为默认值
function initialize_game_variable() {
    $_SESSION['lx'] = 0;
    $_SESSION['bosshp'] = 500;
    $_SESSION['playerhp'] = 100;
    $_SESSION['playerpf'] = 0;
    $_SESSION['dui'] = 0;
    $_SESSION['cuo'] = 0;
    $_SESSION['message'] = 0;
}
// 初始化游戏变量,将所有游戏变量重置为默认值
if (!isset($_GET['page']) || $_GET['page'] == '1') {
    initialize_game_variable();
}
if (isset($_GET['page']) > 0 and $_SESSION['bosshp'] < 0) {
    echo "<script>alert('挑战成功!'); window.location.assign('index.php');</script>";
    initialize_game_variable();
    exit;
}
if (isset($_GET['page']) > 0 and $_SESSION['playerhp'] < 0) {
    echo "<script>alert('挑战失败!'); window.location.assign('index.php');</script>";
    initialize_game_variable();
    exit;
}
// 生成数学题目
function generate_question() {
    $operators = array('+', '-', '*');
    $operator = $operators[array_rand($operators)];
    $num1 = rand(1, 100);
    $num2 = rand(1, 100);
    switch ($operator) {
        case '+':
            $result = $num1 + $num2;
            break;
        case '-':
            $result = $num1 - $num2;
            break;
        case '*':
            $result = $num1 * $num2;
            break;
        default:
            return generate_question();
    }
    $_SESSION['as'] = $result;
    return "$num1 $operator $num2";
}
function game_logs($data) {
    $time = time();
    $file = 'list.txt'; 
    file_put_contents($file, $data);
}
class FileProcessor {
    private $file;
    public function __construct($file) {
        $this->file = $file;
    }
    public function processData() {
        $data = file_get_contents($this->file);
        $lines = explode("\n", $data);
        $sortedArray = array();
        foreach ($lines as $line) {
            $json = json_decode($line, true);
            if ($json) {
                $sortedArray[] = $json;
            }
        }
        usort($sortedArray, function($a, $b) {
            return $b["gamepf"] - $a["gamepf"];
        });
        return $sortedArray;
    }
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数学快问快答挑战</title>
<style>
body{
    background-color: #673AB7;
    font-family: Arial, san-serif;
}
.main{
    max-width: 800px;
    margin: auto;
    background-color: #FFF;
    padding: 20px;
    border-radius: 10px;
}
.main h1 {
    text-align: center;
    font-size: 2em;
    color: #673AB7;
}
.intro{
    background-color: #512DA8;
    color: #FFF;
    padding: 10px;
    border-radius: 5px;
    margin-top: 50px;
    font-size: 0.8em;
}
.userinfo{
    background-color: #EDE7F6;
    color: #512DA8;
    padding: 10px;
    border-radius: 5px;
    margin-top: 20px;
    font-size: 0.9em;
}
.userinfo form{
    display: inline-block;
    margin-top: 10px;
}
.userinfo input[type=text], .userinfo input[type=submit]{
    font-size: 1.2em;
    padding: 2px 5px;
    border-radius: 3px;
    border: 1px solid #512DA8;
}
.game-body{
    padding: 50px;
    font-size: 1.5em;
    color: #512DA8;
}
.game-body form{
    margin-top: 20px;
}
.game-body input[type=text], .game-body input[type=submit]{
    font-size: 1.3em;
    padding: 2px 5px;
    border-radius: 3px;
    border: 1px solid #512DA8;
}
.message{
    background-color: #BA68C8;
    color: #FFF;
    padding: 10px;
    border-radius: 5px;
    margin-top: 20px;
    font-size: 1.1em;
}
.health-bar {
    width: 100%;
    height: 20px;
    background: linear-gradient(to right, red 100%);
    position: relative;
    border: 1px solid #000;
    border-radius: 5px;
    margin: 20px auto;
}
.health-bar::before {
    content: "";
    display: block;
    height: 100%;
    width: var(--health);
    background-color: rgba(255, 0, 0, 0.8);
    border-radius: 5px;
}
.health-text {
    text-align: center;
    font-weight: bold;
    margin-top: 10px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}
.button {
    display: inline-block;
    padding: 10px 20px;
    background-color: #00B0F0;
    color: yellow;
    font-size: 1.5em;
    border: none;
    border-radius: 10px;
    cursor: pointer;
    text-decoration: none;
    text-align: center;
}
.button a {
    color: yellow;
    text-decoration: none;
    display: inline-block;
    width: 100%;
    height: 100%;
}
</style>
</head>
<body>
<div>
<h1>数学快问快答挑战游戏</h1>
<div>
<?php
if (isset($_SESSION['username'])) {
echo '<span style="font-size: 1.5em;">'.$_SESSION['username'].':</span><span style="font-size: 1.2em;">欢迎加入数学快问快答挑战游戏!当前分数:'.$_SESSION['playerpf'].'</span>';
    $bossHealthPercentage = ($_SESSION['bosshp'] / 500) * 100; 
    $playerHealthPercentage = ($_SESSION['playerhp'] / 100) * 100; 
    echo <<<HTML
    <table width="100%">
    <tbody>
    <tr>
    <th valign="left" style="border-color: rgb(221, 221, 221);" width="100">BOSS:</th>
    <td valign="left" style="border-color: rgb(221, 221, 221);" width="100%">
    <div style="--health: {$bossHealthPercentage}%; ">HP值:{$_SESSION['bosshp']}/500</div>
    </td>
    </tr>
    <tr>
    <th valign="left" style="border-color: rgb(221, 221, 221);" width="100">{$_SESSION['username']}</th>
    <td valign="left" style="border-color: rgb(221, 221, 221);" width="100%">
    <div style="--health: {$playerHealthPercentage}%; ">HP值:{$_SESSION['playerhp']}/100</div>
    </td>
    </tr>
    </tbody>
    </table>
    HTML;
    if($_SESSION['message'] != 0){
        echo '<p><strong>上次挑战结果:</strong></p >';
        echo '<div>'.$_SESSION['message'].'</div>';
        initialize_game_variable();
    }
}else {
    if (!isset($_POST['username'])) {
        echo <<<HTML
        <form id="joinForm" action="index.php" method="POST">
        请输入您的名字:<input type="text" name="username" required><br>
        <input type="submit" value="提交">
        </form>
        HTML;
    } else {
        $_SESSION['username'] = $_POST['username'];
echo '<span style="font-size: 1.5em;">'.$_SESSION['username'].':</span><span style="font-size: 1.2em;">欢迎加入数学快问快答挑战游戏!</span>';
    }
}
?>
</div><div>
<?php
if (!isset($_GET['page'])) {
    if (isset($_SESSION['username'])) {
        echo '<center><div><a href="index.php?page=1" target="_self">请点击此处开始挑战</a></div></center>';
    } else {
        echo '必须输入用户名,才可以挑战!';
    }
}
if (isset($_GET['page']) && isset($_SESSION['username'])) {
    if (isset($_POST['as'])) {
        $post_as = $_POST['as'];
        $session_as = $_SESSION['as'];
        if ($post_as == $session_as) {
            $_SESSION['lx']++;
            $_SESSION['dui'] = $_SESSION['dui'] + 1;
            $diff = time() - $_POST['time'];
            $decimal = round($diff / 1000, 3);
            $bcpf = 500 * ($_SESSION['lx'] + $decimal);
            $bcpf = round($bcpf);
            $_SESSION['playerpf'] += $bcpf;
            $_SESSION['bosshp'] -= 10 + $_SESSION['lx'] * 5;
            if ($_SESSION['bosshp'] <= 0) {
                $annums = $_SESSION['dui'] + $_SESSION['cuo'];
                $_SESSION['playerpf'] = $_SESSION['playerpf'] *($_SESSION['dui'] / $annums);
                $_SESSION['playerpf'] = round($_SESSION['playerpf']);
                $message .= '恭喜您,尊敬的'.$_SESSION['username'].',您的本次挑战完美成功!您的本次挑战分:<span>' . $_SESSION['playerpf']. '</span>';
                $message .= '<br/>你本次一共答题:'.$annums.'道,对:<span>'.$_SESSION['dui'].'</span>道,错:<span>'.$_SESSION['cuo'].'</span>道!';
                $gamelog = array('username' => $_SESSION['username'], 'gamepf' => $_SESSION['playerpf'], 'time' => time()); 
                $fileProcessor = new FileProcessor('list.txt');
                $sortedData = $fileProcessor->processData(); 
                array_push($sortedData, $gamelog);
                // 按照'gamepf'值对$sortedData数组进行排序
                usort($sortedData, function($a, $b) {
                    return $b['gamepf'] - $a['gamepf'];
                });
                $x = 0;
                $finalData = "";
                foreach ($sortedData as &$data) {
                    $x++;
                    if ($x <= 100 && $x > 0) {
                        $finalData .= json_encode($data)."\n"; 
                    }
                }
                if ($x == 0) {
                    $finalData .= json_encode($gamelog); 
                }
                game_logs($finalData);
                initialize_game_variable();
                $_SESSION['message'] = $message;
                echo "<script>alert('挑战成功!'); window.location.assign('index.php');</script>";
                exit;
            } else {
                $message = '回答正确!请继续挑战下一题!当前挑战分:' . $bcpf;
                $url = 'index.php?page=' . ($_GET['page'] + 1);
                echo "<script>alert('$message'); window.location.assign('$url');</script>";
                exit;
            }
        } else {
            $_SESSION['playerpf'] -= 1000;
            $_SESSION['playerpf'] = round($_SESSION['playerpf']);
            $_SESSION['lx'] = 0;
            $_SESSION['playerhp'] -= 10;
            $_SESSION['cuo'] = $_SESSION['cuo'] + 1;
            if ($_SESSION['playerhp'] <= 0) {
                $annums = $_SESSION['dui'] + $_SESSION['cuo'];
                $message .= '很抱歉,尊敬的:'.$_SESSION['username'].',你此次挑战失败了!请继续努力';
                $message .= '<br/>你本次一共答题:<span>'.$annums.'</span>道,对:<span>'.$_SESSION['dui'].'</span>道,错:<span>'.$_SESSION['cuo'].'</span>道!';
                initialize_game_variable();
                $_SESSION['message'] = $message;
                echo "<script>alert('挑战失败!'); window.location.assign('index.php');</script>";
                exit;
            } else {
                $message = '回答错误!请继续挑战下一题!本次扣除积分:1000';
                $url = 'index.php?page=' . ($_GET['page'] + 1);
                echo "<script>alert('$message'); window.location.assign('$url');</script>";
                exit;
            }
        }
        $_POST = array();
    }
    if ($_SESSION['bosshp'] > 0 && $_SESSION['playerhp'] > 0) {
        echo '';
        echo '<center>'.generate_question().'等于多少?';
        echo '<form id="joinForm" action="index.php?page=' . ($_GET['page']) . '" method="POST">';
        echo '<input type="text" name="as" required>';
        echo '<input type="hidden" name="time" value="'.time().'">';
        echo '<input type="submit" value="提交">';
        echo '</form></center>';
    }
}
?>
</div>
<div>
<table width="100%">
<thead>
<tr>
<th style="border-color: rgb(221, 221, 221);" width="10%">
排序<br/>
</th>
<th style="border-color: rgb(221, 221, 221);" width="35%">
玩家
</th>
<th style="border-color: rgb(221, 221, 221);" width="25%">
评分
</th>
<th style="border-color: rgb(221, 221, 221);" width="30%">
挑战时间
</th>
</tr>
</thead>
<tbody>
<?php
$fileProcessor = new FileProcessor('list.txt');
$sortedData = $fileProcessor->processData();
$i = 0;
foreach ($sortedData as $value) {
    $i++;
    echo '<tr>';
    echo '<td width="10%" style="border-color: rgb(251, 213, 181);">' .$i . '</td>';
    echo '<td width="35%" style="border-color: rgb(251, 213, 181);">' .$value['username'] . '</td>';
    echo '<td width="25%" style="border-color: rgb(251, 213, 181);">' .$value['gamepf'] . '</td>';
    echo '<td width="30%" style="border-color: rgb(251, 213, 181);">' .date('Y-m-d H:i:s',$value['time']) . '</td>';
    echo '</tr>';
}
?>
</tbody>
</table>
</div>
<div>
<h3>游戏规则介绍:</h3>
<p>
<strong>评分机制:</strong>
</p >
<p>
1:每答对一题,加上500基础分,连续答对额外获得奖励分(系统根据答题使用时间和连续答对次数进行奖励)!<br/>
2:每答错一题,扣除1000评分,终止连续答对次数!
</p >
<p>
<strong>战斗机制:</strong>
</p >
<p>
1:BOSS初始值,BOSS血量500点,每答对一题,对BOSS伤害10点血量,连续答对根据连续答对次数获得额外伤害值!答错不对BOSS造成伤害,同时终止连续答对额外伤害值!<br/>
2:玩家初始值,玩家血量100点,每答错一题,玩家被BOSS伤害10点,玩家对BOSS不造成伤害,无连续答错惩罚。
</p >
<p>
<strong>胜负机制:</strong>
</p >
<p>
1:胜利判断依据,BOSS血量小于或等于0,玩家血量大于0;<br/>
2:失败判断依据,玩家血量小于或等于0,BOSS血量大于0;
</p >
</div>
</div>
</body>
</html>


代码讲解:

我们首先设定一个游戏规则和胜负评判机制,然后用代码来完成,游戏规则也在代码中介绍,这里就不说了,我们来分析一下代码中一些常用的PHP知识点吧!

我们首先自定义了一个函数:

function initialize_game_variable() {
    $_SESSION['lx'] = 0;
    $_SESSION['bosshp'] = 500;
    $_SESSION['playerhp'] = 100;
    $_SESSION['playerpf'] = 0;
    $_SESSION['dui'] = 0;
    $_SESSION['cuo'] = 0;
    $_SESSION['message'] = 0;
}


这里我们自定义的函数initialize_game_variable()的作用主要是初始化游戏数据,每一局游戏的开始,我们都使用initialize_game_variable()函数对必要数据进行初始化,为玩家挑战游戏做好准备!

代码中我们就通过获取$_GET['page']来判断游戏是否开始,利用BOSS的血量和玩家的血量来判断游戏是否结束,文中代码:

// 初始化游戏变量,将所有游戏变量重置为默认值
if (!isset($_GET['page']) || $_GET['page'] == '1') {
    initialize_game_variable();
}
if (isset($_GET['page']) > 0 and $_SESSION['bosshp'] < 0) {
    echo "<script>alert('挑战成功!'); window.location.assign('index.php');</script>";
    initialize_game_variable();
    exit;
}
if (isset($_GET['page']) > 0 and $_SESSION['playerhp'] < 0) {
    echo "<script>alert('挑战失败!'); window.location.assign('index.php');</script>";
    initialize_game_variable();
    exit;
}


本代码中用到一个我之前文章没有介绍过的一个函数:switch(),该代码可以在一定程度上减少if判断句。当然本文的代码中没有很好的体现。

// 生成数学题目
function generate_question() {
    $operators = array('+', '-', '*');
    $operator = $operators[array_rand($operators)];
    $num1 = rand(1, 100);
    $num2 = rand(1, 100);
    switch ($operator) {
        case '+':
            $result = $num1 + $num2;
            break;
        case '-':
            $result = $num1 - $num2;
            break;
        case '*':
            $result = $num1 * $num2;
            break;
        default:
            return generate_question();
    }
    $_SESSION['as'] = $result;
    return "$num1 $operator $num2";
}


这里的switch($v)函数,通过$v值的不同,运行不同的代码。在通过判断句运行较小代码块的时候,使用该方法,十分简洁,但是运行的代码块比较复杂的时候,代码看起来就更乱。

本来时间已经很晚了,文章篇幅因为代码的原因,看起来已经很臃肿了,不想在继续写下去了,但是我觉得关于代码中数组的排序的知识点,有必要分享出来给大家借鉴一下。

gamelog = array('username' => $_SESSION['username'], 'gamepf' => $_SESSION['playerpf'], 'time' => time()); 
$fileProcessor = new FileProcessor('list.txt');
$sortedData = $fileProcessor->processData(); 
array_push($sortedData, $gamelog);
// 按照'gamepf'值对$sortedData数组进行排序
usort($sortedData, function($a, $b) {
    return $b['gamepf'] - $a['gamepf'];
});
$x = 0;
$finalData = "";
foreach ($sortedData as &$data) {
    $x++;
    if ($x <= 100 && $x > 0) {
        $finalData .= json_encode($data)."\n"; 
    }
}
if ($x == 0) {
    $finalData .= json_encode($gamelog); 
}
game_logs($finalData);


$gamelog是把在玩家挑战成功以后,把用户名、评分、和时间组装到一个数组利,然后使用json_encode()把它转换成json数据以后,保存道txt文件里。这里用到了两个函数,都与数组有关,array_push($oldarr, $newarr)与usort()函数。array_push($oldarr, $newarr)的作用是把$newarr函数插入到$oldarr函数里。

usort($sortedData, function($a, $b) {
    return $b['gamepf'] - $a['gamepf'];
});


该usort()函数在这里的作用是把$sortedData数组按照子数组键名'gamepf'对应值的大小进行从大到小进行排序,以便我们在对一些数组需要按照升序或者降序排列的时候使用!

好了,实在不能再写下去了,代码分享和代码解读就到这里了。代码不完善和讲述有异议的欢迎留言讨论,让我们一起学习成长!

欢迎站长或从事网站建设服务的朋友加入我们的‘‘网站建设交流群’’,请扫码加入,如果二维码过期,请私聊该微信公众号‘‘文煞站长笔记网’’!

PHP网页小游戏分享:如何用PHP写一个简单的网页小游戏?  第3张


欢迎您,来自美国–俄亥俄州–特拉华县–都柏林的朋友,您的IP:18.217.45.29,您的网络:Amazon数据中心


PHP笔记排行
随机推荐
猜你喜欢

服务热线

1888888888

要发发发发发发

站长微信公众号

站长微信公众号

分享:

支付宝

微信