Guess::tries()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
nc 1
nop 0
dl 0
loc 3
c 1
b 0
f 0
cc 1
rs 10
1
<?php
2
namespace Bashar\Guess;
3
4
/**
5
 * Guess my number, a class supporting the game through GET, POST and SESSION.
6
 */
7
class Guess
8
{
9
    /**
10
     * @var int $number   The current secret number.
11
     * @var int $tries    Number of tries a guess has been made.
12
     */
13
    private $number;
14
    private $tries;
15
16
17
    /**
18
     * Constructor to initiate the object with current game settings,
19
     * if available. Randomize the current number if no value is sent in.
20
     *
21
     * @param int $number The current secret number, default -1 to initiate
22
     *                    the number from start.
23
     * @param int $tries  Number of tries a guess has been made,
24
     *                    default 6.
25
     */
26
    public function __construct(int $number = -1, int $tries = 6)
27
    {
28
        $this->tries = $tries;
29
        if ($number === -1) {
30
            $number = rand(1, 100);
31
        }
32
        $this->number = $number;
33
    }
34
35
36
37
    /**
38
     * Randomize the secret number between 1 and 100 to initiate a new game.
39
     *
40
     * @return void
41
     */
42
    public function random() : void
43
    {
44
        $number = rand(1, 100);
45
        $this->number = $number;
46
    }
47
48
49
50
    /**
51
     * Get number of tries left.
52
     *
53
     * @return int as number of tries made.
54
     */
55
    public function tries() : int
56
    {
57
        return $this->tries;
58
    }
59
60
61
62
63
    /**
64
     * Get the secret number.
65
     *
66
     * @return int as the secret number.
67
     */
68
    public function number() : int
69
    {
70
        return $this->number;
71
    }
72
73
74
75
76
    /**
77
     * Make a guess, decrease remaining guesses and return a string stating
78
     * if the guess was correct, too low or to high or if no guesses remains.
79
     *
80
     * @throws GuessException when guessed number is out of bounds.
81
     *
82
     * @return string to show the status of the guess made.
83
     */
84
    public function makeGuess(int $guess) : string
85
    {
86
        if ($guess < 1 || $guess > 100) {
87
            throw new GuessException("The given number is out of range.");
88
        }
89
        $this->tries--;
90
        if ($this->tries < 0) {
91
            $this->tries=0;
92
        }
93
94
        if ($guess === $this->number) {
95
            $res = "CORRECT";
96
        } elseif ($guess > $this->number) {
97
            $res = "TOO HIGH";
98
        } else {
99
            $res = "TOO LOW";
100
        }
101
        return $res;
102
    }
103
}
104