C++ – Minesweeper

The other day I was tutoring a freshman programmer program his first minesweeper text game in C++. Here is the resulting code.

#include <iostream>
#include<cstdlib>
#include<ctime>
 
const int DIMX = 6;
const int DIMY = 6;
const int MINES = 6;
const int MINE = -1;
const char COVERED = 'X';
const char UNCOVERED = ' ';
const char FLAG = 'F';
int state[DIMX][DIMY];
char display[DIMX][DIMY];
 
void init(); // initialize game states
int countSorroundingMines(int x, int y); // helper function used by init
void reveal(int x, int y);
void player(); // handle player input
void setFlag();
void uncover();
void print(); // print the minefield
void cheat(); // print out the mines
bool isWin();
bool isLose();
bool playNewGame();
 
int main() {
    std::cout << "Welcome to MineSweeper!" << std::endl;
    init();
    bool playing = true;
    while(playing) {
        print();
        player();
        if(isWin()) {
            std::cout << "You Win!" << std::endl;
            playing = false;
        } else if(isLose()) {
            std::cout << "You Lose!" << std::endl;
            playing = false;
        }
 
        if(!playing) {
            playing = playNewGame();
            if(playing) {
                init();
            }
        }
    }
    std::cout << "Exiting Minesweeper!" << std::endl;
    return 0;
}
 
void init() {
    std::cout << "New Game!" << std::endl;
    // set display to "uncovered"
    for(int y = 0; y < DIMY; y++) {
        for(int x = 0; x < DIMX; x++) {
            display[x][y] = COVERED;
        }
    }
    // initialize mines
    srand(time(0));
    for(int i = 0; i < MINES; i++) {
        bool placed = false;
        while(!placed) {
            int x = rand() % DIMX;
            int y = rand() % DIMY;
            if(state[x][y] != MINE) { // check mine not set
                placed = true;
                state[x][y] = MINE;
            }
        }
    }
    // place hint numbers
    for(int y = 0; y < DIMY; y++) {
        for(int x = 0; x < DIMX; x++) {
            state[x][y] = countSorroundingMines(x, y);
        }
    }
}
 
bool playNewGame() {
    bool selected = false;
    while(!selected) {
        char choice;
        std::cout << "Play another game? Y or N" << std::endl;
        std::cin >> choice;
        if(choice == 'N' || choice == 'n') {
            return false;
            selected = true;
        } else if(choice == 'Y' || choice == 'y') {
            return true;
            selected = true;
        } else {
            std::cout << "That is not a valid choice!" << std::endl;
        }
    }
}
 
void reveal(int x, int y) {
    if(x >= 0 && x < DIMX && y >= 0 && y < DIMY) { // check that x and y are valid
        if(display[x][y] == UNCOVERED) {
            return;
        }
        display[x][y] = UNCOVERED;
 
        if(state[x][y] == MINE || state[x][y] != 0) {
            return;
        }
        reveal(x - 1, y - 1);
        reveal(x, y - 1);
        reveal(x + 1, y - 1);
        reveal(x - 1, y);
        reveal(x + 1, y);
        reveal(x - 1, y + 1);
        reveal(x, y + 1);
        reveal(x + 1, y + 1);
    } else {
        return;
    }
}
 
/*
[x-1, y-1][x, y-1][x+1, y-1]
[x-1, y  ][x, y  ][x+1, y  ]
[x-1, y+1][x, y+1][x+1, y+1]
*/
int countSorroundingMines(int x, int y) {
    if(state[x][y] == MINE) {
        return MINE;
    }
    int num = 0;
    if(x > 0 && y > 0) { // top left
        if(state[x - 1][y - 1] == MINE) {
            num++;
        }
    }
    if(y > 0) { // top
        if(state[x][y - 1] == MINE) {
            num++;
        }
    }
    if(x < DIMX - 1  && y > 0) { // top  right
        if(state[x + 1][y - 1] == MINE) {
            num++;
        }
    }
    if(x > 0) { // left
        if(state[x - 1][y] == MINE) {
            num++;
        }
    }
    if(x < DIMX - 1) { // right
        if(state[x + 1][y] == MINE) {
            num++;
        }
    }
    if(x > 0 && y < DIMY - 1) { // bottom left
        if(state[x - 1][y + 1] == MINE) {
            num++;
        }
    }
    if(y < DIMY - 1) { // bottom
        if(state[x][y + 1] == MINE) {
            num++;
        }
    }
    if(x < DIMX - 1 && y < DIMY - 1) { // bottom right
        if(state[x + 1][y + 1] == MINE) {
            num++;
        }
    }
    return num;
}
 
bool isWin() {
    bool win = true;
    for(int y = 0; y < DIMY; y++) {
        for(int x = 0; x < DIMX; x++) {
            win &= ((display[x][y] == UNCOVERED && state[x][y] != MINE) ||
                    ((display[x][y] == COVERED || display[x][y] == FLAG) && state[x][y] == MINE));
        }
    }
    return win;
}
 
bool isLose() {
    for(int y = 0; y < DIMY; y++) {
        for(int x = 0; x < DIMX; x++) {
            if (display[x][y] == UNCOVERED && state[x][y] == MINE) {
                return true;
            }
        }
    }
    return false;
}
 
void player() {
    std::cout << "Commands: R => reveal square, F => set flag, C => cheat, N => New Game" << std::endl;
    bool selected = false;
    while(!selected) {
        char choice;
        std::cin >> choice;
        if(choice == 'R' || choice == 'r') {
            uncover();
            selected = true;
        } else if(choice == 'F' || choice == 'f') {
            setFlag();
            selected = true;
        } else if(choice == 'C' || choice == 'c') {
            cheat();
        } else if(choice == 'N' || choice == 'n') {
            init();
            selected = true;
        } else {
            std::cout << "Invalid Choice!" << std::endl;
        }
    }
 
}
 
void uncover() {
    bool selected = false;
    while(!selected) {
        int x;
        int y;
        std::cout << "Input X (1 - " << (DIMX) << ")" << std::endl;
        std::cin >> x;
        std::cout << "Input Y (1 - " << (DIMY) << ")" << std::endl;
        std::cin >> y;
        x--;
        y--;
        if(x >= 0 && x < DIMX && y >= 0 && y < DIMY) {
            reveal(x, y); // call recursive reveal algorithm
            selected = true;
        } else {
            std::cout << "(X,Y) Values out of range!" << std::endl;
        }
    }
}
 
void setFlag() {
    bool selected = false;
    while(!selected) {
        int x;
        int y;
        std::cout << "Input X (1 - " << (DIMX) << ")" << std::endl;
        std::cin >> x;
        std::cout << "Input Y (1 - " << (DIMY) << ")" << std::endl;
        std::cin >> y;
        x--;
        y--;
        if(x >= 0 && x < DIMX && y >= 0 && y < DIMY) {
            display[x][y] = FLAG;
            selected = true;
        } else {
            std::cout << "(X,Y) Values out of range!" << std::endl;
        }
    }
}
 
void cheat() {
    std::cout << "Cheating is bad!" << std::endl;
    std::cout << "   ";
    for(int x = 0; x < DIMX; x++) {
        std::cout << (x + 1) << " ";
    }
    std::cout << std::endl << "";
    for(int x = 0; x < DIMX; x++) {
        std::cout << "";
    }
    std::cout << std::endl;
    for(int y = 0; y < DIMY; y++) {
        std::cout << (y + 1) << "  ";
        for(int x = 0; x < DIMX; x++) {
            if(state[x][y] == MINE) {
                std::cout << "@ ";
            } else {
                if(state[x][y] == 0) {
                    std:: cout << "  ";
                } else {
                    std:: cout << state[x][y] << " ";
                }
            }
        }
        std::cout << std::endl;
    }
}
 
