Форум программистов, компьютерный форум, киберфорум
PHP для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.67/6: Рейтинг темы: голосов - 6, средняя оценка - 4.67
0 / 0 / 0
Регистрация: 12.01.2014
Сообщений: 10

Неожиданный конец

12.01.2014, 22:52. Показов 1205. Ответов 6
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Помогите с кодом, в конце выдает вот такую ошибку:
PHP
1
Parse error: syntax error, unexpected end of file in C:\Users\UserHP\Desktop\▒▒▒▒▒▒▒\PocketMine-MP\plugins\PocketGuard (4).php on line 315
сам код:
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
<?php
 
/*
 __PocketMine Plugin__
name=PocketGuard
description=PocketGuard guards your chest against thieves.
version=1.1.2
author=MinecrafterJPN
class=PocketGuard
apiversion=10
*/
 
class PocketGuard implements Plugin
{
    private $api, $db, $queue = array();
 
    const NOT_LOCKED = -1;
    const NORMAL_LOCK = 0;
    const PASSCODE_LOCK = 1;
    const PUBLIC_LOCK = 2;
 
    public function __construct(ServerAPI $api, $server = false)
    {
        $this->api = $api;
    }
 
    public function init()
    {
        $this->loadDB();
        $this->api->addHandler("player.block.touch", array($this, "eventHandler"));
        $this->api->console->register("pg", "Main command of PocketGuard", array($this, "commandHandler"));
        $this->api->ban->cmdWhitelist("pg");
    }
 
