You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

73 lines
1.7 KiB

  1. /*
  2. * Othello engine.
  3. *
  4. * This program keeps track of the current state of the board and renders it
  5. * appropriately. It calls the respective players, validates and implements
  6. * their moves. It furthermore keeps track of the players' move time limits.
  7. */
  8. #include <cstdio>
  9. #include <cassert>
  10. #include <cstdlib>
  11. #include <cstring>
  12. #include <sys/types.h> // mode_t
  13. #include <sys/stat.h> // mkfifo()
  14. #include <unistd.h> // unlink(), fork()
  15. #include <signal.h> // signal()
  16. #include "board.h"
  17. #include "mcp.h"
  18. bool serialize_state(int fd, const game_state *state) { return state->dump_to_fd(fd); }
  19. void initialize_state(game_state *state, char const *init)
  20. {
  21. if (init[0] == 'O')
  22. state->player(0);
  23. else
  24. state->player(1);
  25. for (unsigned r = 0; r < state->rows(); ++r) {
  26. for (unsigned c = 0; c < state->columns(); ++c) {
  27. char field = init[r * state->columns() + c + 1];
  28. FieldType t;
  29. switch(field) {
  30. case '.': t = EMPTY; break;
  31. case 'O': t = PLAYER_1; break;
  32. case 'X': t = PLAYER_2; break;
  33. default: t = OUT_OF_BOUNDS; break;
  34. }
  35. state->set(r+1,c+1,t);
  36. }
  37. }
  38. }
  39. bool is_final_state(game_state const *state) { return state->finished(); }
  40. bool deserialize_move(int fd, game_move *move)
  41. {
  42. char buf[128];
  43. memset(buf,0,128);
  44. ssize_t r = read(fd, buf, 128);
  45. if (r != 3) return false;
  46. int res = sscanf(buf, "%u,%u", &move->row, &move->col);
  47. if (res != 2) return false;
  48. return true;
  49. }
  50. bool apply_move(game_state *state,
  51. const game_move *move)
  52. {
  53. // skip move only if it's really impossible
  54. if ((move->row == 0) &&
  55. (move->col == 0) &&
  56. !state->can_move()) {
  57. state->skipped();
  58. return true;
  59. }
  60. return state->move(move->row, move->col);
  61. }