void print() {
    std::cout << "   ";
    for(int x = 0; x < DIMX; x++) {
        std::cout << (x + 1) << " ";
    }
    std::cout << std::endl << "";
    for(int x = 0; x < DIMX; x++) {
        std::cout << "";
    }
    std::cout << std::endl;
    for(int y = 0; y < DIMY; y++) {
        std::cout << (y + 1) << "  ";
        for(int x = 0; x < DIMX; x++) {
            if(display[x][y] == COVERED || display[x][y] == 'F') { // is it tile still uncovered
                std::cout << display[x][y] << " ";
            } else { // display the state
                if(state[x][y] == MINE) {
                    std::cout << "@ ";
                } else {
                    if(state[x][y] == 0) {
                        std:: cout << "  ";
                    } else {
                        std:: cout << state[x][y] << " ";
                    }
                }
            }
        }
 
        std::cout << std::endl;
    }
}

Sample Output:

C – Simple ASCII RPG/MUDD

This is a very simple RPG that uses ASCII art. It’s not balanced nor complete, just meant to serve as a tutorial of some procedural coding in C.

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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
#include <iostream>
#include <string>
#include <cstdlib>
 
using namespace std;
 
// function declarations
void newGame();
void initPlayer();
void printPlayer();
void initArea();
void generateRandomEnemies();
void printArea();
void printMenu();
void getPlayerInput();
bool isAlive();
int isEnemy();
void fight(struct Enemy& enemy);
void gameOver();
void levelUp();
int dice(int sides);
 
 
// common structures
struct Location {
    int x;      // the x position in the area
    int y;      // the y position in the area
};
 
struct Weapon {
    string name;    // name of weapon
    int damage;  // max damage
    int crit;   // critical hit range (1 to 20)
};
 
struct Armor {
    string name;    // name of armor
    int defence;  // defense modifier
};
 
struct Shield {
    string name;    // name of armor
    int defence;  // defense modifier
};
 
struct Player {
    string name;// name of player
    int job;    // job (class) of the player
 
    int hp;     // current hp
    int hpm;    // hp max
 
    int str;    // strength
    int dex;    // dexterity
    int con;    // constitution
    int iq;     // intelligence
    int wis;    // widsom
    int cha;    // charisma
 
    int bab;    // base attack bonus
    int fort;   // fortitude
    int reflex; // reflex
    int will;   // will
 
    int ac;     // armor class
 
    int level;  // level
    int xp;     // current xp
    int gold;   // amount of gold
 
    struct Weapon weapon;
    struct Armor armor;
    struct Shield shield;
 
    struct Location location;
};
 
struct Enemy {
    string name;// enemy name
    int hp;     // current hp
    int str;    // strength
    int dex;    // dexterity
    int ac;     // armor class
    int gold;   // amount of gold enemy is carrying
    struct Location location;
};
 
 
// create a simple area default 30x30
int AREA_WIDTH = 20;
int AREA_HEIGHT = 12;
int** area; // 2 dimensional array for the area
 
const int AREA_WALKABLE = 0;
const int AREA_WALL = 1;
 
// default player structure
Player player;
 
// default array of enemies (for now lets assume 10 enemies per area)
Enemy* enemies;
const int ENEMIES_MAX_NUM = 100;
 
// main function
int main() {
    srand(time(0)); // generate new random seed (for use with rand() in the dice() function)
    newGame();
 
    while(isAlive()) {
        printArea();
        printMenu();
        getPlayerInput();
 
        int enemyIndex = isEnemy();
        if(enemyIndex> -1) {
            fight(enemies[enemyIndex]);
        }
    }
 
    gameOver();
    return 0;
}
 
// function definitions
bool isAlive() {
    if(player.hp > 0) {
        return true;
    }
    return false;
}
 
 
void gameOver() {
    cout << "Thou Art Dead" << endl;
}
 
 
void newGame() {
    initArea();
    generateRandomEnemies();
    initPlayer();
    printPlayer();
}
 
void initArea() {
    area = new int*[AREA_WIDTH];
    for(int x = 0; x < AREA_WIDTH; ++x) {
         area[x] = new int[AREA_HEIGHT];
         for(int y = 0; y < AREA_HEIGHT; ++y) { // initialize the values, this is optional, but recommended
             if(dice(4) >= 2) {
                area[x][y] =  AREA_WALKABLE;
             } else {
                area[x][y] =  AREA_WALL;
             }
         }
    }
}
 
void generateRandomEnemies() {
    enemies = new Enemy[ENEMIES_MAX_NUM];
    for(int i = 0; i < ENEMIES_MAX_NUM; i++) {
        enemies[i].name = "slime";
        enemies[i].hp = 4 + dice(4);
        enemies[i].str = 12 + dice(4);
        enemies[i].dex = 10 + dice(4);
        enemies[i].ac = 10 + dice(4);
        enemies[i].gold = dice(10);
        enemies[i].location.x = dice(AREA_WIDTH) - 1;
        enemies[i].location.y = dice(AREA_HEIGHT) - 1;
    }
}
 
void initPlayer() {
    player.name = "Kenny";
    player.hpm = 20 + dice(10);
    player.hp = player.hpm;
    player.str = 8 + dice(6);
    player.dex =  8 + dice(6);
    player.con =  8 + dice(6);
    player.iq  =  8 + dice(6);
    player.wis =  8 + dice(6);
    player.cha =  8 + dice(6);
 
    player.bab = 0;
    player.fort = dice(4);
    player.reflex = dice(4);
    player.will = dice(4);
 
    player.ac = 10;
    player.level = 1;
    player.xp = 0;
    player.gold = 30 + dice(100);
 
    player.weapon.name = "Wood Sword";
    player.weapon.damage = 4;
    player.weapon.crit = 19;
 
    player.armor.name = "Leather";
    player.armor.defence = 1;
 
    player.shield.name = "Wood";
    player.shield.defence = 1;
 
    player.location.x = 5;
    player.location.y = 5;
 
}
 
void printPlayer() {
    cout << player.name << endl;
    cout << "HP " << player.hp << "/" << player.hpm << endl;
    cout << "XP " << player.xp << "\t Lvl " << player.level << endl;
    cout << "STR " << player.str << "\t INT " << player.iq << endl;
    cout << "DEX " << player.dex << "\t WIS " << player.wis << endl;
    cout << "CON " << player.con << "\t CHA " << player.cha << endl;
    cout << "BAB +" << player.bab << "\tAC " << player.ac << endl;
    cout << "FORT +" << player.fort << "\tREFLEX +" << player.reflex << "\tWILL +" << player.will << endl;
    cout << "GOLD " << player.gold << endl;
    cout << "WEAPON " << player.weapon.name << ": 1D" << player.weapon.damage << " crit (" << player.weapon.crit << "-20) x2" << endl;
    cout << "ARMOR " << player.armor.name << ": +" << player.armor.defence << endl;
    cout << "SHIELD " << player.shield.name << ": +" << player.shield.defence << endl;
}
 
 
void printArea() {
    for(int y = 0; y < AREA_HEIGHT; ++y) {
        for(int x = 0; x < AREA_WIDTH; ++x) {
            if(player.location.x == x && player.location.y == y) {
                cout << "@";
            } else {
                if(area[x][y] == AREA_WALKABLE) {
                    cout << " ";
                } else if(area[x][y] == AREA_WALL) {
                    cout << "#";
                }
            }
 
        }
        cout << endl;
    }
}
 
void printMenu() {
    cout << "Commands" << endl;
    cout << "L - move left\tR - move right" << endl;
    cout << "U - move up\tD - move down" << endl;
    cout << "S - print stats\tH - Heal (30gp)" << endl;
    cout << "X - exit game" << endl;
    cout << ">";
}
 
