-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.php
executable file
·1081 lines (1032 loc) · 38.7 KB
/
index.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
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// //created september 2015 by anton bil
//db structure:
/*$db = new SQLite3('mysqlitedb.db');*/
/*game(gamenumber,status,starter,tokenplayer,deckontable,restcards,winner)
gameuser(usernr,gamenumber,ordernr,status,password)
player(ip,id,name,status)
playercards(player,game,cards)
gamemove(game,player,cards,time)
*/
/*$db->exec('CREATE TABLE IF NOT EXISTS
game (gamenumber STRING PRIMARY KEY,
status STRING,
starter STRING,
tokenplayer STRING,
deckontable STRING,
restcards STRING,
winner STRING);');
//gameuser(usernr,gamenumber,status,cards)
// IF NOT EXISTS
$db->exec('CREATE TABLE IF NOT EXISTS
gameuser (player STRING,
game STRING,
status STRING,
cards STRING,
ordernr INTEGER,
PRIMARY KEY (player, game));');
//player(ip,id,name,status)
$db->exec('CREATE TABLE IF NOT EXISTS
player (ip STRING PRIMARY KEY,
id STRING,
name STRING,
paasword STRING,
status STRING);');
//gamemove(game,player,cards,time)
$db->exec('CREATE TABLE IF NOT EXISTS
gamemove (game STRING,
player STRING,
time STRING,
cardsin STRING,
cardsout STRING,
PRIMARY KEY (game, player,time));');
CREATE TABLE "main"."commercial" ("title" STRING PRIMARY KEY NOT NULL , "firstline" STRING, "description" STRING, "picture" BLOB)
*/
require "notorm/NotORM.php";
//http://www.notorm.com/#api
require 'vendor/slim/slim/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
/*
*
*/
class CardApi extends \Slim\Slim
{
const ADMINPASSWORD = "CardApi";
private $db;
const INITIATED = 0;
const RUNNING = 1;
const ENDED = 2;
private static $GAME_STATE = ['initiated', 'running','ended'];
function gameState($i){
return self::$GAME_STATE[$i];
}
const PLAYING = 0;
const PASS = 1;
private static $PLAYER_STATE = ['playing', 'pass'];
function playerState($i){
return self::$PLAYER_STATE[$i];
}/*
* constructor for class
* initializes db.
*/
function __construct() {
parent::__construct();
$this->initDB();
}
/*
return result as JSON-object
*/
function returnResult($result){
$this->response()->header("Content-Type", "application/json");
echo json_encode($result);
}
/*
* send back error message in JSON
*/
function returnError($error){
$result=array("error"=>$error);
$this->response()->header("Content-Type", "application/json");
echo json_encode($result);
}
/*
* getter for db
*/
function getDB()
{
return $this->db;
}
/*
* initialize db to be used for storage in app
*/
function initDB()
{
$pdo = new PDO('sqlite:mysqlitedb.db');
$this->db = new NotORM($pdo);
//return $db;
}
/*
* remove cardnumber from cards
* return new cards
* if cardnumber not part of cards return false
*/
function removeFrom($cardnumber,$cards){
$arrcards=json_decode($cards);
$nr=count($arrcards);
for ($i = 0; $i < count($arrcards); ++$i) {
if ($arrcards[$i]==$cardnumber){$nr=$i;};
}
if ($nr==count($arrcards))return false;
array_splice($arrcards, $nr, 1);
return json_encode($arrcards);
}
/*
* add card to set of cards
*/
function addTo($cardnumber,$cards){
$arrcards=json_decode($cards);
if (!is_int ($cardnumber))$cardnumber=intval($cardnumber);
$arrcards[]=$cardnumber;
return json_encode($arrcards);
}
/*
* sets up state for next move
* if game is ended game endstate is set up.
*/
function nextMove($gamenr,$nr){
$findgame=$this->getDB()->game->where(array("gamenumber"=>$gamenr))->fetch();
$nr2=$this->getDB()->gameuser->where(array("game" => $gamenr))->max("ordernr");
$nr++;
if ($nr>$nr2)$nr=1;
$nr=strval($nr);
if($this->checkForEndGame($gamenr,$nr)){
$this->getDB()->game->insert_update(array("gamenumber"=>$gamenr), array(), array("status"=>$this->gameState(CardApi::ENDED)));
$this->getWinner($gamenr);
};
$result = $this->getDB()->game->insert_update(array("gamenumber"=>$gamenr), array(), array("tokenplayer"=>$nr));
}
/*
* returns true if current move is winning
* if winning status of game is updated in db
*/
function checkForWinning($gamenr,$cards){
$result = false;
$arrcards=json_decode($cards);
//if player has 31, then end game
if ($this->getValue($arrcards)==31){
$this->getDB()->game->insert_update(array("gamenumber"=>$gamenr), array(), array("status"=>$this->gameState(CardApi::ENDED)));
$this->getWinner($gamenr);
$result=true;
}
return $result;
}
/*
* check if game is ended.
* if player has passed, and gets token, then game is ended.
*/
function checkForEndGame($gamenr,$nr){
//if player has passed in previous, then end game
$finduser=$this->getDB()->gameuser->where(array("game" => $gamenr, "ordernr" => $nr))->fetch();
return ($finduser["status"]==$this->playerState(CardApi::PASS));
}
/*
* input: array of card-numbers
* returns: value for total of cards
*/
function getValue($cards){
$cardvalue=array();
for ($i=0;$i<count($cards);$i++){
$cardvalue[]=$this->getCard($cards[$i]);
}
$val=0;
for ($i=0;$i<4;$i++){
$hval=0;
for ($j=0;$j<count($cardvalue);$j++){
if($cardvalue[$j][0]==$i)$hval=$hval+$cardvalue[$j][1];
}
if ($hval>$val)$val=$hval;
}
if ($val<31)
if(count($cards)>0){
$equal=true;
for ($i=1;$i<count($cardvalue);$i++)
if (!($cardvalue[0][2]==$cardvalue[$i][2])) $equal=false;
if ($equal) $val=30.5;
}
return $val;
}
/*
* input: card-number
* returns: deck of card, and value in points
*/
function getCard($card) {
$fl=floor(($card-1) / 13);
//$rv = cardnumber inside harten/klaver/etc
$rv=(($card-1) % 13)+1;
//$rm = value of card when summed up
$rm=$rv;
if ($rm>10) $rm=10;
if ($rm==1) $rm=11;
return array($fl,$rm,$rv,$card);
}
/*
* calculates the winner if game is ended
*/
function getWinner($gamenr){
//get all players
$findusers=$this->getDB()->gameuser->where("game", $gamenr);
$userwin=null;
$max=0;
$values=array();
foreach ($findusers as $user) {
$cards=$user["cards"];
$val=$this->getValue(json_decode($cards));
if ($val>$max){
$max=$val;
$userwin=$user;
}
$values[]=array("player"=>$user["player"],"value"=>$val);
}
$ip1=$userwin["player"];
$this->getDB()->game->insert_update(array("gamenumber"=>$gamenr), array(), array("winner"=>$ip1));
return array("winner"=>$ip1,"winningvalue"=>$max,"data"=>$values);
}
/*
* add move to gamemove table
*/
function addMove($game,$player,$time,$cardsin,$cardsout){
$newmoveuser=array(
"game" => $game,
"player" => $player,
"time" => $time,
"cardsin" => $cardsin,
"cardsout" => $cardsout
);
return $this->getDB()->gamemove->insert($newmoveuser);
}
/*
* check if player has token for this game
* If so, return player , game-instance and token
* if not, generate error messages, and return false;
*/
function checkgameplayertoken($ip, $gamenr,$status,$checkToken){
$findgame=$this->getDB()->game->where(array("gamenumber"=>$gamenr,"status"=>$status))->fetch();
$result="0";
if ($findgame){
$token=$findgame["tokenplayer"];
if($checkToken)
$finduser=$this->getDB()->gameuser->where(array("game" => $gamenr, "player" => $ip, "ordernr" => $token))->fetch();
else
$finduser=$this->getDB()->gameuser->where(array("game" => $gamenr, "player" => $ip))->fetch();
if($checkToken)
if (!($token==$finduser["ordernr"])){$this->returnError("player $ip does not have token");return false;}
} else {$this->returnError("$gamenr not defined or not $status");return false;}
return array("findgame"=>$findgame,"finduser"=>$finduser,"token"=>$token);
}
/*
* check if player has token for game that is running
*/
function checkgameplayertokenRunning($ip, $gamenr){
return $this->checkgameplayertoken($ip, $gamenr,$this->gameState(CardApi::RUNNING),true);
}
/*
* check if password belongs to player with ip
*/
function identifyPlayer($ip){
$password=$this->request()->post('password');
$identifyplayer=$this->getDB()->player->where(array("ip"=>$ip,"password"=>$password));
if (count($identifyplayer)==0){$this->returnError("player $ip unknown or password incorrect");return;}
return true;
}
function identifyAdmin(){
$password=$this->request()->post('password');
//var_dump($password);
$identifyplayer=$this->getDB()->player->where(array("ip"=>"admin","password"=>$password));
$error=false;
if (count($identifyplayer)==0){
//no admin-password set yet
//check for default admin-password
$identifyplayer=$this->getDB()->player->where(array("ip"=>"admin"));
if (count($identifyplayer)==0){
if (!($password==CardApi::ADMINPASSWORD))
$error=true;
} else $error=true;//admin with wrong password
}
if ($error){$this->returnError("player admin unknown or password ($password) incorrect");}
return !$error;
}
function createTable($pdo,$table,$fields){
$query="DROP TABLE IF EXISTS $table;CREATE TABLE $table ($fields);";
return $pdo->exec($query);
}
}//end class CardApi
// create new Slim instance
$app = new CardApi();
//start services
// add new Routes
//identify(ip,naam)
//test with curl:
//curl -X POST http://127.0.0.1/anton/cardapi/identify/myip/anton
//of
//curl -H "Content-Type: application/json" -X POST -d '{"username":"xyz","password":"xyz"}' http://127.0.0.1/anton/cardapi/players/myip/add/hans
$app->post('/players/:ip/add/:naam',function ($ip,$naam) use ($app) {
$findplayer=$app->getDB()->player->where("ip", $ip);
$password=$app->request()->post('password');
if (count($findplayer)>0){
$players = array();
foreach ($findplayer as $player) {
$players[] = array(
"id" => $player["id"],
"ip" => $player["ip"],
"name" => $player["name"],
"status" => $player["status"]
);
}
} else {
$id=$_SERVER['REMOTE_ADDR'];
$status='ok';
$newplayer=array(
"id" => $id, // omit or null for auto_increment
"ip" => $ip,
"name" => $naam,
"status" => $status,
"password" => $password
);
$result = $app->getDB()->player->insert($newplayer);
$players=$newplayer;
}
$app->returnResult(array(
"player" => $players));
$db=null;
});
//validate if player with ip has password
$app->post('/players/:ip/validate',function ($ip) use ($app) {
if (!$app->identifyPlayer($ip)) return;
$app->returnResult(array(
"result" => "ok"));
$db=null;
});
//curl -X POST --data "password=p3" http://192.168.2.8/CardApi/games/n132/initiate
$app->post('/games/:ip/initiate' ,function ($ip) use ($app) {
if (!$app->identifyPlayer($ip)) return;
$nr=$app->getDB()->game->max("gamenumber");
$status=$app->gameState(CardApi::INITIATED);//'initiated';
$cards=array();
for ($j=0;$j<4;$j++){
$cards[]=$j*13+1;//cards 2-6 are not dealt.
for ($i=6;$i<13;$i++)$cards[]=$i+$j*13+1;
}
$newgame=array(
"gamenumber" => $nr+1,
"starter" => $ip,
"tokenplayer" => 1,
"status" => $status,
"restcards" => json_encode($cards),
"deckontable" => json_encode(array())
);
$result = $app->getDB()->game->insert($newgame);
//gameuser(usernr,gamenumber,ordernr,status)
$newgameuser=array(
"game" => $nr+1,
"player" => $ip,
"ordernr" => 1,
"status" => $status,
"cards" => json_encode(array())
);
$result2 = $app->getDB()->gameuser->insert($newgameuser);
$app->returnResult(array(
"result" => $result));
});
//curl -X GET http://127.0.0.1/anton/cardapi/games/myip/starting
$app->get('/games/:ip/starting',function ($ip) use ($app) {
$findgames=$app->getDB()->game->where("status", $app->gameState(CardApi::INITIATED));
if (count($findgames)>0){
$games = array();
foreach ($findgames as $game) {
$games[] = array(
"id" => $game["gamenumber"],
"player" => $game["starter"]
);
}
$app->returnResult(array(
"games" => $games));
} else $app->returnError("no games defined yet");return;
});
$app->get('/games/:ip/all',function ($ip) use ($app) {
//game (gamenumber ,status,starter
$findgames=$app->getDB()->game();
if (count($findgames)>0){
$games = array();
foreach ($findgames as $game) {
$games[] = array(
"starter" => $game["starter"],
"gamenumber" => $game["gamenumber"],
"status" => $game["status"]
);
}
$app->returnResult(array(
"games" => $games));
} else $app->returnError("no games defined yet");return;
});
//returns list of ip for all players who have applied for a game
//curl -X GET http://127.0.0.1/anton/cardapi/initiategame/myip2
$app->get('/games/:ip/:gamenr/players',function ($ip, $gamenr) use ($app) {
$findplayer=$app->getDB()->gameuser->where("game", $gamenr);
if (count($findplayer)==0){$app->returnError("no player for game $gamenr");return;}
//TODO: if sqlite, findplayer is in order of addition
//if mysql, they are ordered by name
$players=array();
foreach ($findplayer as $player) {
$players[]=$player["player"];//gameuser (player ,game,status,cards,ordernr INTEGER,
}
$app->returnResult(array(
"players" => $players));
});
//returns all players with ordernr for one game
$app->get('/games/:ip/:gamenr/playersadv',function ($ip, $gamenr) use ($app) {
$findplayer=$app->getDB()->gameuser->where("game", $gamenr);
if (count($findplayer)==0){$app->returnError("no player for game $gamenr");return;}
$players=array();
foreach ($findplayer as $player) {
$players[]=array(//gameuser (player ,game,status,cards,ordernr INTEGER,
"ordernr" => $player["ordernr"],
"player" => $player["player"]
);
}
$app->returnResult(array(
"players" => $players));
});
//returns name of ipplayer if ip is known to system, otherwise error
$app->get('/players/:ip/:ipplayer/name',function ($ip, $ipplayer) use ($app) {
$findplayer=$app->getDB()->player->where("ip", $ipplayer);
if (count($findplayer)==0){$app->returnError("no player $ipplayer");return;}
foreach ($findplayer as $player) {
$result=$player["name"];
}
$app->returnResult(array(
"name" => $result));
});
//returns 1 if game still starting, and not full, and ip has not applied for this game yet. Otherwise 0.
//player applies for game
$app->post('/games/:gamenr/apply/:ip',function ($ip, $gamenr) use ($app) {
//check if user exists
if (!$app->identifyPlayer($ip)) return;
//check if game already initated
$findgame=$app->getDB()->game->where("gamenumber",$gamenr);//CardApi::INITIATED
$result="";
if (count($findgame)>0){
$error=false;
foreach ($findgame as $game) {
if (!(CardApi::INITIATED==$game["status"])) $error=true;
}
if ($error){$app->returnError("game $gamenr not defined");return;}
} else {$app->returnError("game $gamenr not defined");return;}
$findusers=$app->getDB()->gameuser->where(array("game" => $gamenr));
if (!(count($findusers)>0)){$app->returnError("game $gamenr not initiated yet");return;}
//check if user not already applied for this game
$findusers=$app->getDB()->gameuser->where(array("game" => $gamenr, "player" => $ip))->fetch();
if ((count($findusers)>1)){$app->returnError("$ip already part of game $gamenr");return;}
$nr=$app->getDB()->gameuser->where(array("game" => $gamenr))->max("ordernr");
if ($nr+1>6){$app->returnError("game $gamenr maximum number of players (6) exceeded");return;}//maximum (52-4*6)/3-1 players
$status=$app->gameState(CardApi::PLAYING);//'initiated';
$newgameuser=array(
"game" => $gamenr,
"player" => $ip,
"ordernr" => $nr+1,
"status" => $status,
"cards" => json_encode(array())
);
$result2 = $app->getDB()->gameuser->insert($newgameuser);
$app->returnResult(array(
"result" => 1));
});
/*
$findgame=$app->getDB()->game->where("gamenumber",$gamenr);//CardApi::INITIATED
$mysterycard=0;
if (count($findgame)>0){
foreach ($findgame as $game) {
$mysterycard=$game["mysterycard"];
}
} else {$app->returnError("game $gamenr not defined");return;}
if ($mysterycard==0){$app->returnError("no mysterycard found in game $gamenr");return;}
$result=$app->getDB()->game->insert_update(array("gamenumber"=>$gamenr), array(), array("mysterycard"=>$cardnumber));
*/
$app->post('/games/:ip/:gamenr/play/mysterycard/:cardnumber',function ($ip, $gamenr, $cardnumber) use ($app) {
if (!$app->identifyPlayer($ip)) return;
$gameplayer=$app->checkgameplayertokenRunning($ip, $gamenr);
if (!$gameplayer)return;
$cards=$gameplayer["finduser"]["cards"];
$cards=$app->removeFrom($cardnumber,$cards);
if (!$cards){$app->returnError("$cardnumber not part of cards of player");return;}
//get mystery card
$findgame=$app->getDB()->game->where("gamenumber",$gamenr);//CardApi::INITIATED
$mysterycard=0;
if (count($findgame)>0){
foreach ($findgame as $game) {
$mysterycard=$game["mysterycard"];
}
} else {$app->returnError("game $gamenr not defined");return;}
if ($mysterycard==0){$app->returnError("no mysterycard found in game $gamenr");return;}
//store new mysterycard in db
$result=$app->getDB()->game->insert_update(array("gamenumber"=>$gamenr), array(), array("mysterycard"=>$cardnumber));
//and now add old mysterycard to player card, and send it back
$cards=$app->addTo($mysterycard,$cards);
$app->getDB()->gameuser->insert_update(array("player"=>$gameplayer["finduser"]["player"],"game"=>$gameplayer["finduser"]["game"]), array(), array("cards"=>$cards));
$winning="continue";
if (!$app->checkForWinning($gamenr,$cards))
$app->nextMove($gamenr,$gameplayer["token"]);
else $winning="winning";
$app->addMove($gamenr,$ip,date('Y-m-d H:i:s'),"[]","[]");
$result = 1;
$app->returnResult(array(
"result" => $result,"mysterycard"=>$mysterycard,"cards"=>$cards,"winning"=>$winning,"value"=>$app->getValue(json_decode($cards))));
});
//initiate mystery card.
//can only be initiated by the player who has initiated and started the game
//game needs to be running
$app->post('/games/:ip/:gamenr/initiatemysterycard',function ($ip, $gamenr) use ($app) {
if (!$app->identifyPlayer($ip)) return;
$gameplayer=$app->checkgameplayertoken($ip, $gamenr,$app->gameState(CardApi::RUNNING),true);
if (!$gameplayer){$app->returnError("game $gamenr not running");return;}
if (!($gameplayer["token"]==1)){$app->returnError("$ip has not initiated and started game $gamenr");return;}
$cards=$gameplayer["findgame"]["restcards"];
$cardnumber=0;
$mycards=json_decode($cards);
$number=rand ( 0 , count($mycards)-1 );
$cardnumber=$mycards[$number];
$playercards[]=$cardnumber;
$cards=$app->removeFrom($cardnumber,$cards);
$result=$app->getDB()->game->insert_update(array("gamenumber"=>$gamenr), array(), array("mysterycard"=>$cardnumber));
$app->returnResult(array(
"result" => 1));
});
//returns 1 if game is started, 0 if ip has not initiated game or no players yet
//player starts game
//curl -X POST --data "password=p3" http://192.168.2.8/CardApi/games/n132/14/start
$app->post('/games/:ip/:gamenr/start',function ($ip, $gamenr) use ($app) {
if (!$app->identifyPlayer($ip)) return;
$gameplayer=$app->checkgameplayertoken($ip, $gamenr,$app->gameState(CardApi::INITIATED),true);
if (!$gameplayer)return;
if (!($gameplayer["token"]==1)){$app->returnError("$ip has not initiated game $gamenr");return;}
//get all players
$findusers=$app->getDB()->gameuser->where("game", $gamenr);
//for all players: give them three cards
$cards=$gameplayer["findgame"]["restcards"];
//var_dump($findusers);
$startercards="";
$status=$app->gameState(CardApi::RUNNING);
foreach ($findusers as $user) {
$playercards=array();
for ($j=1;$j<4;$j++){
$mycards=json_decode($cards);
$number=rand ( 0 , count($mycards)-1 );
$cardnumber=$mycards[$number];
$playercards[]=$cardnumber;
$cards=$app->removeFrom($cardnumber,$cards);
}
//save $playercards to db
if($user["player"]==$ip) $startercards=json_encode($playercards);
$app->getDB()->gameuser->insert_update(array("player"=>$user["player"],"game"=>$user["game"]), array(), array("cards"=>json_encode($playercards)));
//check for every user if it is 31
if($app->checkForWinning($gamenr,json_encode($playercards))) $status=$app->gameState(CardApi::ENDED);
}
//give the table cards, and save it in game
$deckcards=array();
for ($j=1;$j<4;$j++){
$mycards=json_decode($cards);
$number=rand ( 0 , count($mycards)-1 );
$cardnumber=$mycards[$number];
$deckcards[]=$cardnumber;
$cards=$app->removeFrom($cardnumber,$cards);
}
//set token = 1 in game, and status=running
$result=$app->getDB()->game->insert_update(array("gamenumber"=>$gamenr), array(), array("deckontable"=>json_encode($deckcards),"restcards"=>$cards,"tokenplayer"=>1,
"status"=>$status));
$app->checkForWinning($gamenr,$startercards);
$app->nextMove($gamenr,0);//check if there is a winner already
$app->returnResult(array(
"result" => 1));
});
//returns the ip which has the token for the game, error if game not started yet etc.
//get player-id who has token for game
$app->get('/games/:ip/:gamenr/token',function ($ip, $gamenr) use ($app) {
$findgame=$app->getDB()->game->where("gamenumber", $gamenr);
if (count($findgame)==0){$app->returnError("no game $gamenr");return;}
foreach ($findgame as $game) {
$result=$game["tokenplayer"];
}
$app->returnResult(array(
"token" => $result));
});
//returns the cards a player has (array of cardnumbers) game is still playing, 0 otherwise
$app->post('/games/:ip/:gamenr/getcards',function ($ip, $gamenr) use ($app) {
if (!$app->identifyPlayer($ip)) return;
$gameuser=$app->getDB()->gameuser->where(array("player"=>$ip,"game"=>$gamenr));
if (!(count($gameuser)>0)){$app->returnError("player $ip not part of game $gamenr");return;}
$cards="nothing";
foreach ($gameuser as $user) {
$cards=$user["cards"];
}
$app->returnResult(array(
"cards" => $cards));
});
/*//returns cardnumber which player gets if player has token, 0 otherwise
$app->get('/getcard/:ip/:gamenr',function ($ip, $gamenr) use ($app) {
});*/
//returns 1 if ip has token, 0 otherwise.
//swaps $cardnumberin for $cardnumberout
//move player: exchange one card for another
$app->post('/games/:ip/:gamenr/play/move/:cardnumberin/:carnumberout',function ($ip, $gamenr, $cardnumberin,$cardnumberout) use ($app) {
if (!$app->identifyPlayer($ip)) return;
$gameplayer=$app->checkgameplayertokenRunning($ip, $gamenr);
if (!$gameplayer)return;
$cards=$gameplayer["finduser"]["cards"];
$cards=$app->removeFrom($cardnumberout,$cards);
if (!$cards){$app->returnError("$cardnumberout not part of cards of player");return;}
$cardsontable=$app->removeFrom($cardnumberin,$gameplayer["findgame"]["deckontable"]);
if (!$cardsontable){$app->returnError("$cardnumberin not part of deckontable");return;}
$cards=$app->addTo($cardnumberin,$cards);
$cardsontable=$app->addTo($cardnumberout,$cardsontable);
$app->getDB()->gameuser->insert_update(array("player"=>$gameplayer["finduser"]["player"],"game"=>$gameplayer["finduser"]["game"]), array(), array("cards"=>$cards));
$app->getDB()->game->insert_update(array("gamenumber"=>$gamenr), array(), array("deckontable"=>$cardsontable));
$winning="continue";
if (!$app->checkForWinning($gamenr,$cards))
$app->nextMove($gamenr,$gameplayer["token"]);
else $winning="winning";
$app->addMove($gamenr,$ip,date('Y-m-d H:i:s'),json_encode(array(intval ($cardnumberin))),json_encode(array(intval ($cardnumberout))));
$result = 1;
$app->returnResult(array(
"result" => $result,"cards"=>$cards,"winning"=>$winning,"value"=>$app->getValue(json_decode($cards))));
});
//-getmoves(ip,ipplayer,gamenr) get
//return moves of player
$app->get('/games/:ip/:gamenr/moves/:ipplayer',function ($ip, $gamenr, $ipplayer) use ($app) {
$findmoves=$app->getDB()->gamemove->where(array("game"=>$gamenr,"player"=>$ipplayer));
if (count($findmoves)==0){$app->returnError("player $ipplayer not part of game $gamenr");return;}
$moves=array();
foreach ($findmoves as $move) {
$moves[]=array("cardsin"=>$move["cardsin"],"cardsout"=>$move["cardsout"]);
}
$app->returnResult(array(
"moves" => $moves));
});
//-getdeckontable(ip,gamenr) get
//returns list of cardnumbers lying open to see
$app->get('/games/:ip/:gamenr/deck',function ($ip, $gamenr) use ($app) {
$findgame=$app->getDB()->game->where(array("gamenumber"=>$gamenr));
if (count($findgame)==0){$app->returnError("no game $gamenr");return;}
foreach ($findgame as $game) {
$result=$game["deckontable"];
}
$app->returnResult(array(
"cards" => $result));
});
//-swapcards(ip,gamenr) post
//returns list of cards lying on table if player has token, otherwise error
//move player: swap cards
$app->post('/games/:ip/:gamenr/play/swap',function ($ip, $gamenr) use ($app) {
if (!$app->identifyPlayer($ip)) return;
$result="0";
$gameplayer=$app->checkgameplayertokenRunning($ip, $gamenr);
if (!$gameplayer)return;
$cardsontable=$gameplayer["finduser"]["cards"];
$cards=$gameplayer["findgame"]["deckontable"];
$app->getDB()->gameuser->insert_update(array("player"=>$gameplayer["finduser"]["player"],"game"=>$gameplayer["finduser"]["game"]), array(), array("cards"=>$cards,"status"=>$app->playerState(CardApi::PASS)));
$app->getDB()->game->insert_update(array("gamenumber"=>$gamenr), array(), array("deckontable"=>$cardsontable));
$winning="continue";
if (!$app->checkForWinning($gamenr,$cards))
$app->nextMove($gamenr,$gameplayer["token"]);
else $winning="winning";
$app->addMove($gamenr,$ip,date('Y-m-d H:i:s'),$cards,$cardsontable);
$result=$cards;
$app->returnResult(array(
"cards" => $result,"cards"=>$cards,"winning"=>$winning,"value"=>$app->getValue(json_decode($cards))));
});
//-offerpass(ip,gamenr) post
//returns 1 if player has token, error otherwise
//move player: pass
$app->post('/games/:ip/:gamenr/play/pass',function ($ip, $gamenr) use ($app) {
if (!$app->identifyPlayer($ip)) return;
$result="0";
$gameplayer=$app->checkgameplayertokenRunning($ip, $gamenr);
if (!$gameplayer)return;
//get number of players
$players=$app->getDB()->gameuser->where(array("game" => $gamenr));
$numberOfPlayers=count($players);
//get number of moves
$moves=$app->getDB()->gamemove->where(array("game"=>$gamenr));
$numberOfMoves=count($moves);
//if number of moves < number of players: illegal move
if ($numberOfMoves<$numberOfPlayers){$app->returnError("number of moves ($numberOfMoves) must not be smaller than number of players ($numberOfPlayers)");return;}
$app->getDB()->gameuser->insert_update(array("player"=>$gameplayer["finduser"]["player"],"game"=>$gameplayer["finduser"]["game"]), array(), array("status"=>$app->playerState(CardApi::PASS)));
//cards not changed, so always continue with next move
$app->nextMove($gamenr,$gameplayer["token"]);
$app->addMove($gamenr,$ip,date('Y-m-d H:i:s'),json_encode(array()),json_encode(array()));
$result=1;
$app->returnResult(array(
"result" => $result));
});
//-claimwin(ip,gamenr) post
//returns 1 if player has won, and has token. error otherwise
//player can check if game is won. is same as getresultgame, except that this can only be claimed by a player of the game itself.
$app->post('/games/:ip/:gamenr/claimwin',function ($ip, $gamenr) use ($app) {
if (!$app->identifyPlayer($ip)) return;
$gameplayer=$app->checkgameplayertoken($ip, $gamenr,$app->gameState(CardApi::ENDED),true);
if (!$gameplayer)return;
$cards=$gameplayer["finduser"]["cards"];
if (!$app->checkForWinning($gamenr,$cards)){$app->returnError("No 31, you only have $val points");return;}
//get all players
$app->returnResult($app->getWinner($gamenr));//checkForWinning($gamenr,$cards)
});
//get finalresults
//returns winner and results for each player if game is ended
$app->get('/games/:ip/:gamenr/finalresults',function ($ip, $gamenr) use ($app) {
$findgame=$app->getDB()->game->
where(array("gamenumber" => $gamenr,"status"=>$app->gameState(CardApi::ENDED)));
if (count($findgame)==0){$app->returnError("game $gamenr not ended or unknown ");return;}
$findusers=$app->getDB()->gameuser->where("game", $gamenr);
$userwin=null;
$max=0;
$players=array();
foreach ($findusers as $user) {
$cards=$user["cards"];
$val=$app->getValue(json_decode($cards));
if ($val>$max){
$max=$val;
$userwin=$user;
}
$players[]=array("player"=>$user["player"],"cards"=>$cards,"handvalue"=>$val);
}
$app->returnResult(array("winner"=>$userwin,"results"=>$players));
});
//-getstategame(ip,gamenr) get
//returns one of: initiated,started,ended
$app->get('/games/:ip/:gamenr/state',function ($ip, $gamenr) use ($app) {
$findgame=$app->getDB()->game->where("gamenumber",$gamenr);//CardApi::INITIATED
$result="";
if (count($findgame)>0){
foreach ($findgame as $game) {
$result=$game["status"];
}
} else {$app->returnError("game $gamenr not defined");return;}
$app->returnResult(array(
"status" => $result));
});
//-getresultgame(ip,gamenr, ipplayer) get
//returns list of cards for ipplayer if game is ended.
$app->get('/games/:ip/:gamenr/cards/:ipplayer',function ($ip, $gamenr, $ipplayer) use ($app) {
$gameplayer=$app->checkgameplayertoken($ipplayer, $gamenr,$app->gameState(CardApi::ENDED),false);
if (!$gameplayer){return;};
//echo "player cards can be shown!";
$cards=$gameplayer["finduser"]["cards"];
$app->returnResult($gameplayer["finduser"]);
});
//-getwinnergame(ip,gamenr) get
//returns ip of winning player if game is ended
$app->get('/games/:ip/:gamenr/winner',function ($ip, $gamenr) use ($app) {
$findgame=$app->getDB()->game->where("gamenumber",$gamenr);
$winner = array("winner" => "none");
if (count($findgame)>0){
foreach ($findgame as $game) {
if ($game["status"]==$app->gameState(CardApi::ENDED))
$winner = array(
"winner" => $game["winner"]
);
}
}
$app->returnResult($winner);
});
//getvalue
//returns value of card. in: cardnumber
$app->get('/cards/:cards/value',function ($cards) use ($app) {
$parts = explode(",", $cards);
$val=$app->getValue($parts);
$app->returnResult(array(
"value" => $val));
});
//commercials
//returns title, first line, description and png.
//end services
$app->get('/commercials/:title',function ($title) use ($app) {
$commercials = $app->getDB()->commercial->where("title",$title);
$result=array();
if (count($commercials)>0){
foreach ($commercials as $commercial) {
$result = array(
"title" => $commercial["title"],
"firstline" => $commercial["firstline"],
"description" => $commercial["description"],
"picture" => $commercial["picture"],
);
}
} else {$app->returnError("no commercials with title $title defined");return;}
$app->returnResult(array(
"commercial" => $result));
});
$app->get('/games/:ip/numberofmoves',function ($ip) use ($app) {
$findmoves=$app->getDB()->gamemove->select("game");
if (count($findmoves)==0){$app->returnError("no moves available");return;}
$moves=array();
foreach ($findmoves as $move) {
if(isset ($moves[$move["game"]]))
$moves[$move["game"]]=$moves[$move["game"]]+1;
else
$moves[$move["game"]]=1;//one occurrence at least
}
$result=array();
foreach ($moves as $key => $number) {
$result[]=array($key,$number);
}
$result=countFrequency2($result);
$app->returnResult(array(
"result" => $result));
});
function countFrequency($games){
$winners=array();
foreach ($games as $game) {
if(isset ($winners[$game[1]]))
$winners[$game[1]]++;
else
$winners[$game[1]]=1;
}
//convert winners to array
$result=array();
foreach ($winners as $key=>$value) {
$result[]=array($key=>$value);
}
return $result;
}
function countFrequency2($games){
$winners=array();
foreach ($games as $game) {
if(isset ($winners[$game[1]]))
$winners[$game[1]]++;
else
$winners[$game[1]]=1;
}
//convert winners to array
$result=array();
foreach ($winners as $key=>$value) {
$result[]=array($key,$value);
}
return $result;
}
$app->get('/games/:ip/gametotals',function ($ip) use ($app) {
$findgame=$app->getDB()->game;//CardApi::INITIATED
$games=array();
if (count($findgame)>0){
foreach ($findgame as $game) {
if(!is_null ($game["winner"])){
$findusers=$app->getDB()->gameuser->where(array("game"=>$game["gamenumber"],"player"=>$game["winner"]));
foreach ($findusers as $user) {
$cards=$user["cards"];
$val=$app->getValue(json_decode($cards));
$games[]=array($game["gamenumber"],$val);
}
}
}
$result=countFrequency2($games);
} else {$app->returnError("no games available");return;}
$app->returnResult(array(
"result" => $result));
});
$app->get('/games/:ip/numplayers',function ($ip) use ($app) {
$findgame=$app->getDB()->game;//CardApi::INITIATED
$games=array();
if (count($findgame)>0){
foreach ($findgame as $game) {
$findusers=$app->getDB()->gameuser->where(array("game"=>$game["gamenumber"]));
$num=0;
foreach ($findusers as $user) {
$num=$num+1;
}
if($num>1)
$games[]=array($game["gamenumber"],$num);//no game for 1 player
}
$result=countFrequency($games);
} else {$app->returnError("no games available");return;}
$app->returnResult(array(
"result" => $result));
});
$app->get('/games/:ip/numplayers1',function ($ip) use ($app) {
$findgame=$app->getDB()->game;//CardApi::INITIATED
$games=array();
if (count($findgame)>0){
foreach ($findgame as $game) {
$findusers=$app->getDB()->gameuser->where(array("game"=>$game["gamenumber"]));
$num=0;
foreach ($findusers as $user) {
$num=$num+1;
}
if($num>1)
$games[]=array($game["gamenumber"],$num);//no game for 1 player
}
$result=countFrequency2($games);
} else {$app->returnError("no games available");return;}
$app->returnResult(array(
"result" => $result));
});
$app->get('/games/:ip/gamewinners',function ($ip) use ($app) {
$findgame=$app->getDB()->game;//CardApi::INITIATED
$games=array();
if (count($findgame)>0){
foreach ($findgame as $game) {
if(!is_null ($game["winner"]))
$games[]=array($game["gamenumber"],$game["winner"]);
}
$result=countFrequency2($games);
} else {$app->returnError("no games available");return;}
$app->returnResult(array(
"result" => $result));
});
//commercials
$app->get('/commercials',function () use ($app) {
$commercials = $app->getDB()->commercial->select("title");
$result=array();
if (count($commercials)>0){
$result=array();
foreach ($commercials as $commercial) {
$result[] = array(
"title" => $commercial["title"]
);
}
} else {$app->returnError("no commercials defined");return;}
$app->returnResult(array(
"commercials" => $result));
});
//delete game
//deletes all items for a game
//available for user admin
//curl -X DELETE --data "password=CardApi" http://127.0.0.1/anton/cardapi/players/1230
$app->delete('/players/:ip', function ($ip) use ($app) {
//Delete player identified by $id
if (!$app->identifyAdmin()) return;
$app->getDB()->gamemove->where("player",$ip)->delete();
$app->getDB()->gameuser->where("player",$ip)->delete();
$result=$app->getDB()->player->where("ip",$ip)->delete();
$app->returnResult(array(
"result" => $result));
});
//curl -X POST --data "password=CardApi" http://127.0.0.1/anton/cardapi/db/create
$app->post('/db/create', function () use ($app) {
//Delete player identified by $id
if (!$app->identifyAdmin()) return;
$pdo = new PDO('sqlite:mysqlitedb.db');
//$file_db = new PDO('sqlite:mysqlitedb.db');
$app->createTable($pdo,"player", "ip STRING PRIMARY KEY,id STRING,name STRING,status STRING, password STRING, datafield STRING");
$app->createTable($pdo,"gameuser", "player STRING,game STRING,status STRING,cards STRING,ordernr INTEGER,PRIMARY KEY (player, game)");
$app->createTable($pdo,"gamemove", "game STRING,player STRING,time STRING,cardsin STRING,cardsout STRING,PRIMARY KEY (game, player,time)");
$app->createTable($pdo,"game", "gamenumber STRING PRIMARY KEY,status STRING,starter STRING,tokenplayer STRING,deckontable STRING,restcards STRING,winner STRING, mysterycard INTEGER");
$app->createTable($pdo,"commercial", "title STRING PRIMARY KEY NOT NULL , firstline STRING, description STRING, picture BLOB");