Guest User

Untitled

a guest
Dec 14th, 2017
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.35 KB | None | 0 0
  1. <table>
  2. <?php
  3. //Determine if a player as aligned three of its symbols and return the id of the player (1
  4. //for X Player, -1 for O Player(Computer)). Otherwise return 0;
  5. function isWinState($board){
  6. $winning_sequences = '012345678036147258048642';
  7. for($i=0;$i<=21;$i+=3){
  8. $player = $board[$winning_sequences[$i]];
  9. if($player == $board[$winning_sequences[$i+1]]){
  10. if($player == $board[$winning_sequences[$i+2]]){
  11. if($player!=0){
  12. return $player;
  13. }
  14. }
  15. }
  16. }
  17. return 0;
  18. }
  19.  
  20. //Player O plays its turn at random
  21. function OsTurn($board){
  22. if(in_array(0,$board)){
  23. $i = mt_rand(0,8);
  24. while($board[$i]!=0){
  25. $i = mt_rand(0,8);
  26. }
  27. $board[$i]=-1;
  28. }
  29. return $board;
  30. }
  31.  
  32. $winstate = 0;
  33. $values = array();
  34.  
  35. if(empty($_GET['values'])){
  36. //initializing the board
  37. $values = array_fill(0,9,0);
  38. //determine who begins at random
  39. if(mt_rand(0,1)){
  40. $values = OsTurn($values);
  41. }
  42. }else{
  43. //get the board
  44. $values = explode(',',$_GET['values']);
  45. //Check if a player X won, if not, player 0 plays its turn.
  46. $winstate = isWinState($values);
  47. if($winstate==0){
  48. $values = OsTurn($values);
  49. }
  50. //Check if a player 0 won
  51. $winstate = isWinState($values);
  52. }
  53. //Display the board as a table
  54. for($i=0;$i<9;$i++){
  55. //begin of a row
  56. if(fmod($i,3)==0){echo '<tr>';}
  57. echo '<td>';
  58. //representation of the player token, depending on the ID
  59. if($values[$i]==1){
  60. echo 'X';
  61. }else if($values[$i]==-1){
  62. echo 'O';
  63. }else{
  64. //If noone put a token on this, and if noone won, make a link to allow player X to
  65. //put its token here. Otherwise, empty space.
  66. if($winstate==0){
  67. $values_link = $values;
  68. $values_link[$i]=1;
  69. echo '<a href="tictactoe.php?values='.implode(',',$values_link).'">&nbsp;</a>';
  70. }else{
  71. echo '&nbsp;';
  72. }
  73. }
  74. echo '</td>';
  75. //end of a row
  76. if(fmod($i,3)==2){echo '</tr>';}
  77. }
  78. ?>
  79. </table>
  80. <?php
  81. //If someone won, display the message
  82. if($winstate!=0){
  83. echo '<p><b>Player '.(($winstate==1)?'X':'O').' won!</b></p>';
  84. }
  85. ?>
  86.  
  87. switch ($aiLevel) {
  88. case 1: $values = $OsTurn($values);
  89. case 2: $values = $betterAi($values);
  90. case 3: $values = $unbeatableAi($values);
  91. }
Add Comment
Please, Sign In to add comment