void getPlayerInput() {
    char input;
    cin >> input;
    cout << endl; // go to the next line
    if(input == 'U' || input == 'u') { // move up
        if(player.location.y - 1 >= 0
                    && area[player.location.x][player.location.y - 1] != AREA_WALL) {
            player.location.y--;
        } else {
            cout << "Can not move there!" << endl;
        }
    } else if(input == 'D' || input == 'd') { // move down
        if(player.location.y + 1 < AREA_HEIGHT
                    && area[player.location.x][player.location.y + 1] != AREA_WALL) {
            player.location.y++;
        } else {
            cout << "Can not move there!" << endl;
        }
    } else if(input == 'L' || input == 'l') { // move left
        if(player.location.x - 1 >= 0
                    && area[player.location.x - 1][player.location.y] != AREA_WALL) {
            player.location.x--;
        } else {
            cout << "Can not move there!" << endl;
        }
    } else if(input == 'R' || input == 'r') { // move right
        if(player.location.x + 1 < AREA_WIDTH
                    && area[player.location.x + 1][player.location.y] != AREA_WALL) {
            player.location.x++;
        } else {
            cout << "Can not move there!" << endl;
        }
    } else if(input == 'X' || input == 'x') {
        gameOver();
    } else if(input == 'S' || input == 's') {
        printPlayer();
    } else if(input == 'H' || input == 'h') {
        if(player.gold >= 30) {
            player.gold -= 30;
            int heal = dice(20);
            cout << "Healed " << heal << "hp" << endl;
            player.hp += heal;
            if(player.hp > player.hpm) {
                player.hp = player.hpm;
            }
        } else {
            cout << "Thou does not have enough gold to pay healing potion!" << endl;
        }
    }
}
 
int isEnemy() {
    for(int i = 0; i < ENEMIES_MAX_NUM; i++) {
        if(enemies[i].location.x == player.location.x &&
                    enemies[i].location.y == player.location.y) {
            return i; // the index of the enemy array
        }
    }
    return -1; // no enemy
}
 
void fight(struct Enemy& enemy) {
    cout << "You just got in a fight with " << enemy.name << endl;
    bool turn = 0; // enemies turn
    if(dice(20) + (player.dex-10)/2 > dice(20) + (enemy.dex-10)/2) {
        turn = 1;
    }
    while(true) {
        if(player.hp <= 0) {
            cout << "Thou has been slain by " << enemy.name << endl;
            break;
        }
        if(enemy.hp <= 0) {
            cout << "Thou has killed " << enemy.name << endl;
            break;
        }
 
        if(turn) { // players turn
            cout << "It is thou turn" << endl;
            int attackRoll = dice(20);
            if(attackRoll + player.bab + (player.str-10)/2 >= enemy.ac) { // hit
                int damage = dice(player.weapon.damage) + (player.str-10)/2;
                if(attackRoll >= player.weapon.crit) {
                    cout << "Critical hit!" << endl;
                    damage *= 2;
                }
                cout << "Attacked " << enemy.name << " for " << damage << " damage!" << endl;
                enemy.hp -= damage;
            } else {
                cout << "Attack missed!" << endl;
            }
            turn = 0;
        } else {
            cout << enemy.name << "'s attack!" << endl;
            int attackRoll = dice(20);
            if(attackRoll + (enemy.str-10)/2 > player.ac + player.armor.defence + player.shield.defence) { // hit
                int damage = (enemy.str-10)/2;
                if(attackRoll >= 19) {
                    cout << "Critical hit!" << endl;
                    damage *= 2;
                }
                cout << "Thou received " << damage << " damage!" << endl;
                player.hp -= damage;
            } else {
                cout << "Attack missed!" << endl;
            }
            turn = 1;
        }
    }
 
    if(player.hp > 0) {
        player.xp += 2 + dice(4);
        player.gold += enemy.gold;
        levelUp();
    }
    // revive the dead enemy
    enemy.hp = 4 + dice(6);
}
 
void levelUp() {
    bool levelup = false;
    if(player.xp > 16 && player.level == 1) {
        levelup = true;
    } else if(player.xp > 40 && player.level == 2) {
        levelup = true;
    } else if(player.xp > 75 && player.level == 3) {
        levelup = true;
    } else if(player.xp > 120 && player.level == 4) {
        levelup = true;
    } else if(player.xp > 170 && player.level == 5) {
        levelup = true;
    } else if(player.xp > 230 && player.level == 6) {
        levelup = true;
    } else if(player.xp > 300 && player.level == 7) {
        levelup = true;
    } else if(player.xp > 400 && player.level == 8) {
        levelup = true;
    } else if(player.xp > 550 && player.level == 9) {
        levelup = true;
    }
    if(levelup) {
        player.level++;
        player.hpm += dice(8) + (player.con-10)/2;
        player.hp = player.hpm;
        player.str += dice(2);
        player.dex += dice(2);
        player.con += dice(2);
        player.iq += dice(2);
        player.wis += dice(2);
        player.cha += dice(2);
        if(player.level % 3 == 0) {
            player.bab += dice(2);
        }
        cout << "Thou has leveled up!" << endl;
        if(player.level == 10) {
            cout << "Congratulations! Thou has reached max level!" << endl;
        }
        printPlayer();
    }
}
 
 
int dice(int sides) {
    int value = rand()%sides+1;
    return value;
}

PHP – Logger

Mainly written for fun, but this is a configurable Logger written in PHP that supports multiple handlers, including Writers (File, SQL, Apache’s Error Log, Echo), configurable Formatting. various logging levels (FATAL, ERROR, WARN, INFO, DEBUG, TRACE). Also useful functions like isDebug/TraceEnabled(), to check before building large strings to debug/trace(). *While each logger instance can have a unique name, there isn’t any parent/child hierarchy attributed to them.

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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
<?php
/**
 * PHP Logger
 * @author Kenny Cason
 * @site www.ken-soft.com
 */
class Logger {
 
	/**
	 * static Logger for convenient quick use of logger
	 */
	public static function getStaticLogger($resource, $config=array()) {
		$logger = new Logger();
		$logger->resource = $resource;
		Logger::configure($logger, $config);
		return $logger;
	}
 
	/**
	 * singleton instances of a Logger indexed by a unique resource
	 */
	private static $loggerInstances = array();
 
	/*
	 * log levels, int value
	*/
 
	const FATAL         = 6;
	const ERROR         = 5;
	const WARN          = 4;
	const INFO          = 3;
	const DEBUG         = 2;
	const TRACE         = 1;
 
	/*
	 * log levels, string values
	*/
	private static $LOG_LEVELS = array( Logger::TRACE => "TRACE",
			Logger::DEBUG => "DEBUG",
			Logger::INFO => "INFO",
			Logger::WARN => "WARN",
			Logger::ERROR => "ERROR",
			Logger::FATAL => "FATAL");
 
	public $handlers = array();
 
	public $logLevel = Logger::INFO;   // default logging level is info
 
	/*
	 * formatting - move to LogFormatter Class later
	*/
	public $resource = ""; // a unique identifier for this logger (i.e. a class name, or script name)
 
 
	/**
	 * using singleton pattern return a logger instance
	 * @param string $resource
	 * @param array configuration
	 * @return Logger instance
	 */
	public static function getLogger($resource, $config=array()) {
		if (!isset(self::$loggerInstances[$resource])) {
			self::$loggerInstances[$resource] = new Logger();
		}
		Logger::$loggerInstances[$resource]->resource = $resource;
		Logger::configure(Logger::$loggerInstances[$resource],$config);
		return Logger::$loggerInstances[$resource];
	}
 
	private static function configure(Logger $logger, $config=array()) {
		if (isset($config['logLevel'])) {
			$logger->logLevel = $config['logLevel'];
		}
		if (isset($config['handlers']) && is_array($config['handlers'])) {
			$logger->clearHandlers();
			$logger->handlers = $config['handlers'];
		}
		if (isset($config['handler']) && !is_array($config['handler'])) {
			$logger->clearHandlers();
			$logger->addHandler($config['handler']);
		}
 
		if(empty($logger->handlers)) {
			$logger->addHandler(new LogFileHandler()); // create a default LogFileHandler
		}
	}
 
