Last active
September 27, 2017 07:22
-
-
Save mmenavas/ff137a98e07fee017dd14afdad28074a to your computer and use it in GitHub Desktop.
PHP class that allows you to draw a rectangle on the command line.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class rectangle { | |
public function __construct($size, $width = 0, $height = 0) { | |
$sizes = $this->getSizes(); | |
if (isset($sizes[$size])) { | |
$this->width = $sizes[$size]['width']; | |
$this->height = $sizes[$size]['height']; | |
} | |
else { | |
// Assume custom size | |
$this->width = $width; | |
$this->height = $height; | |
} | |
} | |
private function getSizes() { | |
$sizes = [ | |
'small' => [ | |
'width' => 2, | |
'height' => 1, | |
], | |
'medium' => [ | |
'width' => 4, | |
'height' => 2, | |
], | |
'large' => [ | |
'width' => 10, | |
'height' => 3, | |
], | |
'x-large' => [ | |
'width' => 20, | |
'height' => 4, | |
] | |
]; | |
return $sizes; | |
} | |
public function drawRectangle() { | |
$width = $this->width; | |
$height = $this->height; | |
$rectangle = ""; | |
if ($width <= 0 && $height <= 0) { | |
return $rectangle; | |
} | |
// Top row | |
$rectangle = $this->drawRow($width, true) . "\n"; | |
// Filling | |
while ($height > 0) { | |
$rectangle .= $this->drawRow($width) . "\n"; | |
$height--; | |
} | |
// Bottom row | |
$rectangle .= $this->drawRow($width, true) . "\n"; | |
return $rectangle; | |
} | |
private function drawRow($width, $isSide = false) { | |
// First column | |
$row = $isSide ? "." : "|"; | |
// Filling | |
while ($width > 0) { | |
$row .= $isSide ? "-" : " "; | |
$width--; | |
} | |
// Last column | |
$row .= $isSide ? "." : "|"; | |
return $row; | |
} | |
} | |
$rect = new Rectangle('small'); | |
print $rect->drawRectangle(); | |
$rect = new Rectangle('medium'); | |
print $rect->drawRectangle(); | |
$rect = new Rectangle('large'); | |
print $rect->drawRectangle(); | |
$rect = new Rectangle('x-large'); | |
print $rect->drawRectangle(); | |
$rect = new Rectangle('custom', 40, 6); | |
print $rect->drawRectangle(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment