implement features

This commit is contained in:
Benno Fünfstück 2020-02-06 17:39:40 +01:00
parent 19ce6f3d75
commit 54d12f1e86

View file

@ -56,6 +56,7 @@ void update_state(struct state * state, struct position hit);
enum target {
T_WATER,
T_BOAT,
T_COMPLETE_BOAT,
};
enum target check_hit(struct state state, struct position hit);
@ -140,9 +141,11 @@ int place_boat(struct state * state, struct boat boat, char c) {
return 1;
}
const int BOAT_LENGTHS[] = { 5, 4, 4, 3, 3, 3, 2, 2, 2, 2 };
/* const int BOAT_LENGTHS[] = { 5, 4, 4, 3, 3, 3, 2, 2, 2, 2 }; */
const int BOAT_LENGTHS[] = {1};
struct state generate_state(void) {
struct state
generate_state(void) {
struct state state;
memset(state.board, 0, BOARD_SIZE*BOARD_SIZE);
@ -177,6 +180,62 @@ void display_state(struct state state) {
puts("---");
}
void update_state(struct state * state, struct position hit) {
enum target check_hit(struct state state, struct position pos) {
char ship = state.board[pos.y][pos.x];
// check if we hit anything
if (ship == 0) return T_WATER;
ship = toupper(ship);
int count = 0;
for (int y = 0; y < BOARD_SIZE; ++y) {
for (int x = 0; x < BOARD_SIZE; ++x) {
if (state.board[y][x] == ship) {
count += 1;
}
}
}
return (count > 1) ? T_BOAT : T_COMPLETE_BOAT;
}
void sink_ship(struct state * state, struct position pos) {
char ship = state->board[pos.y][pos.x];
for (int x = 0; x < BOARD_SIZE; ++x) {
for (int y = 0; y < BOARD_SIZE; ++y) {
if (ship == toupper(state->board[y][x])) {
state->board[y][x] = '#';
}
}
}
}
void update_state(struct state * state, struct position pos) {
enum target target = check_hit(*state, pos);
// update board
switch (target) {
case T_BOAT:
state->board[pos.y][pos.x] = tolower(state->board[pos.y][pos.x]);
break;
case T_COMPLETE_BOAT: {
sink_ship(state, pos);
break;
}
default:
state->board[pos.y][pos.x] = '*';
break;
}
// check for game over
int letter_count = 0;
for (int x = 0; x < BOARD_SIZE; ++x) {
for (int y = 0; y < BOARD_SIZE; ++y) {
if (isalpha(state->board[pos.y][pos.x])) {
letter_count += 1;
}
}
}
state->game_over = (letter_count == 0);
}