PocketMine-MP 5.15.1 git-be6754494fdbbb9dd57c058ba0e33a4a78c4581f
CraftingGrid.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\crafting;
25
28use function max;
29use function min;
30use const PHP_INT_MAX;
31
32abstract class CraftingGrid extends SimpleInventory{
33 public const SIZE_SMALL = 2;
34 public const SIZE_BIG = 3;
35
36 private ?int $startX = null;
37 private ?int $xLen = null;
38 private ?int $startY = null;
39 private ?int $yLen = null;
40
41 public function __construct(
42 private int $gridWidth
43 ){
44 parent::__construct($this->getGridWidth() ** 2);
45 }
46
47 public function getGridWidth() : int{
48 return $this->gridWidth;
49 }
50
51 public function setItem(int $index, Item $item) : void{
52 parent::setItem($index, $item);
53 $this->seekRecipeBounds();
54 }
55
56 private function seekRecipeBounds() : void{
57 $minX = PHP_INT_MAX;
58 $maxX = 0;
59
60 $minY = PHP_INT_MAX;
61 $maxY = 0;
62
63 $empty = true;
64
65 for($y = 0; $y < $this->gridWidth; ++$y){
66 for($x = 0; $x < $this->gridWidth; ++$x){
67 if(!$this->isSlotEmpty($y * $this->gridWidth + $x)){
68 $minX = min($minX, $x);
69 $maxX = max($maxX, $x);
70
71 $minY = min($minY, $y);
72 $maxY = max($maxY, $y);
73
74 $empty = false;
75 }
76 }
77 }
78
79 if(!$empty){
80 $this->startX = $minX;
81 $this->xLen = $maxX - $minX + 1;
82 $this->startY = $minY;
83 $this->yLen = $maxY - $minY + 1;
84 }else{
85 $this->startX = $this->xLen = $this->startY = $this->yLen = null;
86 }
87 }
88
92 public function getIngredient(int $x, int $y) : Item{
93 if($this->startX !== null && $this->startY !== null){
94 return $this->getItem(($y + $this->startY) * $this->gridWidth + ($x + $this->startX));
95 }
96
97 throw new \LogicException("No ingredients found in grid");
98 }
99
103 public function getRecipeWidth() : int{
104 return $this->xLen ?? 0;
105 }
106
110 public function getRecipeHeight() : int{
111 return $this->yLen ?? 0;
112 }
113}
setItem(int $index, Item $item)