	public function setLevel($level=Logger::ERROR) {
		if($level >= Logger::TRACE && $level <= Logger::FATAL) {
			$this->logLevel = $level;
		} else {
			$this->logLevel = Logger::INFO;
		}
	}
 
	/**
	 * return the current log level
	 * @return string
	 */
	public function getLevel() {
		return  Logger::$LOG_LEVELS[$this->logLevel];
	}
 
	/**
	 * set the log mode. (i.e.log to LOG_TYPE_FILE / LOG_TYPE_SQL / LOG_TYPE_ERROR_LOG
	 * @param int
	 */
	public function setLogMode($logMode) {
		$this->logMode = $logMode;
	}
 
	/**
	 * get lhe log mode
	 * @return int
	 */
	public function getLogMode() {
		return $this->logMode;
	}
 
 
	/**
	 * get all handlers
	 */
	public function getHandlers() {
		return $this->handlers;
	}
 
	/**
	 * add a handler
	 * @param ILogHandler $handler
	 */
	public function addHandler(ILogHandler $handler) {
		$this->handlers[] = $handler;
	}
 
	/**
	 * clear all handlers
	 */
	public function clearHandlers() {
		$this->handlers = array();
	}
 
	/**
	 * determine if the logger level is at least DEBUG level
	 * @return bool
	 */
	public function isDebugEnabled() {
		if($this->getLevel() <= Logger::DEBUG) {
			return true;
		}
		return false;
	}
 
	/**
	 * determine if the logger level is at least TRACE level
	 * @return bool
	 */
	public function isTraceEnabled() {
		if($this->getLevel() <= Logger::TRACE) {
			return true;
		}
		return false;
	}
 
	/**
	 * log at trace level
	 * @param string $msg
	 * @param object $obj (optional)
	 */
	public function trace($msg, $obj=null) {
		if($this->logLevel <= Logger::TRACE) {
			$this->log(Logger::TRACE, $msg, $obj);
		}
	}
 
	/**
	 * log at debug level
	 * @param string $msg
	 * @param object $obj (optional)
	 */
	public function debug($msg, $obj=null) {
		if($this->logLevel <= Logger::DEBUG) {
			$this->log(Logger::DEBUG, $msg, $obj);
		}
	}
 
	/**
	 * log at info level
	 * @param string $msg
	 * @param object $obj (optional)
	 */
	public function info($msg, $obj=null) {
		if($this->logLevel <= Logger::INFO) {
			$this->log(Logger::INFO, $msg, $obj);
		}
	}
 
	/**
	 * log at warn level
	 * @param string $msg
	 * @param object $obj (optional)
	 */
	public function warn($msg, $obj=null) {
		if($this->logLevel <= Logger::WARN) {
			$this->log(Logger::WARN, $msg, $obj);
		}
	}
 
	/**
	 * log at error level
	 * @param string $msg
	 * @param object $obj (optional)
	 */
	public function error($msg, $obj=null) {
		if($this->logLevel <= Logger::ERROR) {
			$this->log(Logger::ERROR, $msg, $obj);
		}
	}
 
	/**
	 * log at catastrophic level
	 * @param string $msg
	 * @param object $obj (optional)
	 */
	public function fatal($msg, $obj=null) {
		if($this->logLevel <= Logger::FATAL) {
			$this->log(Logger::FATAL, $msg, $obj);
		}
	}
 
	/**
	 * private helper
	 * @param int $logLevel
	 * @param string $msg
	 */
	public function log($logLevel, $msg, $obj=null) {
		$record = new LogRecord();
		$record->setLevel(Logger::$LOG_LEVELS[$logLevel]);
		$record->setMessage($msg);
		$record->setResource($this->resource);
		$record->setObject($obj);
		foreach($this->handlers as $handler) {
			$handler->publish($record);
		}
	}
 
	/**
	 * private constructor init using getLogger()
	 */
	private function __construct() {
	}
 
	/**
	 *  Prevent users to clone the instance
	 */
	public function __clone() {
		$this->log('Clone is not allowed.');
	}
 
}
 
/**
 * This class encapsulates the Record to be logged
 */
class LogRecord {
 
	private $resource;
 
	private $level;
 
	private $msg;
 
	private $obj; // optional object to log along with $msg
 
	private $time;
 
	public function __construct() {
		$this->time = time();
	}
 
	public function setResource($resource) {
		$this->resource = $resource;
	}
 
	public function setLevel($level) {
		$this->level = $level;
	}
 
	public function setMessage($msg) {
		$this->msg = $msg;
	}
 
	public function setObject($obj) {
		$this->obj = $obj;
	}
 
	public function setTime($time) {
		$this->time = $time;
	}
 
	public function getResource() {
		return $this->resource;
	}
 
	public function getLevel() {
		return $this->level;
	}
 
	public function getMessage() {
		return $this->msg;
	}
 
	public function getObject() {
		return $this->obj;
	}
 
	public function getTime($format=null) {
		if($format == null) {
			return $this->time;
		}
		return date($format, $this->time);
	}
 
}
 
 
 
 
 
/**
 * LogHandler interface
 */
interface ILogHandler {
 
	public function publish(LogRecord $record);
 
	public function setFormatter(ILogFormatter $formatter);
 
	public function getFormatter();
 
}
 
/**
 * contains common functionality between log handlers
 */
abstract class AbstractLogHandler implements ILogHandler {
 
	protected $formatter;
 
	public function __construct() {
		$this->formatter = new LogDefaultFormatter();
	}
 
	public function setFormatter(ILogFormatter $formatter) {
		$this->formatter = $formatter;
	}
 
	public function getFormatter() {
		return $this->formatter;
	}
 
}
 
/**
 * Outputs to a LogFile
 */
class LogFileHandler extends AbstractLogHandler {
 
	private $logFileName = "/tmp/output.log";
 
	public function __construct($logFileName="") {
		parent::__construct();
		if($logFileName != "") {
			$this->logFileName = $logFileName;
		}
	}
 
	public function publish(LogRecord $record) {
		$log_msg = $this->formatter->format($record);
 
		$logFile = fopen($this->logFileName, 'a');
		if (!$logFile) {
			return array('status' => 'failure', 'msg' => 'Error Opening Log File');
		}
		fwrite($logFile, $log_msg);
		fclose($logFile);
	}
 
	/**
	 * set the log file name to append to
	 * @param string
	 */
	public function setLogFileName($logFileName) {
		$this->logFileName = $logFileName;
	}
 
	public function getLogFileName() {
		return $this->logFileName;
	}
 
}
 
/**
 * Echo out the Log
 */
class LogConsoleHandler extends AbstractLogHandler {
 
	public function __construct() {
		parent::__construct();
	}
 
	public function publish(LogRecord $record) {
		echo $this->formatter->format($record);
	}
 
}
 
/**
 * Log via error_log()
 */
class LogApacheErrorLogHandler extends AbstractLogHandler {
 
	public function __construct() {
		parent::__construct();
	}
 
	public function publish(LogRecord $record) {
		error_log($this->formatter->format($record));
	}
 
}
 
/**
 * Logs to SQL DataBase
 */
class LogSQLHandler extends AbstractLogHandler {
 
	private $db = null; // mysqli instance
 
	public function __construct($db) {
		$this->db = $db;
	}
 
	public function publish(LogRecord $record) {
		$sql = "INSERT INTO `log` (log_level, date, resource, msg) VALUES ('{$record->getLevel()}','{$record->getTime()}', ?, ?);";
		$statement = $this->db->prepare($sql);
		$statement->bind_param("ss", $record->getResource(), $record->getMessage());
		if (!$statement->execute()) {
			return array('status' => 'failure', 'msg' => 'SQL Error');
		}
		$statement->close();
	}
 
