利用workerman+html開發簡單的在線五子棋對戰

1、workerman下載,地址:https://github.com/walkor/workerman
2、cd到workerman項目根目錄下,在workerman根目錄下新建game.php,而後編寫五子棋服務端交互代碼,最後命令啓動已經寫好的五子棋服務器
sudo php game.php  startjavascript

game.php的代碼以下:php

<?php
use Workerman\Worker;

require_once __DIR__ . '/Autoloader.php';

$global_uid = 0;
//棋盤大小,默認15行15列
$global_i = 15;
$global_j = 15;

// 當客戶端連上來時分配uid
function handle_connection($connection)
{
    global $text_worker, $global_uid, $global_i, $global_j;

    // 爲這個連接分配一個uid
    $connection->uid = ++$global_uid;
    $text_worker->uidConnections[$connection->uid] = array('cons' => $connection);
    $text_worker->user_data[$connection->uid] = array('playing' => 0, 'name' => 'player' . $connection->uid, 'qipan' => array(), 'type' => 0, 'move' => 0);
    $json = array('status' => 1, 'msg' => '', 'data' => array());
    $json['data']['name'] = $text_worker->user_data[$connection->uid]['name'];
    $connection->send(json_encode($json)); //生成玩家暱稱
    echo "player {$connection->uid} connected!\n";

    //分配對手
    foreach ($text_worker->user_data as $k => $val) {
        /*var_dump($val['playing']);*/
        if ($val['playing'] == 0 && $k != $connection->uid) {
            //初始化棋盤
            $init_data = array();
            for ($i = 0; $i <= $global_i; $i++) {
                for ($j = 0; $j <= $global_j; $j++) {
                    $init_data[$i][$j] = 0;
                }
            }
            $text_worker->user_data[$k]['qipan'] = $init_data;
            $text_worker->user_data[$connection->uid]['qipan'] = $init_data;

            $text_worker->user_data[$k]['playing'] = $connection->uid;
            $text_worker->user_data[$connection->uid]['playing'] = $k;

            //分配紅黑方
            $text_worker->user_data[$k]['type'] = 1;
            $text_worker->user_data[$k]['move'] = 1;
            $text_worker->user_data[$connection->uid]['type'] = 2;
            $text_worker->user_data[$connection->uid]['move'] = 0;

            $json = array('status' => 2, 'msg' => '初始化棋盤...', 'data' => array());
            $json['data']['qipan'] = $init_data;

            $text_worker->uidConnections[$k]['cons']->send("爲你匹配到對手{$text_worker->user_data[$connection->uid]['name']}!");
            $text_worker->uidConnections[$connection->uid]['cons']->send("爲你匹配到對手{$val['name']}!");
            break;
        }
    }
    /*var_dump($text_worker->user_data);*/
}

// 當客戶端發送消息過來時
function handle_message($connection, $data)
{
    global $text_worker, $global_i, $global_j;
    $data = json_decode($data, true);
    if ($data['status'] == 2 && $text_worker->user_data[$connection->uid]['playing'] > 0 && $text_worker->user_data[$connection->uid]['move'] == 1) {
        $my_uid = $connection->uid;
        $your_uid = $text_worker->user_data[$my_uid]['playing'];
        $qipan = $text_worker->user_data[$your_uid]['qipan'];
        $press = explode('_', $data['data']);
        if (!empty($press)) {
            $press_val = $qipan[$press[0]][$press[1]];
            if ($press_val != 0) {
                return;
            } else {
                $qipan[$press[0]][$press[1]] = $text_worker->user_data[$my_uid]['type'];

                $text_worker->user_data[$my_uid]['qipan'] = $qipan;
                $text_worker->user_data[$your_uid]['qipan'] = $qipan;
                $text_worker->user_data[$your_uid]['move'] = 1;
                $text_worker->user_data[$my_uid]['move'] = 0;

                $json = array('status' => 2, 'msg' => '', 'data' => array());
                $json['data']['type'] = $text_worker->user_data[$my_uid]['type'];
                $json['data']['press_i'] = $press[0];
                $json['data']['press_j'] = $press[1];
                $text_worker->uidConnections[$my_uid]['cons']->send(json_encode($json));
                $text_worker->uidConnections[$your_uid]['cons']->send(json_encode($json));

                $count = get_who_win($qipan, $press[0], $press[1], $text_worker->user_data[$my_uid]['type'], $global_i, $global_j);
                file_put_contents('./qipan', json_encode($qipan));
                if ($count >= 5) { //分出勝負
                    $json = array('status' => 3, 'msg' => $text_worker->user_data[$my_uid]['name'] . ' Win !', 'data' => array());
                    $json['data']['type'] = $text_worker->user_data[$my_uid]['type'];
                    $text_worker->uidConnections[$my_uid]['cons']->send(json_encode($json));
                    $text_worker->uidConnections[$your_uid]['cons']->send(json_encode($json));
                }
            }
        }
    }

}