    public function eventHandler($data, $event)
    {       
        $username = $data['player']->username;
        if ($data['type'] === "place" and $data['item']->getID() === CHEST) {
            $c = $this->getSideChest($data['block']->x, $data['block']->y, $data['block']->z);
            if ($c !== false) {
                $cInfo = $this->getChestInfo($c->x, $c->y, $c->z);
                $isLocked = $cInfo === self::NOT_LOCKED ? false : true;
                if ($isLocked) {
                    $this->api->chat->sendTo(false, "[PocketGuard] Cannot place chest next to locked chest", $username);
                    return false;
                }
            } 
        }
        if ($data['target']->getID() === CHEST) {
            $chestInfo = $this->getChestInfo($data['target']->x, $data['target']->y, $data['target']->z);
            $owner = $chestInfo === self::NOT_LOCKED ? $chestInfo : $chestInfo['owner'];
            $attribute = $chestInfo === self::NOT_LOCKED ? $chestInfo : $chestInfo['attribute'];
            $pairChest = $this->api->tile->get(new Position($data['target']->x, $data['target']->y, $data['target']->z, $this->api->level->getDefault()));
            if ($pairChest instanceof Tile) {
                $pairChest = $pairChest->isPaired() ? $pairChest->getPair() : false;
            } else {
                $pairChest = false;
            }           
            if (isset($this->queue[$username])) {
                $task = $this->queue[$username];
                switch ($task[0]) {
                    case "lock":
                        if ($attribute === self::NOT_LOCKED) {
                            $this->lock($username, $data['target']->x, $data['target']->y, $data['target']->z, self::NORMAL_LOCK);
                            if ($pairChest !== false) $this->lock($username, $pairChest->x, $pairChest->y, $pairChest->z, self::NORMAL_LOCK);
                        } else {
                            $this->api->chat->sendTo(false, "[PocketGuard] The chest has already been guarded by other player.", $username);
                        }
                        break;
                    case "unlock":
                        if ($owner === $username and $attribute === self::NORMAL_LOCK) {
                            $this->unlock($data['target']->x, $data['target']->y, $data['target']->z, $username);
                            if ($pairChest !== false) $this->unlock($pairChest->x, $pairChest->y, $pairChest->z, $username);
                        } elseif ($attribute === self::NOT_LOCKED) {
                            $this->api->chat->sendTo(false, "[PocketGuard] The chest is not guarded.", $username);
                        } else {
                            $this->api->chat->sendTo(false, "[PocketGuard] The chest has been guarded by other player or by other method.", $username);
                        }
                        break;
                    case "public":
                        if ($attribute === self::NOT_LOCKED) {
                            $this->lock($username, $data['target']->x, $data['target']->y, $data['target']->z, self::PUBLIC_LOCK);
                            if ($pairChest !== false) $this->lock($username, $pairChest->x, $pairChest->y, $pairChest->z, self::PUBLIC_LOCK);
                        } else {
                            $this->api->chat->sendTo(false, "[PocketGuard] That chest has already been guarded by other player.", $username);
                        }
                        break;
                    case "info":
                        if ($attribute !== self::NOT_LOCKED) {
                            $this->info($data['target']->x, $data['target']->y, $data['target']->z, $username);
                        } else {
                            $this->api->chat->sendTo(false, "[PocketGuard] The chest is not guarded.", $username);
                        }
                        break;
                    case "passlock":
                        if ($attribute === self::NOT_LOCKED) {
                            $this->lock($username, $data['target']->x, $data['target']->y, $data['target']->z, self::PASSCODE_LOCK, $task[1]);
                            if ($pairChest !== false) $this->lock($username, $pairChest->x, $pairChest->y, $pairChest->z, self::NORMAL_LOCK, $task[1]);
                        } else {
                            $this->api->chat->sendTo(false, "[PocketGuard] The chest has already been guarded by other player.", $username);
                        }
                        break;
                    case "passunlock":
                        if ($attribute === self::PASSCODE_LOCK) {
                            if ($this->checkPasscode($data['target']->x, $data['target']->y, $data['target']->z, $task[1])) {
                                $this->unlock($data['target']->x, $data['target']->y, $data['target']->z, $username);
                                if ($pairChest !== false) $this->unlock($pairChest->x, $pairChest->y, $pairChest->z, $username);
                            } else {
                                $this->api->chat->sendTo(false, "[PocketGuard] Failed to unlock due to wrong passcode.", $username);
                            }
                        } else {
                            $this->api->chat->sendTo(false, "[PocketGuard] That chest is not guarded by passcode.", $username);
                        }
                        break;
                    case "share":
                        break;
                }
                unset($this->queue[$username]);
                return false;
            } elseif ($owner !== $username and $attribute !== self::PUBLIC_LOCK and $attribute !== self::NOT_LOCKED) {
                $this->api->chat->sendTo(false, "[PocketGuard] That chest has been guarded.", $username);
                $this->api->chat->sendTo(false, "[PocketGuard] If you want to know the detail, use /pg info", $username);
                return false;
            } else {
                if ($owner === $username and $data['type'] === 'break' and $attribute !== self::NOT_LOCKED) {
                    $this->unlock($data['target']->x, $data['target']->y, $data['target']->z, $username);
                    if ($pairChest !== false) $this->unlock($pairChest->x, $pairChest->y, $pairChest->z, $username);
                } elseif ($owner !== $username and $data['type'] === 'break' and $attribute === self::PUBLIC_LOCK) {
                    $this->api->chat->sendTo(false, "[PocketGuard] The player who is not owner cannot break public chest.", $username);
                    return false;
                }
            }
        }
    }
 
