-
Notifications
You must be signed in to change notification settings - Fork 5
/
whack-the-mole.c
123 lines (109 loc) · 2.62 KB
/
whack-the-mole.c
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
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <ncurses.h>
#define ROWS 10
#define COLS 20
#define MOLES 5
#define MOLE_CHAR 'M'
#define HAMMER_CHAR 'H'
int main()
{
// initialize ncurses
initscr();
cbreak();
noecho();
keypad(stdscr, TRUE);
curs_set(0);
timeout(100);
// initialize random number generator
srand(time(NULL));
// initialize game state
int score = 0;
char board[ROWS][COLS];
int mole_rows[MOLES], mole_cols[MOLES];
int i, j;
for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
board[i][j] = ' ';
}
}
for (i = 0; i < MOLES; i++)
{
mole_rows[i] = rand() % ROWS;
mole_cols[i] = rand() % COLS;
board[mole_rows[i]][mole_cols[i]] = MOLE_CHAR;
}
// main game loop
while (1)
{
// clear screen and print board
clear();
for (i = 0; i < ROWS; i++)
{
for (j = 0; j < COLS; j++)
{
mvaddch(i, j, board[i][j]);
}
}
// print score
mvprintw(ROWS + 1, 0, "Score: %d", score);
// get user input
int ch = getch();
if (ch == KEY_LEFT)
{
board[ROWS - 1][0] = HAMMER_CHAR;
refresh();
napms(50);
board[ROWS - 1][0] = ' ';
}
else if (ch == KEY_RIGHT)
{
board[ROWS - 1][COLS - 1] = HAMMER_CHAR;
refresh();
napms(50);
board[ROWS - 1][COLS - 1] = ' ';
}
// move moles
for (i = 0; i < MOLES; i++)
{
board[mole_rows[i]][mole_cols[i]] = ' ';
mole_rows[i] = (mole_rows[i] + 1) % ROWS;
mole_cols[i] = rand() % COLS;
board[mole_rows[i]][mole_cols[i]] = MOLE_CHAR;
}
// check for hits
for (i = 0; i < MOLES; i++)
{
if (board[ROWS - 1][mole_cols[i]] == HAMMER_CHAR)
{
score++;
mole_rows[i] = rand() % ROWS;
mole_cols[i] = rand() % COLS;
board[mole_rows[i]][mole_cols[i]] = MOLE_CHAR;
}
}
// check for game over
if (score >= 10)
{
mvprintw(ROWS + 2, 0, "You win!");
getch();
break;
}
else if (score <= -5)
{
mvprintw(ROWS + 2, 0, "You lose!");
getch();
break;
}
// wait a bit
refresh();
napms(100);
}
// clean up ncurses
endwin();
// exit program
return 0;
}