	public function setDB(mysqli $db) {
		$this->db = $mysqli;
	}
 
	public function getDB() {
		return $this->db;
	}
 
	public static function init() {
		$sql = "CREATE TABLE `log` (
		`id` BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY,
		`log_level` VARCHAR( 16 ) NOT NULL,
		`date` DATETIME NOT NULL,
		`resource` VARCHAR( 128 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
		`msg` VARCHAR( 1024 ) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL
		) ENGINE = MYISAM;";
		$this->db->query($sql);
	}
 
}
 
 
 
 
 
 
 
 
/**
 * Interface for formatting log messages
 */
interface ILogFormatter {
 
	public function format(LogRecord $record);
 
}
 
/**
 * concrete implementation of a Log Formatter that is formattable
 * %L - Log Level
 * %T - Time of logging
 * %R - Resource of the logger
 * %M - The Message
 * %O - The Object
 */
class LogFormatter implements ILogFormatter {
 
	private $format = null;
 
	private $dateFormat = "Y-m-d H:i:s";
 
	public function __construct($format="%L [%T] %R %M %O") {
		$this->format = $format;
	}
 
	/**
	 * return a formatted string
	 * @param LogRecord $record
	 */
	public function format(LogRecord $record) {
		$formatted_record = $this->format;
		$formatted_record = str_replace("%L",$record->getLevel(),$formatted_record);
		$formatted_record = str_replace("%T",$record->getTime($this->dateFormat),$formatted_record);
		$formatted_record = str_replace("%R",$record->getResource(),$formatted_record);
		$formatted_record = str_replace("%M",$record->getMessage(),$formatted_record);
		$formatted_record = str_replace("%O",$record->getObject(),$formatted_record);
		return $formatted_record;
	}
 
	public function setDateFormat($dateFormat) {
		$this->dateFormat = $dateFormat;
	}
 
}
 
/**
 * Default log formatter, format is immutable, but should suffice for most cases
 */
class LogDefaultFormatter implements ILogFormatter {
 
	private $dateFormat = "Y-m-d H:i:s";
 
	public function __construct() {
	}
 
	public function format(LogRecord $record) {
		return "{$record->getLevel()}\t[{$record->getTime($this->dateFormat)}]\t{$record->getResource()}\t{$record->getMessage()}\t".print_r($record->getObject(),1)."\n";
	}
 
}
 
?>

A simple Demo

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
<?php
 
require_once("DBConfig.php"); // <-- DB stuff only really needed if you want to use the SQL writer.
require_once("Logger.php");
 
$db = new mysqli($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_DATABASE,$DB_PORT);
$db->set_charset("utf8");
// check connection
if (mysqli_connect_errno()) {
    printf("DB Connection failed: %s\n", mysqli_connect_error());
    exit();
}
 
/*
 * out of class example
 */
//$logger = Logger::getLogger(__FILE__);
//$logger->addHandler(new LogConsoleHandler());
//$logger->addHandler(new LogFileHandler("/tmp/output.log"));
//$logger->addHandler(new LogSQLHandler($db));
 
 
/*
 * in class example
 */
 
$foo = new Foo($db);
$foo->bar();
 
class Foo {
 
    private $logger;
 
    public function __construct($db) {
        /*
         * A simple Logger with default Formatter and a Default LogFileHandler (prints out to /tmp/output.log
         */
        $this->logger = Logger::getLogger(__CLASS__, array("logLevel" => Logger::TRACE));
 
        /**
         * add a custom Formatter
         */
        $this->logger->clearHandlers(); // this clears the default handler (i may make this happen invisibly later)
        $fh = new LogFileHandler("/tmp/output.log");
        $fh->setFormatter(new LogFormatter("%L --- %R --- (%T) --- %M %O\n"));
        $this->logger->addHandler($fh);
 
     //   $this->logger = Logger::getLogger(__CLASS__, array("logLevel" => Logger::TRACE,
     //       "handlers" => array(new LogFileHandler("/tmp/output3.log"), new LogSQLHandler($db), new LogConsoleHandler(), new LogErrorLogHandler())
    //        ));
 
        print_r($this->logger);
    }
 
    public function bar() {
 
        $this->logger->trace("A Trace Statement (Level INFO)");
        $this->logger->debug("A Debug Statement (Level INFO)");
        $this->logger->info("An Info level msg (Level INFO)");
        $this->logger->warn("A Warning Occured (Level INFO)");
        $this->logger->error("An Error Occured (Level INFO)");
        $this->logger->fatal("A Fatal Error occured (Level INFO)");
 
        $this->logger->setLevel(Logger::TRACE);
        $this->logger->trace("A Trace Statement (Level TRACE)");
        $this->logger->debug("A Debug Statement (Level TRACE)");
        $this->logger->info("An Info level msg (Level TRACE)", $this);
        $this->logger->warn("A Warning Occured (Level TRACE)");
        $this->logger->error("An Error Occured (Level TRACE)");
        $this->logger->fatal("A Fatal Error occured (Level TRACE)");
 
        $this->logger->setLevel(Logger::FATAL);
        $this->logger->trace("A Trace Statement (Level FATAL)");
        $this->logger->debug("A Debug Statement (Level FATAL)");
        $this->logger->info("An Info level msg (Level FATAL)");
        $this->logger->warn("A Warning Occured (Level FATAL)", $this);
        $this->logger->error("An Error Occured (Level FATAL)");
        $this->logger->fatal("A Fatal Error occured (Level FATAL)");
 
        if($this->logger->isDebugEnabled()) {
            $this->logger->debug("First Debug Statement (shouldn't be printed)");
        }
        $this->logger->setLevel(Logger::DEBUG);
        if($this->logger->isDebugEnabled()) {
            $this->logger->debug("Second Debug Statement (should be printed)");
        }
        if($this->logger->isTraceEnabled()) {
            $this->logger->trace("First Trace Statement (shouldn't be printed)");
        }
        $this->logger->setLevel(Logger::TRACE);
        if($this->logger->isTraceEnabled()) {
            $this->logger->trace("Second Trace Statement (should be printed)");
        }
    }
 
    public function __toString() {
        return "ASFASDFASDF";
    }
}
 
 
echo "<br/>Test Complete<br/>";
?>

PHP – Observer/Observable Design Pattern

This is a PHP implementation of the Java Observer/Observable classes.

Observable.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
<?php
 
/**
 * Observable
 *
 * @author kenny
 */
class Observable {
 
	private $changed = false;
 
	private $observers = array();
 
	public function addObserver(Observer $o) {
		if($o == null) {
			throw new NullPointerException();
		}
		$contains = 0;
		foreach($this->observers as $observer) {
			if($o === $observer) {
				$contains = true;
				break;
			}
		}
		if(!$contains) {
			$this->observers[] = $o;
		}
	}
 
	public function deleteObserver(Observer $o) {
		for($i = 0; $i < count($this->observers); $i++) {
			if($this->observers[$i] == $o) {
				unset($this->observers[$i]);
			}
		}
		$observers = array();
		foreach($this->observers as $observer) {
			$observers[] = $observer;
		}
		$this->observers = $observers;
	}
 
	public function notifyObservers($object = null) {
		if(!$this->changed) {
			return;
			$this->clearChanged();
		}
		foreach($this->observers as $ob) {
			$ob->update($this, $object);
		}
	}
 
	public function deleteObservers() {
		$this->observers = array();
	}
 
	protected function setChanged() {
		$this->changed = true;
	}
 
	protected function clearChanged() {
		$this->changed = false;
	}
 
	public function hasChanged() {
		return $this->changed;
	}
 
	public function countObservers() {
		return count($this->observers);
	}
 
}
?>

Observer.php

1
2
3
4
5
6
7
8
9
10
11
<?php
 