    public function CommandHandler($cmd, $args, $issuer, $alias)
    {
        $subCmd = $args[0];
        $output = "";
        if ($issuer === 'console') {
            $output .= "[PocketGuard] Must be run on the world.";
        } elseif(isset($this->queue[$issuer->username])) {
            $output .= "[PocketGuards] You still have the task to do!";
        } else {
            switch ($subCmd) {
                case "lock":
                case "unlock":
                case "public":
                case "info":
                    $this->queue[$issuer->username] = array($subCmd);
                    break;
                case "passlock":
                case "passunlock":
                    $passcode = $args[1];
                    $this->queue[$issuer->username] = array($subCmd, $passcode);
                    break;
                case "share":
                    $target = $args[1];
                    $this->queue[$issuer->username] = array($subCmd, $target);
                    break;
                default:
                    $output .= "[PocketGuards] Such command dose not exist!";
                    return $output;
            }
            $output .= "[PocketGuards][CMD:" . $subCmd . "] Touch the target chest!";
        }
        return $output;
    }
private function loadDB()
        {
        $this->db = new SQLite3($this->api->plugin->configPath($this) . "PocketGuard.sqlite3");
       $stmt = $this->db->prepare('
                CREATE TABLE IF NOT EXISTS chests("
                ("id INTEGER PRIMARY KEY AUTOINCREMENT,
                owner TEXT NOT NULL,
                x INTEGER NOT NULL,
                y INTEGER NOT NULL,
                z INTEGER NOT NULL,
                attribute INTEGER NOT NULL,
                passcode TEXT")');
        ")) ;
        $stmt->execute();
        $stmt->close();
    }
 
    private function getSideChest($x, $y, $z)
    {
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x + 1, $y, $z));
        if ($item->getID() === CHEST) return $item;
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x - 1, $y, $z));
        if ($item->getID() === CHEST) return $item;
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x, $y, $z + 1));
        if ($item->getID() === CHEST) return $item;
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x, $y, $z - 1));
        if ($item->getID() === CHEST) return $item;
        return false;
    }
 
    private function getChestInfo($x, $y, $z)
    {
        $stmt = $this->db->prepare('SELECT * FROM chests WHERE x = :x AND y = :y AND z = :z');
        $stmt->bindValue(:x, $x);
        $stmt->bindValue(:y, $y);
        $stmt->bindValue(:z, $z);
        $result = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        $stmt->close();
        if ($result === false) {
            return self::NOT_LOCKED;
        } else {
            return $result;
        }
    }
 
    private function getAttribute($x, $y, $z)
    {
        $stmt = $this->db->prepare('SELECT attribute FROM chests WHERE x = :x AND y = :y AND z = :z');
        $stmt->bindValue(:x, $x);
        $stmt->bindValue(:y, $y);
        $stmt->bindValue(:z, $z);
        $result = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        $stmt->close();
        if ($result === false) {
            $ret = self::NOT_LOCKED;
        } else {
            $ret = $result[attribute];
        }
        return $ret;
    }
 
    private function getOwner($x, $y, $z)
    {
        $stmt = $this->db->prepare('SELECT owner FROM chests WHERE x = :x AND y = :y AND z = :z');
        $stmt->bindValue(:x, $x);
        $stmt->bindValue(:y, $y);
        $stmt->bindValue(:z, $z);
        $result = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        $stmt->close();
        if ($result === false) {
            $ret = self::NOT_LOCKED;
        } else {
            $ret = $result[owner];
        }
        return $ret;
    }
 
    private function lock($owner, $x, $y, $z, $attribute, $passcode = null)
    {
        $stmt = $this->db->prepare('INSERT INTO chests (owner, x, y, z, attribute, passcode) VALUES (:owner, :x, :y, :z, :attribute, :passcode)');
        $stmt->bindValue(:owner, $owner);
        $stmt->bindValue(:x, $x);
        $stmt->bindValue(:y, $y);
        $stmt->bindValue(:z, $z);
        $stmt->bindValue(:attribute, $attribute);
        $stmt->bindValue(:passcode, $passcode);
        $stmt->execute();
        $stmt->close();
        if ($attribute === self::PASSCODE_LOCK) {
            $this->api->chat->sendTo(false, '[PocketGuard] Completed to lock. Passcode:$passcode', $owner);
        } else {
            $this->api->chat->sendTo(false, '[PocketGuard] Completed to lock.', $owner);
        }
    }
 
    private function unlock($x, $y, $z, $username)
    {
        $stmt = $this->db->prepare('DELETE FROM chests WHERE x = :x AND y = :y AND z = :z');
        $stmt->bindValue(:x, $x);
        $stmt->bindValue(:y, $y);
        $stmt->bindValue(:z, $z);
        $stmt->execute();
        $this->api->chat->sendTo(false, '[PocketGuard] Completed to unlock.', $username);
        $stmt->close();
    }
 
    private function checkPasscode($x, $y, $z, $passcode)
    {
        $stmt = $this->db->prepare('SELECT * FROM chests WHERE x = :x AND y = :y AND z = :z AND passcode = :passcode');
        $stmt->bindValue(:x, $x);
        $stmt->bindValue(:y, $y);
        $stmt->bindValue(:z, $z);
        $stmt->bindValue(:passcode, $passcode);
        $result = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        return $result === false ? false : true;
    }
 
    private function info($x, $y, $z, $username)
    {
        $stmt = $this->db->prepare('SELECT owner, attribute FROM chests WHERE x = :x AND y = :y AND z = :z');
        $stmt->bindValue(:x, $x);
        $stmt->bindValue(:y, $y);
        $stmt->bindValue(:z, $z);
        $result = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        $stmt->close();
        $owner = $result[owner];
        $attribute = $result[attribute];
        switch ($attribute) {
            case self::NORMAL_LOCK:
                $lockType = 'Normal';
                break;
            case self::PASSCODE_LOCK:
                $lockType = 'Passcode';
                break;
            case self::PUBLIC_LOCK:
                $lockType = 'Public';
                break;
        }
        $this->api->chat->sendTo(false, '[PocketGuard] Owner:$owner LockType:$lockType', $username);
    }
 
    public function __destruct();
    {
        $this->db->close();
    }
}
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
12.01.2014, 22:52
Ответы с готовыми решениями:

неожиданный конец файла
Здравствуйте. Есть код, на который система выдает ошибку неожиданного конца файла в 85 строке. Как исправить? &lt;?php // подключаем...

Синтаксическая ошибка: неожиданный '['
добрый день возникла вот такая головоломка. function xpnd($str){ //converts scientific notation to number, if there is scientific...

Неожиданный конец файла
Не выводятся данные, хотя на другом сервере выводились... выводит и указывает на последнюю строку &lt;?php $sql =...

6
27 / 27 / 10
Регистрация: 26.01.2013
Сообщений: 231
12.01.2014, 23:34
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private function loadDB()
        {
        $this->db = new SQLite3($this->api->plugin->configPath($this) . "PocketGuard.sqlite3");
       $stmt = $this->db->prepare('
                CREATE TABLE IF NOT EXISTS chests("
                ("id INTEGER PRIMARY KEY AUTOINCREMENT,
                owner TEXT NOT NULL,
                x INTEGER NOT NULL,
                y INTEGER NOT NULL,
                z INTEGER NOT NULL,
                attribute INTEGER NOT NULL,
                passcode TEXT")');
        // ")) ; 
        $stmt->execute();
        $stmt->close();
    }
комментируй или удали строку которую я пометил. И должно придти счастье.
0
0 / 0 / 0
Регистрация: 12.01.2014
Сообщений: 10
12.01.2014, 23:47  [ТС]
Цитата Сообщение от anonymous_23 Посмотреть сообщение
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private function loadDB()
        {
        $this->db = new SQLite3($this->api->plugin->configPath($this) . "PocketGuard.sqlite3");
       $stmt = $this->db->prepare('
                CREATE TABLE IF NOT EXISTS chests("
                ("id INTEGER PRIMARY KEY AUTOINCREMENT,
                owner TEXT NOT NULL,
                x INTEGER NOT NULL,
                y INTEGER NOT NULL,
                z INTEGER NOT NULL,
                attribute INTEGER NOT NULL,
                passcode TEXT")');
        // ")) ; 
        $stmt->execute();
        $stmt->close();
    }
комментируй или удали строку которую я пометил. И должно придти счастье.
удалял не робит
0
0 / 0 / 0
Регистрация: 12.01.2014
Сообщений: 10
12.01.2014, 23:53  [ТС]
Цитата Сообщение от anonymous_23 Посмотреть сообщение
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private function loadDB()
        {
        $this->db = new SQLite3($this->api->plugin->configPath($this) . "PocketGuard.sqlite3");
       $stmt = $this->db->prepare('
                CREATE TABLE IF NOT EXISTS chests("
                ("id INTEGER PRIMARY KEY AUTOINCREMENT,
                owner TEXT NOT NULL,
                x INTEGER NOT NULL,
                y INTEGER NOT NULL,
                z INTEGER NOT NULL,
                attribute INTEGER NOT NULL,
                passcode TEXT")');
        // ")) ; 
        $stmt->execute();
        $stmt->close();
    }
комментируй или удали строку которую я пометил. И должно придти счастье.
а вот теперь вот такая ошибка :
PHP
1
Parse error: syntax error, unexpected 'private' (T_PRIVATE) in C:\Users\UserHP\Desktop\▒▒▒▒▒▒▒\PocketMine-MP\plugins\PocketGuard (4).php on line 187
часть кода:
PHP
1
2
3
4
5
6
7
8
9
10
11
12
    private function getSideChest($x, $y, $z);
    {
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x + 1, $y, $z));
        if ($item->getID() === CHEST) return $item;
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x - 1, $y, $z));
        if ($item->getID() === CHEST) return $item;
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x, $y, $z + 1));
        if ($item->getID() === CHEST) return $item;
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x, $y, $z - 1));
        if ($item->getID() === CHEST) return $item;
        return false;
    }
Помогите короче))
0
27 / 27 / 10
Регистрация: 26.01.2013
Сообщений: 231
12.01.2014, 23:55
Ну так ещё глянь как идёт вызов строкового ключа массива
PHP
1
$owner = $result[owner];
И так везде.
А ведь нужны кавычки
PHP
1
$owner = $result['owner'];
Это чисто проверка на синтаксис.
0
0 / 0 / 0
Регистрация: 12.01.2014
Сообщений: 10
13.01.2014, 00:08  [ТС]
Цитата Сообщение от anonymous_23 Посмотреть сообщение
Ну так ещё глянь как идёт вызов строкового ключа массива
PHP
1
$owner = $result[owner];
И так везде.
А ведь нужны кавычки
PHP
1
$owner = $result['owner'];
Это чисто проверка на синтаксис.
Там были кавычки, из за них сервер давал сбой я их убрал, а вот с этим хз что делать

