forked from clinew/2048
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
89 lines (76 loc) · 2.45 KB
/
main.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
/*
* Copyright 2014 by Wade T. Cline
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stdlib.h>
#ifdef HAVE_CSTRING
# include <cstring>
#else
# ifdef HAVE_STRING_H
# include <string.h>
# endif
#endif
#include <unistd.h>
#include "board.h"
int main(int argc, char* argv[]) {
struct board board;
char input[1024];
int status; // Game status.
int valid;
// Print legal shenanigains.
printf("\t2048 (implemented in C) Copyright (C) 2014 Wade T. Cline\n"
"\tThis program comes with ABSOLUTELY NO WARRANTY. This is\n"
"\tfree software, and you are welcome to redistribute it\n"
"\tunder certain conditions. See the file 'COPYING' in the\n"
"\tsource code for details.\n\n");
// Set up board.
board_init(&board);
// Play the game.
while (!(status = board_done(&board))) {
// Print the board.
board_print(&board);
// Get the player's move.
valid = 0;
memset((void*)input, 0, sizeof(input));
write(STDOUT_FILENO, (void*)"> ", 3);
if (read(STDIN_FILENO, (void*)input, sizeof(input) - 1)
== -1) {
perror("Error reading input");
break;
}
input[strlen(input) - 1] = 0;
if (!strcmp(input, "w") || !strcmp(input, "up")) {
valid = board_move_up(&board);
} else if (!strcmp(input, "s") || !strcmp(input, "down")) {
valid = board_move_down(&board);
} else if (!strcmp(input, "a") || !strcmp(input, "left")) {
valid = board_move_left(&board);
} else if (!strcmp(input, "d") || !strcmp(input, "right")) {
valid = board_move_right(&board);
} else {
printf("Don't understand input: %s.\n", input);
continue;
}
// Prepare for user's next move.
if (valid) {
board_plop(&board);
} else {
printf("Invalid move.\n");
}
}
// Print the final board.
printf("Game over, you %s!", (status < 0) ? "LOSE" : "WIN");
board_print(&board);
// Return success.
return EXIT_SUCCESS;
}