/**
 *
 * @author kenny
 */
interface Observer {
 
	public function update(Observable $o, $object);
}
?>

A Unit test (using SimpleTest)

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
<?php
 
define('SIMPLE_TEST', '../simpletest/'); 
require_once(SIMPLE_TEST . 'unit_tester.php');
require_once(SIMPLE_TEST . 'reporter.php');
require_once('Observable.php');
require_once('Observer.php');
 
class MockObservable extends Observable {
 
    public $object = null;
 
    public function set($object) {
        $this->object = $object;
    }
 
    public function setAndNotify($object) {
        $this->object = $object;
        $this->setChanged();
        $this->notifyObservers($object);
    }
 
}
 
class MockObserver implements Observer {
 
    public $observed = null;
 
    public function update(Observable $o, $observed) {
        $this->observed = $observed;
    }
}
 
class ObserverTest extends UnitTestCase {
 
    public function setUp() {
 
    }
 
    public function test() {
 
        $observer = new MockObserver();
        $observable = new MockObservable();
 
        // test defaults
        $this->assertNull($observer->observed);
        $this->assertNull($observable->object);
        $this->assertFalse($observable->hasChanged());
        $this->assertEqual($observable->countObservers(), 0);
 
        // test add
        $observable->addObserver($observer);
        $this->assertEqual($observable->countObservers(), 1);
 
        // test to not add duplicate observers
        $observable->addObserver($observer);
        $this->assertEqual($observable->countObservers(), 1);
        $observer2 = new MockObserver();
        $observable->addObserver($observer2);
        $this->assertEqual($observable->countObservers(), 2);
        $observable->deleteObserver($observer2);
        $this->assertEqual($observable->countObservers(), 1);
 
        // test delete
        $observable->deleteObserver($observer);
        $this->assertEqual($observable->countObservers(), 0);
        $observable->addObserver($observer);
 
        $observable->set(10);
        // test not notfiy unless setChagnged() has been called
        $observable->notifyObservers();
        $this->assertNull($observer->observed);
 
        // test notify
        $observable->setAndNotify(10);
        $this->assertEqual($observer->observed, 10);
 
    }
 
}
 
?>

PHP – Binary Tree

A simple binary tree in php, will add a delete function later :P

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
<?php
 
/**
 * binary Tree node
 */
class BinaryTreeNode {
 
	public $object;
	public $left;
	public $right;
 
	public function __construct($object) {
		$this->object = $object;
		$this->left = null;
		$this->right = null;
	}
 
	public function compareTo($object) {
		if ($this->object <= $object) {
			return BinaryTree::$RIGHT;
		}
		return BinaryTree::$LEFT;
	}
 
}
/**
 * A simple BinaryTree
 *
 * @author kenny
 */
class BinaryTree {
 
	public static $LEFT = -1;
 
	public static $RIGHT = 1;
 
	private $root;
 
	private $size;
 
	public function __construct() {
		$this->root = null;
		$this->size = null;
	}
 
	public function add($object) {
		$this->addRecur($this->root, $object);
	}
 
	private function addRecur($n, $object) {
		if($this->root == null) {
			$this->root = new BinaryTreeNode($object);
			$this->size++;
		} else if($n->compareTo($object) == BinaryTree::$LEFT) {
			if($n->left == null) {
				$n->left = new BinaryTreeNode($object);
				$this->size++;
			} else {
				$this->addRecur($n->left, $object);
			}
		} else {
			if($n->right == null) {
				$n->right = new BinaryTreeNode($object);
				$this->size++;
			} else {
				$this->addRecur($n->right, $object);
			}
		}
	}
 
	public function contains($object) {
		return $this->containsRecur($this->root, $object);
	}
 
	private function containsRecur($n, $object) {
		if($this->root == null) {
			return false;
		} else if($n->object == $object) {
			return true;
		} else if($n->compareTo($object) == BinaryTree::$LEFT) {
			if($n->left == null) {
				return false;
			} else {
				return $this->containsRecur($n->left, $object);
			}
		} else {
			if($n->right == null) {
				return false;
			} else {
				return $this->containsRecur($n->right, $object);
			}
		}
	}
 
	public function size() {
		return $this->size;
	}
 
	public function isEmpty() {
		return ($this->size == 0);
	}
 
	public function getAll() {
		$all = array();
		$this->getAllRecur($this->root, $all);
		return $all;
	}
 
	private function getAllRecur($n, &$all) {
		if($n == null) {
			return;
		}
		$all[] = $n;
		$this->getAllRecur($n->left, $all);
		$this->getAllRecur($n->right, $all);
	}
 
	public function getRoot() {
		if($this->root == null) {
			return null;
		}
		return $this->root->object;
	}
 
}
?>

A Unit test (using SimpleTest)

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
<?php
 
define('SIMPLE_TEST', '../simpletest/'); 
require_once(SIMPLE_TEST . 'unit_tester.php');
require_once(SIMPLE_TEST . 'reporter.php');
$test = &new GroupTest('BinaryTreeTest');
$test->addTestCase(new BinaryTreeTest());
$test->run(new HtmlReporter());
 
 
class BinaryTreeTest extends UnitTestCase {
 
    public function setUp() {
 
    }
 
    public function test() {
 
        $btree = new BinaryTree();
        $this->assertEqual($btree->size(), 0);
        $btree->add(10);
        $this->assertEqual($btree->size(), 1);
        $this->assertEqual($btree->getRoot(), 10);
 
        $btree->add(15);
        $this->assertEqual($btree->size(), 2);
 
        $btree->add(5);
        $this->assertEqual($btree->size(), 3);
        $btree->add(3);
        $this->assertEqual($btree->size(), 4);
 
        $this->assertEqual($btree->getRoot(), 10);
 
 
        $this->assertTrue($btree->contains(10));
        $this->assertTrue($btree->contains(15));
        $this->assertTrue($btree->contains(5));
        $this->assertFalse($btree->contains(-1));
        $this->assertFalse($btree->contains(55));
 
        $arr = $btree->getAll();
        $this->assertEqual(count($arr), $btree->size());
 
 
    }
 
}
 
?>

jTicTacToe – Display a Tic Tac Toe Game State/Animation (jGames)

jTicTacToe is one module within the jGames suite used to display Tic Tac Toe game states, as well as animations. jGames can be downloaded from the jGames home page.

Display Static Tic Tac Toe State
First include the following lines to your webpage

1
2
    <script type="text/javascript" src="js/jgames/jquery.jgames.js"></script>
    <link href="js/jgames/css/style.css" rel="stylesheet" type="text/css" />

Create an empty div tag and give it an ID, i.e. “tictactoe”. This is where the tic tac toe board will be rendered to.

1
<div id="tictactoe"></div>

Next, create the state of the tic tac toe board using Javascript. The below state represents every piece in the Tic Tac Toe game and renders the tic tac toe above left tic tac toe board.

1
2
3
4
5
6
        var board_tictactoe = [
            ["o", "o", "x"],
            ["o", "x", "x"],
            [" ", "o", " "]
        ];
       $("#tictactoe").tictactoe(board_tictactoe);

Creating an Animation
Creating an animation is very easy. You simply pass an array of states, and the time interval between states (in milliseconds) to the tictactoeAnimator() function. Below is the code to render the above right Tic Tac Toe animation.

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
        var board_tictactoe_anim =
        [
            [
                [" ", " ", " "],
                [" ", " ", " "],
                [" ", " ", " "]
            ],
            [
                [" ", " ", "o"],
                [" ", " ", " "],
                [" ", " ", " "]
            ],
            [
                [" ", " ", "o"],
                [" ", "x", " "],
                [" ", " ", " "]
            ],
            [
                [" ", " ", "o"],
                [" ", "x", " "],
                [" ", " ", "o"]
            ],
            [
                [" ", " ", "o"],
                [" ", "x", "x"],
                [" ", " ", "o"]
            ],
            [
                [" ", " ", "o"],
                [" ", "x", "x"],
                [" ", "o", "o"]
            ],
            [
                [" ", " ", "o"],
                ["x", "x", "x"],
                [" ", "o", "o"]
            ]
        ];
 
        $("#tictactoe_anim").tictactoeAnimator(board_tictactoe_anim, 1000);