Добавлено через 2 минуты
anonymous_23, так помоги вот с этим
ошибка:
PHP
1
Parse error: syntax error, unexpected 'private' (T_PRIVATE) in C:\Users\UserHP\Desktop\▒▒▒▒▒▒▒\PocketMine-MP\plugins\PocketGuard (4).php on line 187
часть кода:
PHP
1
2
3
4
5
6
7
8
9
10
11
12
private function getSideChest($x, $y, $z);
    {
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x + 1, $y, $z));
        if ($item->getID() === CHEST) return $item;
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x - 1, $y, $z));
        if ($item->getID() === CHEST) return $item;
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x, $y, $z + 1));
        if ($item->getID() === CHEST) return $item;
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x, $y, $z - 1));
        if ($item->getID() === CHEST) return $item;
        return false;
    }
буду очень благодарен)
0
27 / 27 / 10
Регистрация: 26.01.2013
Сообщений: 231
13.01.2014, 00:27
В общем Ошибки исправил, остались только скобки проверить, где то не доставлены (эт уже сам спокойно прогляди).
PHP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
class PocketGuard implements Plugin
{
    private $api, $db, $queue = array();
 
    const NOT_LOCKED = -1;
    const NORMAL_LOCK = 0;
    const PASSCODE_LOCK = 1;
    const PUBLIC_LOCK = 2;
 
    public function __construct(ServerAPI $api, $server = false)
    {
        $this->api = $api;
    }
 
    public function init()
    {
        $this->loadDB();
        $this->api->addHandler("player.block.touch", array($this, "eventHandler"));
        $this->api->console->register("pg", "Main command of PocketGuard", array($this, "commandHandler"));
        $this->api->ban->cmdWhitelist("pg");
    }
 