// 當客戶端斷開時,廣播給全部客戶端
function handle_close($connection)
{
    global $text_worker;
    /*foreach ($text_worker->connections as $conn) {
        $conn->send("user[{$connection->uid}] logout");
    }*/
}

/**
 * 判斷輸贏
 * $qipan 棋盤數據
 * $i 下子時的橫座標
 * $i 下子時的縱座標
 * $type 1黑方 2紅方
 * $global_i 棋盤邊界值
 * $global_j 棋盤邊界值
 */
function get_who_win($qipan = array(), $i = -1, $j = -1, $type = 0, $global_i = 0, $global_j = 0)
{

    $count = 0;
    $temp_type = $type;
    if (empty($qipan) || $i < 0 || $j < 0 || $type <= 0) {
        return $count;
    }
    echo json_encode($qipan)."\n";
    echo 'i=' . $i . '|j=' . $j . '|type=' . $type . '|gi=' . $global_i . '|gj=' . $global_j . "\n";
    /*左右上下的判斷*/
    $count = 1;
    $a = array(
        0 => array('index' => $j, 'border' => $global_j), //左右,
        1 => array('index' => $i, 'border' => $global_i) //上下
    );
    for ($round = 0; $round <= 1; $round++) {
        $mov1_num = 1;
        $mov2_num = 1;
        while (true) {
            $mov1 = $a[$round]['index'] + $mov1_num;
            $mov2 = $a[$round]['index'] - $mov2_num;
            $temp_mov1 = $temp_mov2 = -1;
            if ($mov1_num > 0) {
                if ($round == 0 && $mov1 <= $global_j) {
                    $temp_mov1 = $qipan[$i][$mov1];
                    var_dump($i.','.$mov1.','.$temp_mov1);
                } elseif ($round == 1 && $mov1 <= $global_i) {
                    $temp_mov1 = $qipan[$mov1][$j];
                }

                if ($temp_mov1 == $temp_type) {
                    $count++;
                    var_dump('count='.$count);
                    $mov1_num++;
                } else {
                    $mov1_num = 0;
                }

            } else {
                $mov1_num = 0;
            }

            if ($mov2 >= 0 && $mov2_num > 0) {
                if ($round == 0) {
                    $temp_mov2 = $qipan[$i][$mov2];
                    var_dump($i.','.$mov2.','.$temp_mov1);
                } elseif ($round == 1) {
                    $temp_mov2 = $qipan[$mov2][$j];
                }
                if ($temp_mov2 == $temp_type) {
                    $count++;
                    $mov2_num++;
                } else {
                    $mov2_num = 0;
                }
            } else {
                $mov2_num = 0;
            }
            if ($count >= 5) {
                return $count;
            }
            if (($mov1_num == 0 && $mov2_num == 0)) {
                break;
            }


        }
    }

    /*斜角的判斷*/
    $count = 1;
    for ($round = 0; $round <= 1; $round++) {
        $mov1_num = 1;
        $mov2_num = 1;
        while (true) {
            $temp_mov1 = $temp_mov2 = -1;
            if (($i - $mov1_num) >= 0 && ($j - $mov1_num) >= 0 && ($j + $mov1_num) <= $global_j && $mov1_num > 0) {
                if ($round == 0) {
                    $temp_mov1 = $qipan[$i - $mov1_num][$j + $mov1_num];
                } elseif ($round == 1) {
                    $temp_mov1 = $qipan[$i - $mov1_num][$j - $mov1_num];
                }

                if ($temp_mov1 == $temp_type) {
                    $count++;
                    $mov1_num++;
                } else {
                    $mov1_num = 0;
                }

            } else {
                $mov1_num = 0;
            }

            if (($i + $mov2_num) <= $global_i && ($j - $mov2_num) >= 0 && ($j + $mov2_num) <= $global_j && $mov2_num > 0) {
                if ($round == 0) {
                    $temp_mov2 = $qipan[$i + $mov2_num][$j - $mov2_num];
                } elseif ($round == 1) {
                    $temp_mov2 = $qipan[$i + $mov2_num][$j + $mov2_num];
                }
                if ($temp_mov2 == $temp_type) {
                    $count++;
                    $mov2_num++;
                } else {
                    $mov2_num = 0;
                }
            } else {
                $mov2_num = 0;
            }
            if ($count >= 5) {
                return $count;
            }
            if (($mov1_num == 0 && $mov2_num == 0)) {
                break;
            }

        }
    }
    return $count;
}

