From 86c97ead9944fc3625d54c54a6860231fc620e82 Mon Sep 17 00:00:00 2001 From: Laurent Mazet Date: Sat, 1 Jun 2024 22:56:37 +0200 Subject: [PATCH] cleaning --- battleships.c | 36 ++++++++++++++++++------------------ board.c | 14 +++++++------- board.h | 2 +- 3 files changed, 26 insertions(+), 26 deletions(-) diff --git a/battleships.c b/battleships.c index 799b9a2..2c570fe 100644 --- a/battleships.c +++ b/battleships.c @@ -31,6 +31,20 @@ int usage (int ret) return ret; } +/* stop loop */ +int stoploop (void) +{ + int stop = 0; + while (!stop) { + switch (getch ()) { + case KEY_ESC: + case 'q': + stop = 1; + } + } + return stop; +} + /* main function */ int main (int argc, char *argv[]) { @@ -207,9 +221,7 @@ int main (int argc, char *argv[]) } } } else { - char symb = (testlocation (boardcomputer, 1, x, y, orient, " ")) ? 'O' : 'X'; - putlocation (boardcomputer, 1, x, y, orient, symb); - if (symb == 'X') { + if (drawbomb (boardcomputer, x, y)) { displaylogs ("Computer ship hited", wlogs, hlogs, xlogs, ylogs); } if (!findlocation (boardcomputer, 1, &x, &y, &orient, " S")) { @@ -220,31 +232,19 @@ int main (int argc, char *argv[]) displayboard (boardhuman, xhuman, yhuman, mode, 1); displayboard (boardcomputer, xcomputer, ycomputer, mode, 1); displaylogs ("All computer ships sunk", wlogs, hlogs, xlogs, ylogs); - while (!stop) { - switch (getch ()) { - case KEY_ESC: - case 'q': - stop = 1; - } - } + stop = stoploop (); } /* computer turn */ - if (drawbomb (boardhuman)) { + if (drawbomb (boardhuman, -1, -1)) { displaylogs ("Humain ship hited", wlogs, hlogs, xlogs, ylogs); } if (testsunk (boardhuman)) { displayboard (boardhuman, xhuman, yhuman, mode, 1); displayboard (boardcomputer, xcomputer, ycomputer, mode, 1); displaylogs ("All human ships sunk", wlogs, hlogs, xlogs, ylogs); - while (!stop) { - switch (getch ()) { - case KEY_ESC: - case 'q': - stop = 1; - } - } + stop = stoploop (); } } break; diff --git a/board.c b/board.c index 108db53..3552d28 100644 --- a/board.c +++ b/board.c @@ -86,14 +86,14 @@ void drawship (board_t *board, int length) putlocation (board, length, x, y, orient, 'S'); } -int drawbomb (board_t *board) +int drawbomb (board_t *board, int x, int y) { - int x, y; - - do { - x = rand () % board->xsize; - y = rand () % board->ysize; - } while (!testlocation (board, 1, x, y, 0, " S")); + if (x == -1) { + do { + x = rand () % board->xsize; + y = rand () % board->ysize; + } while (!testlocation (board, 1, x, y, 0, " S")); + } int ret = testlocation (board, 1, x, y, 0, " "); if (ret) { diff --git a/board.h b/board.h index 0dc3e9d..56923bb 100644 --- a/board.h +++ b/board.h @@ -17,7 +17,7 @@ void putlocation (board_t *board, int length, int x, int y, int orient, char sym void drawship (board_t *board, int length); -int drawbomb (board_t *board); +int drawbomb (board_t *board, int x, int y); int testsunk (board_t *board); -- 2.30.2