jOthello – Display a Othello Game State/Animation (jGames)

jOthello is one module within the jGames suite used to display Othello game states, as well as animations. jGames can be downloaded from the jGames home page.

Display Static Othello State
First include the following lines to your webpage

1
2
    <script type="text/javascript" src="js/jgames/jquery.jgames.js"></script>
    <link href="js/jgames/css/style.css" rel="stylesheet" type="text/css" />

Create an empty div tag and give it an ID, i.e. “othello”. This is where the othello board will be rendered to.

1
<div id="othello"></div>

Next, create the state of the othello board using Javascript. The below state represents every piece in the Othello game and renders the othello above left othello board.

1
2
3
4
5
6
7
8
9
10
11
        var board_othello = [
            [" ", " ", " ", " ", " ", " ", " ", " "],
            [" ", " ", "b", " ", " ", " ", "w", " "],
            [" ", " ", "b", " ", " ", "w", " ", " "],
            [" ", "b", "b", "b", "w", "w", "w", " "],
            [" ", " ", "b", "w", "w", " ", " ", " "],
            [" ", "b", "w", "w", "w", "w", " ", " "],
            [" ", "w", " ", "w", " ", " ", " ", " "],
            ["w", "b", " ", "w", " ", " ", " ", " "]];
 
       $("#othello").othello(board_othello);

Creating an Animation
Creating an animation is very easy. You simply pass an array of states, and the time interval between states (in milliseconds) to the othelloAnimator() function. Below is the code to render the above right othello animation.

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
        var board_othello_anim =
        [
            [
                [" ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", "b", " ", " ", " ", "w", " "],
                [" ", " ", "b", " ", " ", "w", " ", " "],
                [" ", "b", "b", "b", "w", "w", "w", " "],
                [" ", " ", "b", "w", "w", " ", " ", " "],
                [" ", "b", "w", "w", "w", "w", " ", " "],
                [" ", "w", " ", "w", " ", " ", " ", " "],
                ["w", "b", " ", "w", " ", " ", " ", " "]
            ],
            [
                [" ", " ", "w", " ", " ", " ", " ", " "],
                [" ", " ", "b", " ", " ", " ", "w", " "],
                [" ", " ", "b", " ", " ", "w", " ", " "],
                [" ", "b", "b", "b", "w", "w", "w", " "],
                [" ", " ", "b", "w", "w", " ", " ", " "],
                [" ", "b", "w", "w", "w", "w", " ", " "],
                [" ", "w", " ", "w", " ", " ", " ", " "],
                ["w", "b", " ", "w", " ", " ", " ", " "]
            ],
            [
                [" ", " ", "w", " ", " ", " ", " ", " "],
                [" ", " ", "w", " ", " ", " ", "w", " "],
                [" ", " ", "w", " ", " ", "w", " ", " "],
                [" ", "b", "w", "b", "w", "w", "w", " "],
                [" ", " ", "w", "w", "w", " ", " ", " "],
                [" ", "b", "w", "w", "w", "w", " ", " "],
                [" ", "w", " ", "w", " ", " ", " ", " "],
                ["w", "b", " ", "w", " ", " ", " ", " "]
            ],
            [
                [" ", " ", "w", " ", " ", " ", " ", " "],
                [" ", " ", "w", " ", " ", " ", "w", " "],
                [" ", " ", "w", " ", " ", "w", " ", " "],
                [" ", "b", "w", "b", "w", "w", "w", " "],
                [" ", " ", "w", "w", "w", " ", " ", " "],
                [" ", "b", "w", "w", "w", "w", "b", " "],
                [" ", "w", " ", "w", " ", " ", " ", " "],
                ["w", "b", " ", "w", " ", " ", " ", " "]
            ],
            [
                [" ", " ", "w", " ", " ", " ", " ", " "],
                [" ", " ", "w", " ", " ", " ", "w", " "],
                [" ", " ", "w", " ", " ", "w", " ", " "],
                [" ", "b", "w", "b", "w", "w", "w", " "],
                [" ", " ", "w", "w", "w", " ", " ", " "],
                [" ", "b", "b", "b", "b", "b", "b", " "],
                [" ", "w", " ", "w", " ", " ", " ", " "],
                ["w", "b", " ", "w", " ", " ", " ", " "]
            ]
        ];
 
        $("#othello_anim").othelloAnimator(board_othello_anim, 1000);


jShogi – Display a Shogi(将棋) Game State/Animation (jGames)

jShogi is one module within the jGames suite used to display Shogi game states, as well as animations. jGames can be downloaded from the jGames home page.

Display Static Shogi State
First include the following lines to your webpage

1
2
    <script type="text/javascript" src="js/jgames/jquery.jgames.js"></script>
    <link href="js/jgames/css/style.css" rel="stylesheet" type="text/css" />

Create an empty div tag and give it an ID, i.e. “shogi”. This is where the shogi board will be rendered to.

1
<div id="shogi"></div>

Next, create the state of the chess board using Javascript. The below state represents every piece in the Chess game and renders the chess top chess board. (Note: To promote a piece you will add “p” to the end of the name, that should be updated by the end of this week!)

1
2
3
4
5
6
7
8
9
10
11
12
        var board_shogi = [
            ["L-", "N-", "S-", "G-", "K-", "G-", "S-", "N-", "L-"],
            [" ", "R-", " ", " ", " ", " ", " ", "B-", " "],
            ["p-", "p-", "p-", "p-", "p-", "p-", "p-", "p-", "p-"],
            [" ", " ", " ", " ", " ", " ", " ", " ", " "],
            [" ", " ", " ", " ", " ", " ", " ", " ", " "],
            [" ", " ", " ", " ", " ", " ", " ", " ", " "],
            ["p", "p", "p", "p", "p", "p", "p", "p", "p"],
            [" ", "B", " ", " ", " ", " ", " ", "R", " "],
            ["L", "N", "S", "G", "K", "G", "S", "N", "L"]
        ];
     //   $("#shogi").shogi(board_shogi);

