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
|
#include <stdio.h>
#include "SDL/SDL.h"
SDL_Surface *screen = NULL;
void init() {
SDL_Init(SDL_INIT_EVERYTHING);
atexit(SDL_Quit);
SDL_WM_SetCaption("Connect 4!", NULL);
screen = SDL_SetVideoMode(98*7, 98*7, 32, SDL_SWSURFACE);
}
typedef enum { O, X, _ } Cell;
int lookup (char c) {
if (c == 'O') return 0;
else if (c == 'X') return 1;
else return 2;
}
void show (Cell board[6][7]) {
int i, j;
SDL_Surface *cell[] = {
SDL_LoadBMP("redsquare.bmp"),
SDL_LoadBMP("yellowsquare.bmp"),
SDL_LoadBMP("emptysquare.bmp") };
SDL_Rect location;
for (i = 0; i < 7; i++) {
for (j = 0; j < 6; j++) {
location.x = i * 98;
location.y = j * 98;
SDL_BlitSurface (cell[board[i][j]], NULL,
screen, &location);
}
}
SDL_Flip(screen);
SDL_FreeSurface(cell[0]);
SDL_FreeSurface(cell[1]);
SDL_FreeSurface(cell[2]);
SDL_FreeSurface(cell[3]);
SDL_FreeSurface(cell[4]);
SDL_FreeSurface(cell[5]);
}
int valid (int number) {
return number >= 0 && number < 6;
}
void play_turn (Cell board[6][7], Cell player) {
int row, col;
SDL_Event event;
SDL_Rect location;
while (SDL_WaitEvent(&event)) {
switch (event.type) {
case SDL_MOUSEBUTTONDOWN:
row = event.button.x / 160;
col = event.button.y / 160;
if (valid(row) && valid(col)
&& board [row] [col] == _) {
board[row][col] = player;
return;
}
else {
break;
case SDL_QUIT:
exit(0);
return;
}
}
board[row][col] = player;
}
}
Cell switch_player (Cell oldPlayer) {
if (oldPlayer == O) {
return X;
} else {
return O;
}
}
int main (int argc, char ** argv) {
Cell board[6][7] = { { _, _, _, _, _, _, _}, { _, _, _, _, _, _, _}, { _, _, _, _, _, _, _}, { _, _, _, _, _, _, _},{ _, _, _, _, _, _, _}, { _, _, _, _, _, _, _} };
Cell player = O;
init();
int game_over (Cell board[6][7]) {
return 0;
}
while (!game_over (board)) {
show (board);
play_turn (board, player);
player = switch_player (player);
}
}
|