    public function eventHandler($data, $event)
    {       
        $username = $data['player']->username;
        if ($data['type'] === "place" and $data['item']->getID() === CHEST) {
            $c = $this->getSideChest($data['block']->x, $data['block']->y, $data['block']->z);
            if ($c !== false) {
                $cInfo = $this->getChestInfo($c->x, $c->y, $c->z);
                $isLocked = $cInfo === self::NOT_LOCKED ? false : true;
                if ($isLocked) {
                    $this->api->chat->sendTo(false, "[PocketGuard] Cannot place chest next to locked chest", $username);
                    return false;
                }
      } 
    }
        if ($data['target']->getID() === CHEST) {
            $chestInfo = $this->getChestInfo($data['target']->x, $data['target']->y, $data['target']->z);
            $owner = $chestInfo === self::NOT_LOCKED ? $chestInfo : $chestInfo['owner'];
            $attribute = $chestInfo === self::NOT_LOCKED ? $chestInfo : $chestInfo['attribute'];
            $pairChest = $this->api->tile->get(new Position($data['target']->x, $data['target']->y, $data['target']->z, $this->api->level->getDefault()));
            if ($pairChest instanceof Tile) {
                $pairChest = $pairChest->isPaired() ? $pairChest->getPair() : false;
            } else {
                $pairChest = false;
            }           
            if (isset($this->queue[$username])) {
                $task = $this->queue[$username];
                switch ($task[0]) {
                    case "lock":
                        if ($attribute === self::NOT_LOCKED) {
                            $this->lock($username, $data['target']->x, $data['target']->y, $data['target']->z, self::NORMAL_LOCK);
                            if ($pairChest !== false) $this->lock($username, $pairChest->x, $pairChest->y, $pairChest->z, self::NORMAL_LOCK);
                        } else {
                            $this->api->chat->sendTo(false, "[PocketGuard] The chest has already been guarded by other player.", $username);
                        }
                        break;
                    case "unlock":
                        if ($owner === $username and $attribute === self::NORMAL_LOCK) {
                            $this->unlock($data['target']->x, $data['target']->y, $data['target']->z, $username);
                            if ($pairChest !== false) $this->unlock($pairChest->x, $pairChest->y, $pairChest->z, $username);
                        } elseif ($attribute === self::NOT_LOCKED) {
                            $this->api->chat->sendTo(false, "[PocketGuard] The chest is not guarded.", $username);
                        } else {
                            $this->api->chat->sendTo(false, "[PocketGuard] The chest has been guarded by other player or by other method.", $username);
                        }
                        break;
                    case "public":
                        if ($attribute === self::NOT_LOCKED) {
                            $this->lock($username, $data['target']->x, $data['target']->y, $data['target']->z, self::PUBLIC_LOCK);
                            if ($pairChest !== false) $this->lock($username, $pairChest->x, $pairChest->y, $pairChest->z, self::PUBLIC_LOCK);
                        } else {
                            $this->api->chat->sendTo(false, "[PocketGuard] That chest has already been guarded by other player.", $username);
                        }
                        break;
                    case "info":
                        if ($attribute !== self::NOT_LOCKED) {
                            $this->info($data['target']->x, $data['target']->y, $data['target']->z, $username);
                        } else {
                            $this->api->chat->sendTo(false, "[PocketGuard] The chest is not guarded.", $username);
                        }
                        break;
                    case "passlock":
                        if ($attribute === self::NOT_LOCKED) {
                            $this->lock($username, $data['target']->x, $data['target']->y, $data['target']->z, self::PASSCODE_LOCK, $task[1]);
                            if ($pairChest !== false) $this->lock($username, $pairChest->x, $pairChest->y, $pairChest->z, self::NORMAL_LOCK, $task[1]);
                        } else {
                            $this->api->chat->sendTo(false, "[PocketGuard] The chest has already been guarded by other player.", $username);
                        }
                        break;
                    case "passunlock":
                        if ($attribute === self::PASSCODE_LOCK) {
                            if ($this->checkPasscode($data['target']->x, $data['target']->y, $data['target']->z, $task[1])) {
                                $this->unlock($data['target']->x, $data['target']->y, $data['target']->z, $username);
                                if ($pairChest !== false) $this->unlock($pairChest->x, $pairChest->y, $pairChest->z, $username);
                            } else {
                                $this->api->chat->sendTo(false, "[PocketGuard] Failed to unlock due to wrong passcode.", $username);
                            }
                        } else {
                            $this->api->chat->sendTo(false, "[PocketGuard] That chest is not guarded by passcode.", $username);
                        }
                        break;
                    case "share":
                        break;
                }
                unset($this->queue[$username]);
                return false;
            } elseif ($owner !== $username and $attribute !== self::PUBLIC_LOCK and $attribute !== self::NOT_LOCKED) {
                $this->api->chat->sendTo(false, "[PocketGuard] That chest has been guarded.", $username);
                $this->api->chat->sendTo(false, "[PocketGuard] If you want to know the detail, use /pg info", $username);
                return false;
            } else {
                if ($owner === $username and $data['type'] === 'break' and $attribute !== self::NOT_LOCKED) {
                    $this->unlock($data['target']->x, $data['target']->y, $data['target']->z, $username);
                    if ($pairChest !== false) $this->unlock($pairChest->x, $pairChest->y, $pairChest->z, $username);
                } elseif ($owner !== $username and $data['type'] === 'break' and $attribute === self::PUBLIC_LOCK) {
                    $this->api->chat->sendTo(false, "[PocketGuard] The player who is not owner cannot break public chest.", $username);
                    return false;
                }
            }
        }
    }
 