// 建立一個文本協議的Worker監聽2347接口
$text_worker = new Worker("websocket://0.0.0.0:2347");

// 只啓動1個進程
$text_worker->count = 1;
$text_worker->uidConnections = array();
$text_worker->user_data = array();
$text_worker->onConnect = 'handle_connection';
$text_worker->onMessage = 'handle_message';
$text_worker->onClose = 'handle_close';

Worker::runAll();

3、編寫web端客戶端代碼,這裏報存爲client.phpcss

 

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script type="text/javascript" src="./js/jquery.min.js"></script>
</head>
<body>
<h3 class="player">玩家</h3>
<table border="1">
    <?php
    for ($i = 0;$i <= 15; $i++) {
    ?>
    <tr>
        <?php
        for ($j = 0; $j <= 15; $j++) {
            ?>
            <td style="width: 40px;height: 40px;position: relative;" id="<?php echo $i;?>_<?php echo $j;?>"
                onclick="press_on(this)">
                <div style="background:#000000;width: 20px;height: 20px;position: absolute;border-radius: 50%;display: none;left: 10px;bottom: 10px"
                    id="div_<?php echo $i;?>_<?php echo $j;?>"></div>
            </td>
        <?php
        }
        }
        ?>

</table>

<script>
    ws = new WebSocket("ws://127.0.0.1:2347");
    ws.onopen = function () {
        // alert("鏈接成功");
        //ws.send('tom');
        //alert("給服務端發送一個字符串:tom");
    };
    ws.onmessage = function (e) {
        //alert("收到服務端的消息:" + e.data);
        var jsonobj = eval('(' + e.data + ')');
        if (jsonobj.status == 1 && jsonobj.data.name != null) {//初始化名字
            alert(jsonobj.data.name);
            $('.player').html(jsonobj.data.name);
        }

        if (jsonobj.status == 2) {//
            var type = jsonobj.data.type;
            var press_i = jsonobj.data.press_i;
            var press_j = jsonobj.data.press_j;
            id = '#div_' + press_i + '_' + press_j;
            $(id).css('display', 'block');
            if (type == 1) {
                $(id).css('background', '#000000');
            }
            if (type == 2) {
                $(id).css('background', '#ffbc00');
            }
        }

        if (jsonobj.status == 3) {//
            var msg = jsonobj.msg;
            var r = confirm(msg + ',play again?');
            if (r) {
                window.location.reload(true);
                return;
            } else {
                return;
            }
        }
    };
    function press_on(value) {
        var send = '{"status":2,"data":"' + value.id + '"}';
        ws.send(send);
    }
</script>

</body>
</html>

四,最後在瀏覽器地址訪問client.php,進入遊戲。html

服務器截圖:java

相關文章
相關標籤/搜索