Creating an Animation
Creating an animation is very easy. You simply pass an array of states, and the time interval between states (in milliseconds) to the shogiAnimator() function. Below is the code to render the bottom shogi animation.

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
        var board_shogi_anim =
            [
                [
                    ["L-", "N-", "S-", "G-", "K-", "G-", "S-", "N-", "L-"],
                    [" ", "R-", " ", " ", " ", " ", " ", "B-", " "],
                    ["p-", "p-", "p-", "p-", "p-", "p-", "p-", "p-", "p-"],
                    [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                    [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                    [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                    ["p", "p", "p", "p", "p", "p", "p", "p", "p"],
                    [" ", "B", " ", " ", " ", " ", " ", "R", " "],
                    ["L", "N", "S", "G", "K", "G", "S", "N", "L"]
                ],
                [
                    ["L-", "N-", "S-", "G-", "K-", "G-", "S-", "N-", "L-"],
                    [" ", "R-", " ", " ", " ", " ", " ", "B-", " "],
                    ["p-", "p-", "p-", "p-", "p-", "p-", "p-", "p-", "p-"],
                    [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                    [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                    [" ", " ", " ", " ", " ", "p", " ", " ", " "],
                    ["p", "p", "p", "p", "p", " ", "p", "p", "p"],
                    [" ", "B", " ", " ", " ", " ", " ", "R", " "],
                    ["L", "N", "S", "G", "K", "G", "S", "N", "L"]
                ],
                [
                    ["L-", "N-", "S-", "G-", "K-", "G-", "S-", "N-", "L-"],
                    [" ", "R-", " ", " ", " ", " ", " ", "B-", " "],
                    ["p-", "p-", "", "p-", "p-", "p-", "p-", "p-", "p-"],
                    [" ", " ", "p-", " ", " ", " ", " ", " ", " "],
                    [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                    [" ", " ", " ", " ", " ", "p", " ", " ", " "],
                    ["p", "p", "p", "p", "p", " ", "p", "p", "p"],
                    [" ", "B", " ", " ", " ", " ", " ", "R", " "],
                    ["L", "N", "S", "G", "K", "G", "S", "N", "L"]
                ],
                [
                    ["L-", "N-", "S-", "G-", "K-", "G-", "S-", "N-", "L-"],
                    [" ", "R-", " ", " ", " ", " ", " ", "B-", " "],
                    ["p-", "p-", " ", "p-", "p-", "p-", "p-", "p-", "p-"],
                    [" ", " ", "p-", " ", " ", " ", " ", " ", " "],
                    [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                    [" ", " ", " ", " ", "p", "p", " ", " ", " "],
                    ["p", "p", "p", "p", " ", " ", "p", "p", "p"],
                    [" ", "B", " ", " ", " ", " ", " ", "R", " "],
                    ["L", "N", "S", "G", "K", "G", "S", "N", "L"]
                ]
            ];
 
        $("#shogi_anim").shogiAnimator(board_shogi_anim, 1000);


jXiangQi – Display a XiangQi(象棋) Game State/Animation (jGames)

jXiangQi is one module within the jGames suite used to display xiangqi game states, as well as animations. jGames can be downloaded from the jGames home page.

Display Static XiangQi State
First include the following lines to your webpage

1
2
    <script type="text/javascript" src="js/jgames/jquery.jgames.js"></script>
    <link href="js/jgames/css/style.css" rel="stylesheet" type="text/css" />

Create an empty div tag and give it an ID, i.e. “xiangqi”. This is where the xiangqi board will be rendered to.

1
<div id="xiangqi"></div>

Next, create the state of the xiangqi board using Javascript. The below state represents every piece in the xiangqi game and renders the top xiangqi board.

1
2
3
4
5
6
7
8
9
10
11
12
        var board_xiangqi = [
            ["br", "bn", "bb", "ba", "bk", "ba", "bb", "bn", "br"],
            [" ", " ", " ", " ", " ", " ", " ", " ", " "],
            [" ", "bc", " ", " ", " ", " ", " ", "bc", " "],
            ["bp", " ", "bp", " ", "bp", " ", "bp", " ", "bp"],
            [" ", " ", " ", " ", " ", " ", " ", " ", " "],
            [" ", " ", " ", " ", " ", " ", " ", " ", " "],
            ["rp", " ", "rp", " ", "rp", " ", "rp", " ", "rp"],
            [" ", "rc", " ", " ", " ", " ", " ", "rc", " "],
            [" ", " ", " ", " ", " ", " ", " ", " ", " "],
            ["rr", "rn", "rb", "ra", "rk", "ra", "rb", "rn", "rr"]];
       $("#xiangqi").xiangqi(board_xiangqi);

Creating an Animation
Creating an animation is very easy. You simply pass an array of states, and the time interval between states (in milliseconds) to the xiangqiAnimator() function. Below is the code to render the bottom xiangqi animation.

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
        var board_xiangqi_anim =
        [
            [
                ["br", "bn", "bb", "ba", "bk", "ba", "bb", "bn", "br"],
                [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", "bc", " ", " ", " ", " ", " ", "bc", " "],
                ["bp", " ", "bp", " ", "bp", " ", "bp", " ", "bp"],
                [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                ["rp", " ", "rp", " ", "rp", " ", "rp", " ", "rp"],
                [" ", "rc", " ", " ", " ", " ", " ", "rc", " "],
                [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                ["rr", "rn", "rb", "ra", "rk", "ra", "rb", "rn", "rr"]
            ],
            [
                ["br", "bn", "bb", "ba", "bk", "ba", "bb", "bn", "br"],
                [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", "bc", " ", " ", " ", " ", " ", "bc", " "],
                ["bp", " ", "bp", " ", "bp", " ", "bp", " ", "bp"],
                [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", " ", " ", " ", " ", "rp", " ", " "],
                ["rp", " ", "rp", " ", "rp", " ", "", " ", "rp"],
                [" ", "rc", " ", " ", " ", " ", " ", "rc", " "],
                [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                ["rr", "rn", "rb", "ra", "rk", "ra", "rb", "rn", "rr"]
            ],
            [
                ["br", "bn", "bb", "ba", "bk", "ba", "bb", "bn", "br"],
                [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", "bc", " ", " ", " ", " ", " ", "  ", " "],
                ["bp", " ", "bp", " ", "bp", " ", "bp", " ", "bp"],
                [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", " ", " ", " ", " ", "rp", " ", " "],
                ["rp", " ", "rp", " ", "rp", " ", "", " ", "rp"],
                [" ", "rc", " ", " ", " ", " ", " ", "rc", " "],
                [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                ["rr", "rn", "rb", "ra", "rk", "ra", "rb", "bc", "rr"]
            ],
            [
                ["br", "bn", "bb", "ba", "bk", "ba", "bb", "bn", "br"],
                [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", "bc", " ", " ", " ", " ", " ", "  ", " "],
                ["bp", " ", "bp", " ", "bp", " ", "bp", " ", "bp"],
                [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", " ", " ", " ", " ", "rp", " ", " "],
                ["rp", " ", "rp", " ", "rp", " ", "", " ", "rp"],
                [" ", "rc", " ", " ", " ", " ", " ", "rc", "rr"],
                [" ", " ", " ", " ", " ", " ", " ", " ", " "],
                ["rr", "rn", "rb", "ra", "rk", "ra", "rb", "bc", " "]
            ]
        ];
 
        $("#xiangqi_anim").xiangqiAnimator(board_xiangqi_anim, 1000);


jGo – Display a Go(围棋) Game State/Animation (jGames)

jGo is one module within the jGames suite used to display Go game states, as well as animations. jGames can be downloaded from the jGames home page. jGo supporst both 13×13 boards as well as 19×19 boards.

Display Static Go State
First include the following lines to your webpage

1
2
    <script type="text/javascript" src="js/jgames/jquery.jgames.js"></script>
    <link href="js/jgames/css/style.css" rel="stylesheet" type="text/css" />

Create an empty div tag and give it an ID, i.e. “go”. This is where the go board will be rendered to.

1
<div id="go"></div>

Next, create the state of the go board using Javascript. The below state represents every piece in the Go game and renders the go top 13×13 go board.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
        var board_go_13 =
            [
                ["b", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "b"],
                [" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", " ", " ", " ", "b", "w", "w", "b", " ", " ", " ", " "],
                [" ", " ", " ", "w", " ", " ", "w", "b", "b", "b", " ", " ", " "],
                [" ", " ", " ", " ", " ", " ", " ", " ", "b", "b", "b", " ", " "],
                [" ", " ", " ", " ", " ", " ", " ", " ", " ", "w", "w", " ", " "],
                [" ", " ", "w", " ", " ", " ", " ", " ", "w", " ", " ", " ", " "],
                [" ", " ", " ", "b", " ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", "w", "b", " ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", "w", "b", " ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", "w", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", " ", "b", " ", " ", " ", " ", " ", " ", " ", " ", " "],
                [" ", " ", "w", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "]
            ];
       $("#go").go(board_go_13);

The below state represents every piece in the Go game and renders the go bottom 19×19 go board. Note that only sizes 13×13 and 19×19 work, anything else will result in an error.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
        var board_go = [
            ["b", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "b"],
            [" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "],
            [" ", " ", " "