    public function CommandHandler($cmd, $args, $issuer, $alias)
    {
        $subCmd = $args[0];
        $output = "";
        if ($issuer === 'console') {
            $output .= "[PocketGuard] Must be run on the world.";
        } elseif(isset($this->queue[$issuer->username])) {
            $output .= "[PocketGuards] You still have the task to do!";
        } else {
            switch ($subCmd) {
                case "lock":
                case "unlock":
                case "public":
                case "info":
                    $this->queue[$issuer->username] = array($subCmd);
                    break;
                case "passlock":
                case "passunlock":
                    $passcode = $args[1];
                    $this->queue[$issuer->username] = array($subCmd, $passcode);
                    break;
                case "share":
                    $target = $args[1];
                    $this->queue[$issuer->username] = array($subCmd, $target);
                    break;
                default:
                    $output .= "[PocketGuards] Such command dose not exist!";
                    return $output;
            }
            $output .= "[PocketGuards][CMD:" . $subCmd . "] Touch the target chest!";
        }
        return $output;
    }
    private function loadDB()
        {
        $this->db = new SQLite3($this->api->plugin->configPath($this) . "PocketGuard.sqlite3");
       $stmt = $this->db->prepare('
                CREATE TABLE IF NOT EXISTS chests("
                ("id INTEGER PRIMARY KEY AUTOINCREMENT,
                owner TEXT NOT NULL,
                x INTEGER NOT NULL,
                y INTEGER NOT NULL,
                z INTEGER NOT NULL,
                attribute INTEGER NOT NULL,
                passcode TEXT")');
        // ")) ;
        $stmt->execute();
        $stmt->close();
    }
 
    private function getSideChest($x, $y, $z)
    {
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x + 1, $y, $z));
        if ($item->getID() === CHEST) return $item;
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x - 1, $y, $z));
        if ($item->getID() === CHEST) return $item;
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x, $y, $z + 1));
        if ($item->getID() === CHEST) return $item;
        $item = $this->api->level->getDefault()->getBlock(new Vector3($x, $y, $z - 1));
        if ($item->getID() === CHEST) return $item;
        return false;
    }
 
    private function getChestInfo($x, $y, $z)
    {
        $stmt = $this->db->prepare("SELECT * FROM chests WHERE x = ':x' AND y = ':y' AND z = ':z'");
        $stmt->bindValue(':x', $x);
        $stmt->bindValue(':y', $y);
        $stmt->bindValue(':z', $z);
        $result = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        $stmt->close();
        if ($result === false) {
            return self::NOT_LOCKED;
        } else {
            return $result;
        }
    }
 
    private function getAttribute($x, $y, $z)
    {
        $stmt = $this->db->prepare("SELECT attribute FROM chests WHERE x = ':x' AND y = ':y' AND z = ':z'");
        $stmt->bindValue(':x', $x);
        $stmt->bindValue(':y', $y);
        $stmt->bindValue(':z', $z);
        $result = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        $stmt->close();
        if ($result === false) {
            $ret = self::NOT_LOCKED;
        } else {
            $ret = $result[attribute];
        }
        return $ret;
    }
 
    private function getOwner($x, $y, $z)
    {
        $stmt = $this->db->prepare("SELECT owner FROM chests WHERE x = ':x' AND y = ':y' AND z = ':z'");
        $stmt->bindValue(':x', $x);
        $stmt->bindValue(':y', $y);
        $stmt->bindValue(':z', $z);
        $result = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        $stmt->close();
        if ($result === false) {
            $ret = self::NOT_LOCKED;
        } else {
            $ret = $result[owner];
        }
        return $ret;
    }
 
    private function lock($owner, $x, $y, $z, $attribute, $passcode = null)
    {
        $stmt = $this->db->prepare("INSERT INTO chests (owner, x, y, z, attribute, passcode) VALUES (:owner, ':x', ':y', ':z', :attribute, :passcode)");
        $stmt->bindValue(':owner', $owner);
        $stmt->bindValue(':x', $x);
        $stmt->bindValue(':y', $y);
        $stmt->bindValue(':z', $z);
        $stmt->bindValue(':attribute', $attribute);
        $stmt->bindValue(':passcode', $passcode);
        $stmt->execute();
        $stmt->close();
        if ($attribute === self::PASSCODE_LOCK) {
            $this->api->chat->sendTo(false, '[PocketGuard] Completed to lock. Passcode:$passcode', $owner);
        } else {
            $this->api->chat->sendTo(false, '[PocketGuard] Completed to lock.', $owner);
        }
    }
 
    private function unlock($x, $y, $z, $username)
    {
        $stmt = $this->db->prepare("DELETE FROM chests WHERE x = ':x' AND y = ':y' AND z = ':z'");
        $stmt->bindValue(':x', $x);
        $stmt->bindValue(':y', $y);
        $stmt->bindValue(':z', $z);
        $stmt->execute();
        $this->api->chat->sendTo(false, '[PocketGuard] Completed to unlock.', $username);
        $stmt->close();
    }
 
    private function checkPasscode($x, $y, $z, $passcode)
    {
        $stmt = $this->db->prepare("SELECT * FROM chests WHERE x = ':x' AND y = ':y' AND z = ':z' AND passcode = :passcode");
        $stmt->bindValue(':x', $x);
        $stmt->bindValue(':y', $y);
        $stmt->bindValue(':z', $z);
        $stmt->bindValue(':passcode', $passcode);
        $result = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        return $result === false ? false : true;
    }
 
    private function info($x, $y, $z, $username)
    {
        $stmt = $this->db->prepare("SELECT owner, attribute FROM chests WHERE x = ':x' AND y = ':y' AND z = ':z'");
        $stmt->bindValue(':x', $x);
        $stmt->bindValue(':y', $y);
        $stmt->bindValue(':z', $z);
        $result = $stmt->execute()->fetchArray(SQLITE3_ASSOC);
        $stmt->close();
        $owner = $result[owner];
        $attribute = $result[attribute];
        switch ($attribute) {
            case self::NORMAL_LOCK:
                $lockType = 'Normal';
                break;
            case self::PASSCODE_LOCK:
                $lockType = 'Passcode';
                break;
            case self::PUBLIC_LOCK:
                $lockType = 'Public';
                break;
        }
        $this->api->chat->sendTo(false, '[PocketGuard] Owner:$owner LockType:$lockType', $username);
    }
 
    public function __destruct()
    {
        $this->db->close();
    }
}
Разложи вложенность всю нормально. Если что то вложено в что то то tab отступи или 2 пробела, и сразу увидишь где чего не хватает.

Добавлено через 1 минуту
Цитата Сообщение от anonymous_23 Посмотреть сообщение
public function __construct(ServerAPI $api, $server = false)
* * {
* * * * $this->api = $api;
* * }
И код такого рода лучше писать
PHP
1
2
3
public function __construct(ServerAPI $api, $server = false){
  $this->api = $api;
}
А то скобки так и теряются что всё уж больно размашесто. Отступы и пробелы конечно хорошо но в разумных целях.
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
13.01.2014, 00:27
Помогаю со студенческими работами здесь

Неожиданный результат работы функции
Всем добрый день! Случилась очень странная ситуация: Есть функция в модели User public static function checkLogged() { ...

Неожиданный возврат из формы (совсем базовое)
Доброго! Есть два простых файла. index.php&lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset=&quot;UTF-8&quot;&gt; ...

Сравнение чисел с плавающей точкой выдают неожиданный результат
Я далеко не новичок в php, но куда еще можно было бы пихнуть данную тему я даже и не знаю. В процессе написания одной системы столкнулся...

Синтаксическая ошибка, неожиданный endif, хотя он должен быть ожиданный! СРОЧНО
Мне пишет неожиданный endif, хотя я вроде бы как написал всё верно, выручайте, еще, если я убираю 2 endif;, то мне пишет о неожиданном...

Неожиданный конец файла
Помогите найти ошибку. Вроде бы, всё правильно, но, тем не менее, получаю неожиданный конец фала с указанием на последнюю строчку. ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Новые блоги и статьи
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL3_image
8Observer8 10.02.2026
Содержание блога Библиотека SDL3_image содержит инструменты для расширенной работы с изображениями. Пошагово создадим проект для загрузки изображения формата PNG с альфа-каналом (с прозрачным. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru