CHANGELOG0000644000175000017500000000225512175132507012177 0ustar sicnesssicnessincoming version * Added copyright header to network.* files version 1.1.8 2013-07-27 * Added timeline showing population vs time graphs (with option -T) * Install changelog.gz * Some installation fixes in Makefile * Removed sentence "See HOW TO PLAY" from the manpage description version 1.1.7 2013-07-22 * Icons 32x32 and 16x16 * Fix Hardening problem * Added a desktop menu file version 1.1.6 2013-07-20 * Separated $(LDFLAGS) and $(LDLIBS) in Makefile (fixed compilation error in Arch Linux) version 1.1.5 2013-07-20 * Quit confirmation dialog for singleplayer and multiplayer client. * Added max map size to manpage * According to changelog standards, '-' points were changed to '*' * Fix lintian warning: "hyphen-used-as-minus-sign" in manpage * Moved $(LDFLAGS) and -o $@ version 1.1.4 2013-07-17 * improved man page, automated version number substitution version 1.1.3 2013-07-16 * added a manpage version 1.1.2 2013-07-15 * bugfix version 1.1.1 2013-07-14 * AIO is replaced with simple non-blocking input (for portability). * fixed possible segmentation faults when starting a server (error in map generation) * optimization -O2 by default client.c0000644000175000017500000001200412170266401012374 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #include "client.h" #include "state.h" int client_init (); int client_connect (); int client_process_msg_s_state (struct state *st, struct msg_s_data *msg) { if (ntohl( msg->time ) <= st->time) return -1; int p, i, j; for (p=0; pcountry[p].gold = ntohl( msg->gold[p] ); st->fg[p].width = msg->width; st->fg[p].height = msg->height; } st->time = ntohl( msg->time ); st->controlled = msg->control; st->grid.width = msg->width; st->grid.height = msg->height; for (i=0; igrid.tiles[i][j].cl = msg->tile[i][j]; for (p=0; pgrid.tiles[i][j].units[p][citizen] = 0; st->grid.tiles[i][j].pl = msg->owner[i][j]; st->grid.tiles[i][j].units[msg->owner[i][j]][citizen] = ntohs( msg->pop[i][j] ); for (p=0; pfg[p].call[i][j] = 0; if ( (msg->flag[i][j] & (1<fg[p].flag[i][j] = 0; else st->fg[p].flag[i][j] = 1; } } } return 0; } int client_receive_msg_s (int sfd, struct state *st) { static uint8_t buf[MSG_BUF_SIZE]; static struct msg_s_data msg_data; struct sockaddr_storage peer_addr; /* address you receive a message from */ socklen_t peer_addr_len = sizeof(peer_addr); int nread = recvfrom(sfd, buf, MSG_BUF_SIZE-1, 0, (struct sockaddr *) &peer_addr, &peer_addr_len); if (nread == -1) return -1; /* Ignore failed request */ uint8_t msg = 0; if (nread >= 1) { msg = buf[0]; switch (msg) { case MSG_S_STATE: if (nread-1 >= sizeof(struct msg_s_data)) { memcpy(&msg_data, buf+1, sizeof(struct msg_s_data)); client_process_msg_s_state (st, &msg_data); } else {return -1;} break; } } return msg; } int client_process_input (struct state *st, struct ui *ui, char c, int sfd, struct addrinfo *srv_addr) { int cursi = ui->cursor.i; int cursj = ui->cursor.j; switch (c) { case 'Q': case 'q': return 1; /* quit program */ /* case 'f': st->prev_speed = st->speed; st->speed = faster(st->speed); break; case 's': st->prev_speed = st->speed; st->speed = slower(st->speed); break; */ case 'p': if (st->speed == sp_pause) send_msg_c (sfd, srv_addr, MSG_C_PAUSE, 0, 0, 0); else { send_msg_c (sfd, srv_addr, MSG_C_UNPAUSE, 0, 0, 0); } break; case 'h': case K_LEFT: cursi--; break; case 'l': case K_RIGHT: cursi++; break; case 'k': case K_UP: cursj--; if (cursj % 2 == 1) cursi++; break; case 'j': case K_DOWN: cursj++; if (cursj % 2 == 0) cursi--; break; case ' ': if (st->fg[st->controlled].flag[ui->cursor.i][ui->cursor.j] == 0) send_msg_c (sfd, srv_addr, MSG_C_FLAG_ON, ui->cursor.i, ui->cursor.j, 0); else send_msg_c (sfd, srv_addr, MSG_C_FLAG_OFF, ui->cursor.i, ui->cursor.j, 0); break; case 'x': send_msg_c (sfd, srv_addr, MSG_C_FLAG_OFF_ALL, 0, 0, 0); break; case 'c': send_msg_c (sfd, srv_addr, MSG_C_FLAG_OFF_HALF, 0, 0, 0); break; case 'r': case 'v': send_msg_c (sfd, srv_addr, MSG_C_BUILD, ui->cursor.i, ui->cursor.j, 0); break; case ESCAPE: case 91: break; } cursi = IN_SEGMENT(cursi, 0, st->grid.width-1); cursj = IN_SEGMENT(cursj, 0, st->grid.height-1); if ( is_visible(st->grid.tiles[cursi][cursj].cl) ) { ui->cursor.i = cursi; ui->cursor.j = cursj; } return 0; /* not finished */ } void send_msg_c (int sfd, struct addrinfo *srv_addr, uint8_t msg, uint8_t i, uint8_t j, uint8_t info) { struct msg_c_data mcd = {i, j, info}; static uint8_t buf[MSG_BUF_SIZE]; buf[0] = msg; memcpy(buf+1, &mcd, sizeof(mcd)); int nsent = sendto(sfd, buf, 1+sizeof(mcd), 0, srv_addr->ai_addr, srv_addr->ai_addrlen); if (nsent == -1) { perror("client: sendto"); } } client.h0000644000175000017500000000246612170266401012414 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #ifndef _CLIENT_H #define _CLIENT_H #include "network.h" #include "messaging.h" #include "state.h" int client_process_input (struct state *st, struct ui *ui, char c, int sfd, struct addrinfo *srv_addr); int client_process_msg_s_state (struct state *st, struct msg_s_data *msg); int client_receive_msg_s (int sfd, struct state *st); void send_msg_c (int sfd, struct addrinfo *srv_addr, uint8_t msg, uint8_t i, uint8_t j, uint8_t info); #endif common.h0000644000175000017500000000342612173210021012411 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #ifndef _COMMON_H #define _COMMON_H #define MAX_PLAYER 8 /* number of players (countries) */ #define NEUTRAL 0 /* neutral player */ #define MAX_CLASS 1 /* classes of units. only one exists. */ #define MAX_WIDTH 40 /* max map width */ #define MAX_HEIGHT 29 /* max map height */ #define DIRECTIONS 6 /* number of neighbors on the grid */ #define MAX_POP 499 /* maximum polulation at a tile (for each player) */ #define MAX_TIMELINE_MARK 72 #define MIN(x,y) (x(r))?(r):(x) )) #define ESCAPE '\033' #define K_UP 65 #define K_DOWN 66 #define K_RIGHT 67 #define K_LEFT 68 /* game speed */ enum config_speed {sp_pause, sp_slowest, sp_slower, sp_slow, sp_normal, sp_fast, sp_faster, sp_fastest}; /* game difficulty */ enum config_dif {dif_easiest, dif_easy, dif_normal, dif_hard, dif_hardest}; #endif curseofwar.60000644000175000017500000001500612175013122013221 0ustar sicnesssicness.TH CURSEOFWAR "6" "July 2013" "curseofwar" "v%VERSION%" .SH NAME curseofwar \- Real Time Strategy Game for Linux .SH SYNOPSIS .B curseofwar [ .B \-c .I port ] [ .B \-C .I IP ] [ .B \-d .I difficulty ] [ .B \-e .I port ] .PD 0 .IP .PD [ .B \-E .I clients ] [ .B \-h ] [ .B \-H .I height ] [ .B \-i .I inequality ] .PD 0 .IP .PD [ .B \-l .I countries ] [ .B \-q .I quality ] [ .B \-r ] [ .B \-R .I seed ] [ .B \-s .I speed ] [ .B \-S .I shape ] [ .B \-T ] [ .B \-W .I width ] .SH DESCRIPTION This is a fast-paced action strategy game for Linux implemented using ncurses user interface. .PP Unlike most RTS, you are not controlling units, but focus on high-level strategic planning: Building infrastructure, securing resources, and moving your armies. .PP The core game mechanics turns out to be quite close to WWI-WWII type of warfare, however, there is no explicit reference to any historical period. .SH OPTIONS .TP \fB\-c\fR \fIport\fR Clients's port (19150 is default). .TP \fB\-C\fR \fIIP\fR Start a client and connect to the provided server's IP\-address. .TP \fB\-d\fR [ee|e|n|h|hh] Difficulty level (AI) from the easiest to the hardest (default is normal). .TP \fB\-e\fR \fIport\fR Server's port (19140 is default). .TP \fB\-E\fR [1|2| ... L] Start a server for not more than L clients. .TP \fB\-h\fR Display this help .TP \fB\-H\fR \fIheight\fR Map height (default is 21, maximum is 29) .TP \fB\-i\fR [0|1|2|3|4] Inequality between the countries (0 is the lowest, 4 in the highest). .TP \fB\-l\fR [2|3| ... N] Sets L, the number of countries (default is N). .TP \fB\-q\fR [1|2| ... L] Choose player's location by its quality (1 = the best available on the map, L = the worst). Only in the singleplayer mode. .TP \fB\-r\fR Absolutely random initial conditions, overrides options \fB\-l\fR, \fB\-i\fR, and \fB\-q\fR. .TP \fB\-R\fR \fIseed\fR Specify a random seed (unsigned integer) for map generation. .TP \fB\-s\fR [p|sss|ss|s|n|f|ff|fff] Game speed from the slowest to the fastest (default is normal). .TP \fB\-S\fR [rhombus|rect|hex] Map shape (rectangle is default). Max number of countries N=4 for rhombus and rectangle, and N=6 for the hexagon. .TP \fB\-T\fR Show the timeline. .TP \fB\-W\fR \fIwidth\fR Map width (default is 21, maximum is 40) .SH "HOW TO PLAY" Normally, the game starts with 4 small countries in the corners of the map. You start as the ruler of the Green country, and your goal is to conquer the whole map. .B Tiles The map is made of hexagonal tiles. They are: /\\^ Mountains, cannot be populated /$\\ Gold mines, cannot be populated too. This is the source of gold for your country. To control a mine, surround it with your army n Villages, have the slowest population growth (+10%) i=i Towns, average population growth (+20%) W#W Fortresses, high population growth (+30%) - Grassland, normal habitable territory .B People People are your primary resource. Thriving popluation is essential for your victory. Every tile can support at most 499 people from each country. When people from more than one country occupy the same tile, they fight. The country that has the highest population at the tile is called the tile owner. The population of the tile owner is shown on all grassland tiles as follows: \. 1 - 3 citizens .br \&.. 4 - 6 .br \&... 7 - 12 .br : 13 - 25 .br \&.: 26 - 50 .br \&.:. 51 - 100 .br :: 101 - 200 .br \&.:: 201 - 400 .br ::: 400 - 499 People migrate from highly populated tiles to less populated tiles. Population grows only in cities. In villages by 10%, in towns by 20%, and fortresses by 30% every simulation step. By controlling cities, you control their surrounding territory. .B Flags Every country can put flags on the map. Flags change migration rates, so that people of your country start gathering at the tiles with flags. Player's flags are shown as white "P" on the right side of a tile. Flags of the computer opponents are shown as "x" on the left side of a tile. The flags can be used to increase population of your own cities, as well as for conquering foreign territories. When countries are fighting for a city, and if the damage to the defender's army is significant, the city can be destroyed: A fortress becomes a town, a town becomes a village, and the village gets completely burnt by the invaders. .TP .B Countries .TP Computer opponents differ in personality, and it affects the way they fight. .SH CONTROLS Arrow keys and H, J, K, L are for moving the cursor R or V build village -> town -> fortress Space add/remove a flag .br X remove all your flags .br C remove a half of your flags S slower .br F faster Q quit .SH MULTIPLAYER To start a server for two players: .IP .B curseofwar \-E 2 .PP To start a client and connect to the server: .IP .B curseofwar \-C .PP To specify ports, use \-e option for server's port, and \-c option for client's port. By default, servers are using port 19140, and clients are using port 19150. .B Examples: Start a server for a single client using port 11111 .IP .B curseofwar \-E 1 \-e 11111 .PP To connect to it: .IP .B curseofwar \-C \-e 11111 .PP Alternatively, to connect to it using port 12345 on the client's side: .IP .B curseofwar \-C \-c 12345 \-e 11111 .PP Note that all needed map options must be setup when you start a server, the map and other data are transmitted to clients, once they are connected. .B Example: Server for 3 clients, no computer opponents, hexagonal map, and equal conditions for all: .IP .B curseofwar \-E3 \-l3 \-S hex \-i0 .PP Game speed cannot be changed by a client, so it must be set initially by the server. Not all data is sent to clients (e.g. info about population is not sent in full). Multiplayer mode is at relatively early development stage. Changes may occure at any moment. When you play with other people, make sure that you are using the same version of the game. Hopefully, game's client-server communication protocol will be improved in future. All communication is made via UDP. Please, report you problems with multiplayer. .SH EXAMPLES A good and easy mode to start playing: .IP .B curseofwar \-i4 \-q1 \-dee .PP Or, on a smaller map: .IP .B curseofwar \-i4 \-q1 \-dee \-W16 \-H16 .SH AUTHORS .B Game: .br Alexey Nikolaev .br .B Makefile: .br Kirill Dmitrenko .br Maximilian Dietrich .br .B Manpage: .br Anton Balashov .br Maximilian Dietrich curseofwar.menu0000644000175000017500000000045412173133004014021 0ustar sicnesssicness?package(curseofwar):\ needs="text" \ command="/usr/bin/curseofwar" \ hints="Strategy,Fast-paced,Action,Terminal,ncurses" \ longtitle="A fast-paced action strategy game" \ section="Games/Strategy" \ title="Curse of War (console)" \ icon="/usr/share/pixmaps/curseofwar-32x32.xpm" grid.c0000644000175000017500000003572312170266401012060 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #include "grid.h" int is_a_city(enum tile_class t) { switch(t) { case village: return 1; case town: return 1; case castle: return 1; default: return 0; } } int is_inhabitable(enum tile_class t) { switch(t) { case abyss: case mountain: case mine: return 0; default: return 1; } } int is_visible(enum tile_class t) { switch(t) { case abyss: return 0; default: return 1; } } const struct loc dirs[DIRECTIONS] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}, {1,-1}, {-1, 1}}; void grid_init(struct grid *g, int w, int h){ g->width = MIN(w, MAX_WIDTH); g->height = MIN(h, MAX_HEIGHT); int i, j; for(i=0; iwidth; ++i) { for(j=0; jheight; ++j) { g->tiles[i][j].cl = grassland; int x = rand() % 20; if(0 == x) { int y = rand() % 6; switch (y){ case 0: g->tiles[i][j].cl = castle; break; case 1: case 2: g->tiles[i][j].cl = town; break; default: g->tiles[i][j].cl = village; } } if(x > 0 && x < 5) { // mountains and mineis if (rand() % 10 == 0) g->tiles[i][j].cl = mine; else g->tiles[i][j].cl = mountain; g->tiles[i][j].pl = NEUTRAL; } else { x = 1 + rand() % (MAX_PLAYER - 1); if (x < MAX_PLAYER) g->tiles[i][j].pl = x; else g->tiles[i][j].pl = NEUTRAL; } int p, c; for (p=0; ptiles[i][j].units[p][c] = 0; } } if (is_a_city(g->tiles[i][j].cl)) { int owner = g->tiles[i][j].pl; g->tiles[i][j].units[owner][citizen] = 10; } } } } /* Stencils */ int stencil_avlbl_loc_num (enum stencil st){ switch(st) { case st_rhombus: return 4; case st_rect: return 4; case st_hex: return 6; } return 0; } #define X_OF_IJ(i,j) 0.5*(j) + (i) #define Y_OF_IJ(i,j) (float)(j) void stencil_rhombus (struct grid *g, int d, struct loc loc[MAX_AVLBL_LOC]) { int xs[] = {d, g->width-1-d, d, g->width-1-d}; int ys[] = {d, g->height-1-d, g->height-1-d, d}; int loc_num = 4; int k; for(k=0; kheight-1) - epsilon; float y0 = Y_OF_IJ(0, 0) - epsilon; float x1 = X_OF_IJ(g->width-1, 0) + epsilon; float y1 = Y_OF_IJ(0, g->height-1) + epsilon; for (i=0; iwidth; ++i) for (j=0; jheight; ++j) { x = X_OF_IJ(i,j); y = Y_OF_IJ(i,j); if (xx1 || yy1) g->tiles[i][j].cl = abyss; } int loc_num = 4; int dx = g->height/2; struct loc temp_loc[] = { {dx+d-1, d}, {g->width-dx-1-d+1, g->height-1-d}, {d+1, g->height-1-d}, {g->width-1-d-1, d} }; int k; for(k=0; kheight/2; for (i=0; iwidth; ++i) for (j=0; jheight; ++j) { if (i+jg->width-1+g->height-1-dx) g->tiles[i][j].cl = abyss; } int loc_num = 6; struct loc temp_loc[] = { {dx+d-2, d}, // tl {d, g->height-1-d}, // bl {g->width-1-d, dx}, // cr {d, dx}, // cl {g->width-1-d-2+2, d}, // tr {g->width-1-dx-d+2, g->height-1-d} // br }; int k; for(k=0; kwidth; ++i) for (j=0; jheight; ++j) { if (g->tiles[i][j].cl == abyss) { int p; for(p=0; ptiles[i][j].units[p][citizen] = 0; g->tiles[i][j].pl = NEUTRAL; } } } } /* Ended Stencils */ /* helper. * floodfill with value val, the closest distance has priority */ void floodfill_closest (struct grid *g, int u[MAX_WIDTH][MAX_HEIGHT], int d[MAX_WIDTH][MAX_HEIGHT], int x, int y, int val, int dist) { if (x < 0 || x >= g->width || y < 0 || y >= g->height || is_inhabitable(g->tiles[x][y].cl) == 0 || d[x][y] <= dist) { return; } u[x][y] = val; d[x][y] = dist; int k; for (k = 0; kwidth; ++i) for(j=0; jheight; ++j) { d[i][j] = MAX_WIDTH * MAX_HEIGHT + 1; u[i][j] = unreachable; } int k; for(k=0; kwidth; ++i) for(j=0; jheight; ++j){ if (is_inhabitable (g->tiles[i][j].cl)) { g->tiles[i][j].units[u[i][j]][citizen] = 1; g->tiles[i][j].pl = u[i][j]; } } */ for(i=0; iwidth; ++i) for(j=0; jheight; ++j){ if (g->tiles[i][j].cl == mine) { int single_owner = unreachable; int max_dist = 0; int min_dist = MAX_WIDTH * MAX_HEIGHT + 1; for (k = 0; k= g->width || y < 0 || y >= g->height || is_inhabitable(g->tiles[x][y].cl) == 0) { continue; } //g->tiles[x][y].units[u[x][y]][citizen] = 401; //g->tiles[x][y].pl = u[x][y]; if (single_owner == unreachable) { single_owner = u[x][y]; max_dist = d[x][y]; min_dist = d[x][y]; } else { if (u[x][y] == single_owner) { max_dist = MAX(max_dist, d[x][y]); min_dist = MIN(min_dist, d[x][y]); } else if (u[x][y] != unreachable) single_owner = competition; } } if (single_owner != competition && single_owner != unreachable) result[single_owner] += (int) ( 100.0 * (MAX_WIDTH + MAX_HEIGHT) * exp(-10.0 * (float)max_dist*min_dist / (MAX_WIDTH*MAX_HEIGHT)) ); } } return; } /* simple shuffling of an array of integers */ void shuffle (int arr[], int len) { int t, i, j, s; for(t=0; twidth; ++i) { for(j=0; jheight; ++j) { for (p=0; p< MAX_PLAYER; ++p) { for (c = 0; ctiles[i][j].units[p][c] = 0; g->tiles[i][j].pl = NEUTRAL; if (is_a_city(g->tiles[i][j].cl)) g->tiles[i][j].cl = grassland; //g->tiles[i][j].pl = NEUTRAL; } } } } locations_num = IN_SEGMENT(locations_num, 2, available_loc_num); int num = MIN(locations_num, players_num + ui_players_num); /* shift in the positions arrays */ int di = rand() % available_loc_num; struct loc chosen_loc [MAX_AVLBL_LOC]; i = 0; while (i < num) { int ii = (i + di + available_loc_num) % available_loc_num; int x = loc_arr[ii].i; int y = loc_arr[ii].j; chosen_loc[i].i = x; chosen_loc[i].j = y; g->tiles[x][y].cl = castle; /* place mines nearby */ int dir = rand() % DIRECTIONS; int ri = dirs[dir].i; int rj = dirs[dir].j; int m = 1; int mine_i = x + m*ri; int mine_j = y + m*rj; g->tiles[mine_i][mine_j].cl = mine; g->tiles[mine_i][mine_j].pl = NEUTRAL; mine_i = x - 2*m*ri; mine_j = y - 2*m*rj; g->tiles[mine_i][mine_j].cl = mine; g->tiles[mine_i][mine_j].pl = NEUTRAL; mine_i = x - m*ri; mine_j = y - m*rj; g->tiles[mine_i][mine_j].cl = grassland; g->tiles[mine_i][mine_j].pl = NEUTRAL; i++; } /* eval locations */ int eval_result[] = {0, 0, 0, 0, 0, 0, 0}; int loc_index[] = {0, 1, 2, 3, 4, 5, 6}; eval_locations(g, chosen_loc, eval_result, num); /* sort in increasing order */ sort(eval_result, loc_index, num); /* Compute inequality */ if (ineq != RANDOM_INEQUALITY) { float avg = 0; for(i=0; i50) return -1; break; case 1: if (x<=50 || x>100) return -1; break; case 2: if (x<=100 || x>250) return -1; break; case 3: if (x<=250 || x>500) return -1; break; case 4: if (x<=500) return -1; break; } } /* suffled computer players */ int *sh_players_comp = malloc(sizeof(int)*players_num); for(i=0; i 0) { int select = IN_SEGMENT(num - conditions, 0, num-1); ihuman = loc_index[select]; } i = 0; while (i < num) { int ii = loc_index[i]; int x = chosen_loc[ ii ].i; int y = chosen_loc[ ii ].j; /* if (human_player != NEUTRAL && ihuman == ii) g->tiles[x][y].pl = human_player; else g->tiles[x][y].pl = sh_players[i]; */ if (ui_players_num > 1) { g->tiles[x][y].pl = sh_players[i]; } else { if (ii == ihuman) g->tiles[x][y].pl = ui_players[0]; else g->tiles[x][y].pl = sh_players_comp[i]; } g->tiles[x][y].units[ g->tiles[x][y].pl ][citizen] = 10; i++; } /* free allocated memory */ free(sh_players); return 0; } /* helper */ void floodfill (struct grid *g, int u[MAX_WIDTH][MAX_HEIGHT], int x, int y, int val) { if (x < 0 || x >= g->width || y < 0 || y >= g->height || is_inhabitable(g->tiles[x][y].cl) == 0 || u[x][y] == val) { return; } u[x][y] = val; int k; for (k = 0; kwidth; ++i) for(j=0; jheight; ++j) m[i][j] = 0; int colored = 0; for(i=0; iwidth; ++i) { for(j=0; jheight; ++j) { if (g->tiles[i][j].pl != NEUTRAL) { if (colored && m[i][j] == 0) return 0; colored = 1; floodfill(g, m, i, j, 1); } } } return 1; } void flag_grid_init(struct flag_grid *fg, int w, int h) { fg->width = MIN(w, MAX_WIDTH); fg->height = MIN(h, MAX_HEIGHT); int i, j; for(i=0; iwidth; ++i) { for(j=0; jheight; ++j) { fg->flag[i][j] = FLAG_OFF; fg->call[i][j] = 0; } } } void spread (struct grid *g, int u[MAX_WIDTH][MAX_HEIGHT], int v[MAX_WIDTH][MAX_HEIGHT], int x, int y, int val, int factor) { if (x < 0 || x >= g->width || y < 0 || y >= g->height || is_inhabitable(g->tiles[x][y].cl) == 0) { return; } int d = val - u[x][y]; if (d > 0) { v[x][y] = MAX(0, v[x][y] + d * factor); u[x][y] += d; int k; for (k = 0; k= g->width || y < 0 || y >= g->height || v[x][y] == val) { return; } v[x][y] = val; int k; for (k = 0; k= g->width || y < 0 || y >= g->height || is_inhabitable(g->tiles[x][y].cl) == 0 || fg->flag[x][y] == FLAG_ON) { return; } int u[MAX_WIDTH][MAX_HEIGHT]; int i, j; for(i=0; i< MAX_WIDTH; ++i){ for(j=0; jflag[x][y] = FLAG_ON; spread(g, u, fg->call, x, y, val, 1); } void remove_flag (struct grid *g, struct flag_grid *fg, int x, int y, int val) { // exit if if (x < 0 || x >= g->width || y < 0 || y >= g->height || is_inhabitable(g->tiles[x][y].cl) == 0 || fg->flag[x][y] == FLAG_OFF) { return; } int u[MAX_WIDTH][MAX_HEIGHT]; int i, j; for(i=0; i< MAX_WIDTH; ++i){ for(j=0; jflag[x][y] = FLAG_OFF; spread(g, u, fg->call, x, y, val, -1); } void remove_flags_with_prob (struct grid *g, struct flag_grid *fg, float prob) { int i, j; for (i=0; iwidth; ++i) { for (j=0; jheight; ++j) { if (fg->flag[i][j] && (float)rand() / RAND_MAX <= prob) { remove_flag(g, fg, i, j, FLAG_POWER); } } } } grid.h0000644000175000017500000001343512170266401012061 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #ifndef _GRID_H #define _GRID_H #include #include #include #include "common.h" #define FLAG_ON 1 #define FLAG_OFF 0 #define FLAG_POWER 8 #define RANDOM_INEQUALITY -1 #define MAX_AVLBL_LOC 7 /* enum unit_class * * Units/Creatures that can be controlled by the players: * Only citizens are available. */ enum unit_class { citizen=0 }; /* enum tile_class * * Territory classes: * mountain is a natural barrier * mine is a source of gold * grassland is a habitable territory that does not have cities * village, town, and castle are three kinds of cities with different population growth rate * (castles have the highest rate, while villages have the lowest). * * */ enum tile_class { abyss=0, mountain=1, mine=2, grassland=3, village=4, town=5, castle=6 }; /* is_a_city(t) returns 1 for village, town, or castle */ int is_a_city(enum tile_class t); /* is_inhabitable(t) returns 1 for grassland, village, town, or castle */ int is_inhabitable(enum tile_class t); int is_visible(enum tile_class t); enum stencil {st_rhombus, st_rect, st_hex}; /* stencil_avlbl_loc_num (st) * number of available locations for the stencil st */ int stencil_avlbl_loc_num (enum stencil st); /* struct tile * * Tiles are the smallest pieces of the map. * * Components: * cl is the tile's territory class, * pl is the id if the player, owner of the tile * units is the array that contains information about the population of the tile * (info for all players, and for all unit classes) * * */ struct tile { enum tile_class cl; int pl; int units[MAX_PLAYER][MAX_CLASS]; }; /* struct loc * * Location. * * Components: * i (horizontal axis) * j (vertical axis) * */ struct loc { int i; int j; }; /* There are 6 possible directions to move from a tile. Hexagonal geometry. */ const struct loc dirs[DIRECTIONS]; /* struct grid * * 2D Array of tiles + width and height information. * The map is stored in this structure. */ struct grid { int width; int height; struct tile tiles[MAX_WIDTH][MAX_HEIGHT]; }; /* grid_init (&g, w, h) * * Initialize the grid g. Set its width to w and height to h. * It also generates the tiles: Random mountains, mines and cities */ void grid_init(struct grid *g, int w, int h); void apply_stencil(enum stencil st, struct grid *g, int d, struct loc loc[MAX_AVLBL_LOC], int *avlbl_loc_num); /* conflict (&g, loc_arr, avlbl_loc_num, players, players_num, human_player) * * Enhances an already initialized grid. * Places at most 4 players at the corners of the map, gives them a castle and 2 mines nearby. * One of those players is always controlled by a human player. * * players is the array of the ids of the possible opponents (represented by integers, usually 1 < i < MAX_PLAYER), * players_num is the size of the players array * * locations_num is the number of starting locations (can be equal to 2, 3, or 4) * human_player is the id of the human player (usually = 1) * * conditions = {1, ... number of available locations}, 1 = the best. * * ineq = inequality from 0 to 4. * */ int conflict (struct grid *g, struct loc loc_arr[], int available_loc_num, int players[], int players_num, int locations_num, int ui_players[], int ui_players_num, int conditions, int ineq); /* is_conected(&g) * Check connectedness of the grid */ int is_connected (struct grid *g); /* struct flag_grid * * Similar to the struct grid, but stores information about player's flags. * Each player has his own struct grid_flag. * * flag[i][j] == 1, if there is a flag. * * call[i][j] determine the power of attraction to this location. * Must be updated when flags are added or removed. */ struct flag_grid { int width; int height; int flag [MAX_WIDTH][MAX_HEIGHT]; int call [MAX_WIDTH][MAX_HEIGHT]; }; /* flag_grid_init (&fg, w, h) * * A simple initialization of the flag grid fg. */ void flag_grid_init(struct flag_grid *fg, int w, int h); /* spread(&g, u, v, x, y, val, factor) * and * even(&g, u, x, y, val) * * Helper functions, primarily are used for maintaining call[i][j] for flag grids */ void spread (struct grid *g, int u[MAX_WIDTH][MAX_HEIGHT], int v[MAX_WIDTH][MAX_HEIGHT], int x, int y, int val, int factor); void even (struct grid *g, int v[MAX_WIDTH][MAX_HEIGHT], int x, int y, int val); /* add_flag (&g, &fg, x, y, v) * * Adds a flag to the flag grid fg at the location (x,y) with power v. */ void add_flag (struct grid *g, struct flag_grid *fg, int x, int y, int val); /* remove_flag (&g, &fg, x, y, v) * * Removes a flag from the flag grid fg at the location (x,y) with power v. */ void remove_flag (struct grid *g, struct flag_grid *fg, int x, int y, int val); /* remove_flags_with_prob (&g, &fg, prob) * * Iterates over all tiles, and removes flags with probability prob. * That is, it removes all flags if prob==1. */ void remove_flags_with_prob (struct grid *g, struct flag_grid *fg, float prob); #endif king.c0000644000175000017500000002511612170430667012065 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #include "king.h" #include int build (struct grid *g, struct country *c, int pl, int i, int j) { if (i>=0 && i < g->width && j>=0 && jheight && g->tiles[i][j].pl == pl) { int price = 0; enum tile_class cl = grassland; switch (g->tiles[i][j].cl) { case grassland: price = PRICE_VILLAGE; cl = village; break; case village: price = PRICE_TOWN; cl = town; break; case town: price = PRICE_CASTLE; cl = castle; break; default: return -1; } if (c->gold >= price) { g->tiles[i][j].cl = cl; c->gold -= price; return 0; } } return -1; } int degrade (struct grid *g, int i, int j) { if (i>=0 && i < g->width && j>=0 && jheight) { enum tile_class cl = grassland; switch (g->tiles[i][j].cl) { case village: cl = grassland; break; case town: cl = village; break; case castle: cl = town; break; default: return -1; } g->tiles[i][j].cl = cl; return 0; } return -1; } void king_evaluate_map (struct king *k, struct grid *g, enum config_dif dif) { int i, j; int u [MAX_WIDTH][MAX_HEIGHT]; for (i=0; iwidth; ++i) { for (j=0; jheight; ++j) { u[i][j] = 0; k->value[i][j] = 0; } } for (i=0; iwidth; ++i) { for (j=0; jheight; ++j) { if (is_inhabitable(g->tiles[i][j].cl)) k->value[i][j] += 1; switch (k->strategy) { case persistent_greedy: if (is_inhabitable(g->tiles[i][j].cl)) k->value[i][j] += 1; break; default: ; } switch (g->tiles[i][j].cl) { case castle: if(k->strategy == noble) spread (g, u, k->value, i, j, 32, 1); else spread (g, u, k->value, i, j, 16, 1); even(g, u, i, j, 0); break; case town: spread (g, u, k->value, i, j, 8, 1); even(g, u, i, j, 0); break; case village: if(k->strategy == noble) spread (g, u, k->value, i, j, 2, 1); else spread (g, u, k->value, i, j, 4, 1); even(g, u, i, j, 0); break; case mine: { int d; for(d=0; dstrategy == midas) spread (g, u, k->value, ii, jj, 8, 1); else spread (g, u, k->value, ii, jj, 4, 1); even (g, u, ii, jj, 0); } }; break; default: ; } } } /* dumb down kings */ int x; for (i=0; iwidth; ++i) { for (j=0; jheight; ++j) { switch(dif) { case dif_easiest: x = k->value[i][j] / 4; x = x + rand()%7 - 3; k->value[i][j] = MAX(0, x); break; case dif_easy: x = k->value[i][j] / 2; x = x + rand()%3 - 1; k->value[i][j] = MAX(0, x); break; default: ; } } } } void king_init (struct king *k, int pl, enum strategy strat, struct grid *g, enum config_dif dif) { k->pl = pl; k->strategy = strat; //king_evaluate_map(k, g, dif); } int builder_default (struct king *k, struct country *c, struct grid *g, struct flag_grid *fg) { int i, j; int i_best = 0, j_best = 0; float v_best = 0.0; float v; int n; for (i=0; iwidth; ++i) { for (j=0; jheight; ++j) { int ok = 0; if ( g->tiles[i][j].pl == k->pl && is_inhabitable(g->tiles[i][j].cl) ) { ok = 1; int di, dj; for(n=0; n= 0 && i+di < g->width && j+dj >= 0 && j+dj < g->height && is_inhabitable (g->tiles[i+di][j+dj].cl) ) { ok = ok && (g->tiles[i+di][j+dj].pl == k->pl); } } } int army = g->tiles[i][j].units[k->pl][citizen]; int enemy = 0; int p; for (p=0; ppl) enemy = enemy + g->tiles[i][j].units[p][citizen]; } int base = 1.0; switch (g->tiles[i][j].cl) { case grassland: base = 1.0; break; case village: base = 8.0; break; case town: base = 32.0; break; default: base = 0.0; } if (k->strategy == midas) base *= (k->value[i][j] + 10); v = ok * base * (MAX_POP - army); if (army < MAX_POP / 10) v = 0.0; if (v > 0.0 && v > v_best) { i_best = i; j_best = j; v_best = v; } } } if (v_best > 0.0) return build(g, c, k->pl, i_best, j_best); else return -1; } /* Auxiliary functions for different kings' strategies: */ void action_aggr_greedy (struct king *k, struct grid *g, struct flag_grid *fg) { int i, j; for (i=0; iwidth; ++i) { for (j=0; jheight; ++j) { if (fg->flag[i][j]) remove_flag(g, fg, i, j, FLAG_POWER); // estimate the value of the grid point (i,j) int army = g->tiles[i][j].units[k->pl][citizen]; int enemy = 0; int p; for (p=0; ppl) enemy = enemy + g->tiles[i][j].units[p][citizen]; } float v = (float) k->value[i][j] * (2.0*enemy - army) * pow(army, 0.5); if (v > 5000) add_flag(g, fg, i, j, FLAG_POWER); } } } void action_one_greedy (struct king *k, struct grid *g, struct flag_grid *fg) { int i, j; int i_best = 0, j_best = 0; float v_best = -1.0; for (i=0; iwidth; ++i) { for (j=0; jheight; ++j) { if (fg->flag[i][j]) remove_flag(g, fg, i, j, FLAG_POWER); // estimate the value of the grid point (i,j) int army = g->tiles[i][j].units[k->pl][citizen]; int enemy = 0; int p; for (p=0; ppl) enemy = enemy + g->tiles[i][j].units[p][citizen]; } float v = (float) k->value[i][j] * (5.0*enemy - army) * pow(army, 0.5); if (v > v_best && v > 5000) {v_best = v; i_best = i; j_best = j;} } } if (v_best > 0) add_flag(g, fg, i_best, j_best, FLAG_POWER); } void action_persistent_greedy (struct king *k, struct grid *g, struct flag_grid *fg) { int i, j; for (i=0; iwidth; ++i) { for (j=0; jheight; ++j) { // estimate the value of the grid point (i,j) int army = g->tiles[i][j].units[k->pl][citizen]; int enemy = 0; int p; for (p=0; ppl) enemy = enemy + g->tiles[i][j].units[p][citizen]; } float v1 = (float) k->value[i][j] * (2.5*enemy - army) * pow(army, 0.7); // weak opportunist float v2 = (float) k->value[i][j] * (MAX_POP - (enemy - army)) * pow(army, 0.7) * 0.5; if (enemy <= army) v2 = -10000; float v = MAX(v1,v2); if (fg->flag[i][j] == FLAG_ON) { if (v < 1000) remove_flag(g, fg, i, j, FLAG_POWER); } else { if (v > 9000) add_flag(g, fg, i, j, FLAG_POWER); } } } } void action_opportunist (struct king *k, struct grid *g, struct flag_grid *fg) { int i, j; for (i=0; iwidth; ++i) { for (j=0; jheight; ++j) { if (fg->flag[i][j]) remove_flag(g, fg, i, j, FLAG_POWER); // estimate the value of the grid point (i,j) int army = g->tiles[i][j].units[k->pl][citizen]; int enemy = 0; int p; for (p=0; ppl) enemy = enemy + g->tiles[i][j].units[p][citizen]; } float v = (float) k->value[i][j] * (MAX_POP - (enemy - army)) * pow(army, 0.5); if (enemy > army && v > 7000) add_flag(g, fg, i, j, FLAG_POWER); } } } /* Priority array */ #define MAX_PRIORITY 32 /* special no-location */ const struct loc no_loc = {-1, -1}; /* initialize array of locations */ void init_locval(struct loc loc[MAX_PRIORITY], int val[MAX_PRIORITY], int len) { int i; for(i=0; i=vx; ++i); if (ii; --j){ loc[j] = loc[j-1]; val[j] = val[j-1]; } loc[i] = lx; val[i] = vx; } } void action_noble (struct king *k, struct grid *g, struct flag_grid *fg) { int i, j; /* number of flags */ int locval_len = 5; struct loc loc[MAX_PRIORITY]; int val[MAX_PRIORITY]; init_locval(loc, val, locval_len); for (i=0; iwidth; ++i) { for (j=0; jheight; ++j) { if (fg->flag[i][j]) remove_flag(g, fg, i, j, FLAG_POWER); // estimate the value of the grid point (i,j) int army = g->tiles[i][j].units[k->pl][citizen]; int enemy = 0; int p; for (p=0; ppl) enemy = enemy + g->tiles[i][j].units[p][citizen]; } float v = (float) k->value[i][j] * (MAX_POP - (enemy - army)) * pow(army, 0.5); if (enemy > army && v > 7000) { //add_flag(g, fg, i, j, FLAG_POWER); struct loc lx = {i,j}; insert_locval(loc, val, locval_len, lx, (int)v); } } } for (i=0; i0; ++i){ add_flag(g, fg, loc[i].i, loc[i].j, FLAG_POWER); } } void place_flags (struct king *k, struct grid *g, struct flag_grid *fg) { switch (k->strategy) { case aggr_greedy: action_aggr_greedy(k, g, fg); break; case one_greedy: action_one_greedy(k, g, fg); break; case persistent_greedy: action_persistent_greedy(k, g, fg); break; case opportunist: action_opportunist(k, g, fg); break; case noble: action_noble(k, g, fg); break; case midas: break; default: ; } } king.h0000644000175000017500000000632012170266401012057 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #ifndef _KING_H #define _KING_H #include "grid.h" /* struct country Data about each country */ struct country { long gold; }; #define PRICE_VILLAGE 150 #define PRICE_TOWN 300 #define PRICE_CASTLE 600 /* build(&g, &c, pl, i, j) build a village, upgrade a village to a town, or upgrade a town to a castle. g and c are struct grid and struct country, pl is the player id ( Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) 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 . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . main.c0000644000175000017500000005576212173210021012052 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include #include "common.h" #include "grid.h" #include "state.h" #include "output.h" #include "messaging.h" #include "client.h" #include "server.h" /*****************************************************************************/ /* Global Constants */ /*****************************************************************************/ volatile sig_atomic_t input_ready; volatile sig_atomic_t time_to_redraw; #define DEF_SERVER_ADDR "127.0.0.1" #define DEF_SERVER_PORT "19140" #define DEF_CLIENT_PORT "19150" void on_timer(int signum); /* handler for alarm */ int update_from_input( struct state *st, struct ui *ui ); int update_from_input_client( struct state *st, struct ui *ui, int sfd, struct addrinfo *srv_addr); int update_from_input_server( struct state *st ); void print_help() { printf( " __ \n" " ____ / ] \n" " / __ \\_ _ ___ ___ ___ __ _| |_ /\\ /\\___ ___ \n" " _/ / \\/ | |X _/ __/ __\\ / \\ / \\ \\ /\\ / /__ \\X _/ \n" " \\ X | | | | |__ | __X | X || | \\ V V // _ | | \n" " \\ \\__/\\ __X_| \\___/___/ \\___/| | \\ /\\ / \\___X_| \n" " \\____/ |/ V V \n" "\n" " Written by Alexey Nikolaev in 2013.\n" "\n"); printf(" Command line arguments:\n\n"); printf( "-W width\n" "\tMap width (default is 21)\n\n" "-H height\n" "\tMap height (default is 21)\n\n" "-S [rhombus|rect|hex]\n" "\tMap shape (rectangle is default). Max number of countries N=4 for rhombus and rectangle, and N=6 for the hexagon.\n\n" "-l [2|3| ... N]\n" "\tSets L, the number of countries (default is N).\n\n" "-i [0|1|2|3|4]\n" "\tInequality between the countries (0 is the lowest, 4 in the highest).\n\n" "-q [1|2| ... L]\n" "\tChoose player's location by its quality (1 = the best available on the map, L = the worst). Only in the singleplayer mode.\n\n" "-r\n" "\tAbsolutely random initial conditions, overrides options -l, -i, and -q.\n\n" "-d [ee|e|n|h|hh]\n" "\tDifficulty level (AI) from the easiest to the hardest (default is normal).\n\n" "-s [p|sss|ss|s|n|f|ff|fff]\n" "\tGame speed from the slowest to the fastest (default is normal).\n\n" "-R seed\n" "\tSpecify a random seed (unsigned integer) for map generation.\n\n" "-T\n" "\tShow the timeline.\n\n" "-E [1|2| ... L]\n" "\tStart a server for not more than L clients.\n\n" "-e port\n" "\tServer's port (19140 is default).\n\n" "-C IP\n" "\tStart a client and connect to the provided server's IP-address.\n\n" "-c port\n" "\tClients's port (19150 is default).\n\n" "-h\n" "\tDisplay this help \n\n" ); } void win_or_lose(struct state *st, int k) { int i, j, p; int pop[MAX_PLAYER]; for (p=0; pgrid.width; ++i){ for(j=0; jgrid.height; ++j){ if(is_inhabitable(st->grid.tiles[i][j].cl)) { for(p=0; pgrid.tiles[i][j].units[p][citizen]; } } } } int win = 1; int lose = 0; int best = 0; for(p=0; pcontrolled && pop[p]>0) win = 0; } if(pop[st->controlled] == 0) lose = 1; if (win) { attrset(A_BOLD | COLOR_PAIR(4)); mvaddstr(2 + st->grid.height, 31, "You are victorious!"); } else if (lose) { attrset(A_BOLD | COLOR_PAIR(2)); mvaddstr(2 + st->grid.height, 31, "You are defeated!"); } } int game_slowdown (int speed) { int slowdown = 20; switch (speed) { case sp_pause: slowdown = 1; break; case sp_slowest: slowdown = 160; break; case sp_slower: slowdown = 80; break; case sp_slow: slowdown = 40; break; case sp_normal: slowdown = 20; break; case sp_fast: slowdown = 10; break; case sp_faster: slowdown = 5; break; case sp_fastest: slowdown = 2; break; } return slowdown; } /* Run the game */ void run (struct state *st, struct ui *ui) { int k = 0; int finished = 0; while( !finished ) { if (time_to_redraw) { k++; if (k>=1600) k=0; int slowdown = game_slowdown(st->speed); if (k % slowdown == 0 && st->speed != sp_pause) { kings_move(st); simulate(st); if (st->show_timeline) { if (st->time%10 == 0) update_timeline(st); } } output_grid(st, ui, k); if (st->show_timeline) { if (st->time%10 == 0) output_timeline(st, ui); } time_to_redraw = 0; if (k%100 == 0) win_or_lose(st, k); } finished = update_from_input(st, ui); pause(); // sleep until woken up by SIGALRM } } /* run client */ void run_client (struct state *st, struct ui *ui, char *s_server_addr, char *s_server_port, char *s_client_port) { int sfd; /* file descriptor of the socket */ int ret_code; /* code returned by a function */ struct addrinfo srv_addr; if ((ret_code = client_init_session (&sfd, s_client_port, &srv_addr, s_server_addr, s_server_port)) != 0) { perror("Failed to initialize networking"); return; } /* non-blocking mode */ fcntl(sfd, F_SETFL, O_NONBLOCK); int k = 0; int finished = 0; int initialized = 0; st->time = 0; while( !finished ) { if (time_to_redraw) { k++; if (k>=1600) k=0; time_to_redraw = 0; if (k%50 == 0) send_msg_c (sfd, &srv_addr, MSG_C_IS_ALIVE, 0, 0, 0); int msg = client_receive_msg_s (sfd, st); if (msg == MSG_S_STATE && initialized != 1) { initialized = 1; ui_init(st, ui); } if (initialized) { output_grid(st, ui, k); } } finished = update_from_input_client(st, ui, sfd, &srv_addr); pause(); } close(sfd); } /* run server */ void run_server (struct state *st, int cl_num_need, char *s_server_port) { int sfd; /* file descriptor of the socket */ struct sockaddr_storage peer_addr; /* address you receive a message from */ socklen_t peer_addr_len = sizeof(struct sockaddr_storage); ssize_t nread; uint8_t buf[MSG_BUF_SIZE]; /* message buffer */ int ret_code; /* code returned by a function */ if ((ret_code = server_init (&sfd, s_server_port)) != 0) { perror("Failed to initialize networking"); return; } /* non-blocking mode */ fcntl(sfd, F_SETFL, O_NONBLOCK); int cl_num = 0; struct client_record cl[MAX_CLIENT]; enum server_mode mode = server_mode_lobby; int finished = 0; int k=0; while( !finished ) { if (time_to_redraw) { switch(mode){ case server_mode_lobby: /* Lobby */ nread = recvfrom(sfd, buf, MSG_BUF_SIZE-1, 0, (struct sockaddr *) &peer_addr, &peer_addr_len); /* try to add a new client */ if ( server_get_msg(buf, nread) > 0 ) { int i; int found = 0; for(i=0; i= cl_num_need) { mode = server_mode_play; cl_num = cl_num_need; } } break; case server_mode_play: /* Game */ k++; if (k>=1600) k=0; int slowdown = game_slowdown(st->speed); if (k % slowdown == 0 && st->speed != sp_pause) { kings_move(st); simulate(st); server_send_msg_s_state(sfd, cl, cl_num, st); } nread = recvfrom(sfd, buf, MSG_BUF_SIZE-1, 0, (struct sockaddr *) &peer_addr, &peer_addr_len); if (nread != -1) { int found_i = -1; int i; for(i=0; i-1) { int msg = server_process_msg_c(buf, nread, st, cl[found_i].pl); if (msg == MSG_C_IS_ALIVE) addstr("."); else addstr("+"); refresh(); } } break; } time_to_redraw = 0; } finished = update_from_input_server(st); pause(); } close(sfd); } /*****************************************************************************/ /* Main */ /*****************************************************************************/ int main(int argc, char* argv[]){ /* Initialize pseudo random number generator */ srand(time(NULL)); /* Parse argv */ int r_flag = 0; // random int dif_val = dif_normal; // diffiulty int sp_val = sp_normal; // speed int w_val = 21; // width int h_val = 21; // height int l_val = 0; // the number of starting locations unsigned int seed_val = rand(); int conditions_val = 0; int conditions_were_set = 0; int timeline_flag = 0; int ineq_val = RANDOM_INEQUALITY; enum stencil shape_val = st_rect; /* multiplayer option */ int multiplayer_flag = 0; int server_flag = 1; char* val_client_port = strdup(DEF_CLIENT_PORT); char* val_server_addr = strdup(DEF_SERVER_ADDR); char* val_server_port = strdup(DEF_SERVER_PORT); int val_clients_num = 1; opterr = 0; int c; while ((c = getopt (argc, argv, "hrTW:H:i:l:q:d:s:R:S:E:e:C:c:")) != -1){ switch(c){ case 'r': r_flag = 1; break; case 'T': timeline_flag = 1; break; //case 'f': f_val = optarg; break; case 'W': { char* endptr = NULL; w_val = MAX(14, strtol(optarg, &endptr, 10)); if (*endptr != '\0') { print_help(); return 1; } }; break; case 'H': { char* endptr = NULL; h_val = MAX(14, strtol(optarg, &endptr, 10)); if (*endptr != '\0') { print_help(); return 1; } }; break; case 'i': { char* endptr = NULL; ineq_val = strtol(optarg, &endptr, 10); if (*endptr != '\0' || ineq_val < 0 || ineq_val > 4) { print_help(); return 1; } }; break; case 'l': { char* endptr = NULL; l_val = strtol(optarg, &endptr, 10); if (*endptr != '\0') { print_help(); return 1; } }; break; case 'q': { char* endptr = NULL; conditions_val = strtol(optarg, &endptr, 10); conditions_were_set = 1; if (*endptr != '\0') { print_help(); return 1; } }; break; case 'R': { char* endptr = NULL; seed_val = abs(strtol(optarg, &endptr, 10)); if (*endptr != '\0' || *optarg == '\0') { print_help(); return 1; } }; break; case 'd': if (strcmp(optarg, "n") == 0) dif_val = dif_normal; else if (strcmp(optarg, "e") == 0) dif_val = dif_easy; else if (strcmp(optarg, "e1") == 0) dif_val = dif_easy; else if (strcmp(optarg, "ee") == 0) dif_val = dif_easiest; else if (strcmp(optarg, "e2") == 0) dif_val = dif_easiest; else if (strcmp(optarg, "h") == 0) dif_val = dif_hard; else if (strcmp(optarg, "h1") == 0) dif_val = dif_hard; else if (strcmp(optarg, "hh") == 0) dif_val = dif_hardest; else if (strcmp(optarg, "h2") == 0) dif_val = dif_hardest; else { print_help(); return 1; } break; case 's': if (strcmp(optarg, "n") == 0) sp_val = sp_normal; else if (strcmp(optarg, "s") == 0 || strcmp(optarg, "s1") == 0) sp_val = sp_slow; else if (strcmp(optarg, "ss") == 0 || strcmp(optarg, "s2") == 0) sp_val = sp_slower; else if (strcmp(optarg, "sss") == 0 || strcmp(optarg, "s3") == 0) sp_val = sp_slowest; else if (strcmp(optarg, "f") == 0 || strcmp(optarg, "f1") == 0) sp_val = sp_fast; else if (strcmp(optarg, "ff") == 0 || strcmp(optarg, "f2") == 0) sp_val = sp_faster; else if (strcmp(optarg, "fff") == 0 || strcmp(optarg, "f3") == 0) sp_val = sp_fastest; else if (strcmp(optarg, "p") == 0) sp_val = sp_pause; else { print_help(); return 1; } break; case 'S': if (strcmp(optarg, "rhombus") == 0) shape_val = st_rhombus; else if (strcmp(optarg, "rect") == 0) shape_val = st_rect; else if (strcmp(optarg, "hex") == 0) shape_val = st_hex; else { print_help(); return 1; } break; /* multiplayer-related options */ case 'E': { char* endptr = NULL; val_clients_num = strtol(optarg, &endptr, 10); if (*endptr != '\0') { print_help(); return 1; } multiplayer_flag = 1; server_flag = 1; } break; case 'e': free(val_server_port); val_server_port = strdup(optarg); break; case 'C': multiplayer_flag = 1; server_flag = 0; free(val_server_addr); val_server_addr = strdup(optarg); break; case 'c': free(val_client_port); val_client_port = strdup(optarg); break; case '?': case 'h': print_help(); return 1; default: abort (); } } /* Adjust l_val and conditions_val */ { int avlbl_loc_num = stencil_avlbl_loc_num (shape_val); if(l_val == 0) l_val = avlbl_loc_num; if (l_val < 2 || l_val > avlbl_loc_num) { print_help(); return 1; } if (conditions_were_set && (conditions_val<1 || conditions_val>l_val)) { print_help(); return 1; } if (val_clients_num < 1 || val_clients_num > l_val) { print_help(); return 1; } if (shape_val == st_rect) { w_val = MIN(MAX_WIDTH-1, w_val+(h_val+1)/2); } } struct sigaction newhandler; /* new settings */ sigset_t blocked; /* set of blocked sigs */ newhandler.sa_flags = SA_RESTART; /* options */ sigemptyset(&blocked); /* clear all bits */ newhandler.sa_mask = blocked; /* store blockmask */ newhandler.sa_handler = on_timer; /* handler function */ if ( sigaction(SIGALRM, &newhandler, NULL) == -1 ) perror("sigaction"); /* prepare the terminal for the animation */ setlocale(LC_ALL, ""); initscr(); /* initialize the library and screen */ cbreak(); /* put terminal into non-blocking input mode */ noecho(); /* turn off echo */ start_color(); clear(); /* clear the screen */ curs_set(0); /* hide the cursor */ use_default_colors(); init_pair(0, COLOR_WHITE, COLOR_BLACK); init_pair(1, COLOR_WHITE, COLOR_BLACK); init_pair(2, COLOR_BLACK, COLOR_BLACK); init_pair(3, COLOR_RED, COLOR_BLACK); init_pair(4, COLOR_GREEN, COLOR_BLACK); init_pair(5, COLOR_BLUE, COLOR_BLACK); init_pair(6, COLOR_YELLOW, COLOR_BLACK); init_pair(7, COLOR_MAGENTA, COLOR_BLACK); init_pair(8, COLOR_CYAN, COLOR_BLACK); color_set(0, NULL); assume_default_colors(COLOR_WHITE, COLOR_BLACK); clear(); struct state st; struct ui ui; /* Initialize the parameters of the program */ attrset(A_BOLD | COLOR_PAIR(2)); mvaddstr(0,0,"Map is generated. Please wait."); refresh(); state_init(&st, w_val, h_val, shape_val, seed_val, r_flag, l_val, val_clients_num, conditions_val, ineq_val, sp_val, dif_val, timeline_flag); ui_init(&st, &ui); clear(); /* non-blocking input */ int fd_flags = fcntl(0, F_GETFL); fcntl(0, F_SETFL, (fd_flags|O_NONBLOCK)); /* Start the real time interval timer with delay interval size */ struct itimerval it; it.it_value.tv_sec = 0; it.it_value.tv_usec = 10000; it.it_interval.tv_sec = 0; it.it_interval.tv_usec = 10000; setitimer(ITIMER_REAL, &it, NULL); refresh(); input_ready = 0; time_to_redraw = 1; if (!multiplayer_flag) { /* Run the game */ run(&st, &ui); } else { if (server_flag) run_server(&st, val_clients_num, val_server_port); else run_client(&st, &ui, val_server_addr, val_server_port, val_client_port); } /* Restore the teminal state */ echo(); curs_set(1); clear(); endwin(); if (!multiplayer_flag || server_flag) printf ("Random seed was %i\n", st.map_seed); free(val_server_addr); free(val_server_port); free(val_client_port); return 0; } /*****************************************************************************/ /* SIGIO Signal Handler */ /*****************************************************************************/ int dialog_quit_confirm(struct state *st, struct ui *ui) { output_dialog_quit_on(st, ui); int done = 0; int finished = 0; char buf[1]; while(!done) { if ( fread(buf, 1, 1, stdin) == 1 ) { char c = buf[0]; switch(c){ case 'y': case 'Y': case 'q': case 'Q': finished = 1; done = 1; break; case 'n': case 'N': case ESCAPE: finished = 0; done = 1; break; default: break; } } else pause(); } output_dialog_quit_off(st, ui); return finished; } int update_from_input( struct state *st, struct ui *ui ) { int c; char buf[1]; int finished=0; while ( fread(buf, 1, 1, stdin) == 1 ) { c = buf[0]; int cursi = ui->cursor.i; int cursj = ui->cursor.j; /*ndelay = 0; */ switch (c) { case 'Q': case 'q': finished = dialog_quit_confirm(st, ui); /* quit program */ break; case 'f': st->prev_speed = st->speed; st->speed = faster(st->speed); break; case 's': st->prev_speed = st->speed; st->speed = slower(st->speed); break; case 'p': if (st->speed == sp_pause) st->speed = st->prev_speed; else { st->prev_speed = st->speed; st->speed = sp_pause; } break; case 'h': case K_LEFT: cursi--; break; case 'l': case K_RIGHT: cursi++; break; case 'k': case K_UP: cursj--; if (cursj % 2 == 1) cursi++; break; case 'j': case K_DOWN: cursj++; if (cursj % 2 == 0) cursi--; break; case ' ': if (st->fg[st->controlled].flag[ui->cursor.i][ui->cursor.j] == 0) add_flag (&st->grid, &st->fg[st->controlled], ui->cursor.i, ui->cursor.j, FLAG_POWER); else remove_flag (&st->grid, &st->fg[st->controlled], ui->cursor.i, ui->cursor.j, FLAG_POWER); break; case 'x': remove_flags_with_prob (&st->grid, &st->fg[st->controlled], 1.0); break; case 'c': remove_flags_with_prob (&st->grid, &st->fg[st->controlled], 0.5); break; case 'r': case 'v': build (&st->grid, &st->country[st->controlled], st->controlled, ui->cursor.i, ui->cursor.j); break; case ESCAPE: case 91: break; } cursi = IN_SEGMENT(cursi, 0, st->grid.width-1); cursj = IN_SEGMENT(cursj, 0, st->grid.height-1); if ( is_visible(st->grid.tiles[cursi][cursj].cl) ) { ui->cursor.i = cursi; ui->cursor.j = cursj; } } return finished; } /* client version */ int update_from_input_client ( struct state *st, struct ui *ui, int sfd, struct addrinfo *srv_addr) { int c; char buf[1]; int finished=0; while ( fread(buf, 1, 1, stdin) == 1 ) { c = buf[0]; switch (c){ case 'q': case 'Q': finished = dialog_quit_confirm(st, ui); /* quit program */ break; default: finished = client_process_input (st, ui, c, sfd, srv_addr); } } return finished; } /* server version */ int update_from_input_server ( struct state *st ) { int c; char buf[1]; int finished=0; while ( fread(buf, 1, 1, stdin) == 1 ) { c = buf[0]; switch (c) { case 'q': case 'Q': finished = 1; break; } } return finished; } /*****************************************************************************/ /* SIGALRM Signal Handler */ /*****************************************************************************/ /* SIGALRM handler -- moves string on the screen when the signal is received */ void on_timer(int signum) { time_to_redraw = 1; // refresh(); } Makefile0000644000175000017500000000230012174700315012411 0ustar sicnesssicnessSHELL = /bin/sh CC = gcc INSTALL = install EXEC = curseofwar PREFIX ?= /usr MANPREFIX = $(PREFIX)/share/man BINDIR = $(DESTDIR)$(PREFIX)/bin MANDIR = $(DESTDIR)$(MANPREFIX)/man6 DOCDIR = $(DESTDIR)$(PREFIX)/share/doc/$(EXEC) SRCS = $(wildcard *.c) HDRS = $(wildcard *.h) OBJS = $(patsubst %.c,%.o,$(SRCS)) EXECS = $(EXEC) CFLAGS += -Wall -O2 LDLIBS += -lncurses -lm VERSION=`cat VERSION` .PHONY: all clean cleanall all: $(EXEC) clean: -rm -f $(OBJS) $(EXECS) %.o: %.c $(HDRS) $(CC) $(CPPFLAGS) $(CFLAGS) -c $(patsubst %.o,%.c,$@) $(EXEC): $(OBJS) $(CC) $(CFLAGS) $(LDFLAGS) grid.o state.o king.o network.o output.o client.o server.o main.o $(LDLIBS) -o $(EXEC) install: all $(INSTALL) -m 755 -D $(EXEC) $(BINDIR)/$(EXEC) $(INSTALL) -m 755 -d $(MANDIR) -sed "s/%VERSION%/$(VERSION)/g" $(EXEC).6 | gzip -c > $(MANDIR)/$(EXEC).6.gz -chmod 644 $(MANDIR)/$(EXEC).6.gz $(INSTALL) -m 755 -d $(DOCDIR) -cat CHANGELOG | gzip -c > $(DOCDIR)/changelog.gz -chmod 644 $(DOCDIR)/changelog.gz install-strip: $(INSTALL) -D -s $(EXEC) $(BINDIR)/$(EXEC) uninstall: -rm $(BINDIR)/$(EXEC) -rm -f $(MANDIR)/$(EXEC).6.gz -rm $(DOCDIR)/changelog.gz show-path: @echo would install to ${BINDIR} messaging.h0000644000175000017500000000342312170266401013105 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #ifndef _MESSAGING_H #define _MESSAGING_H #include #include "common.h" /* messages from from a client to a server */ #define MSG_C_CONNECT 1 #define MSG_C_BUILD 20 #define MSG_C_FLAG_ON 21 #define MSG_C_FLAG_OFF 22 #define MSG_C_FLAG_OFF_ALL 23 #define MSG_C_FLAG_OFF_HALF 24 #define MSG_C_IS_ALIVE 30 #define MSG_C_PAUSE 40 #define MSG_C_UNPAUSE 41 /* message from a server to a client */ #define MSG_S_CONN_ACCEPTED 5 #define MSG_S_CONN_REJECTED 6 #define MSG_S_STATE 10 struct msg_c_data { uint8_t i; uint8_t j; uint8_t info; }; struct msg_s_data { uint8_t control; /* player you control */ uint8_t pause_request; uint32_t gold [MAX_PLAYER]; uint32_t time; uint8_t width; uint8_t height; uint8_t flag [MAX_WIDTH][MAX_HEIGHT]; uint8_t owner [MAX_WIDTH][MAX_HEIGHT]; uint16_t pop [MAX_WIDTH][MAX_HEIGHT]; uint8_t tile [MAX_WIDTH][MAX_HEIGHT]; }; #endif network.c0000644000175000017500000001337612175132507012630 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #include "network.h" void *get_in_addr(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return &(((struct sockaddr_in*)sa)->sin_addr); } return &(((struct sockaddr_in6*)sa)->sin6_addr); } /* returns port number */ in_port_t get_in_port(struct sockaddr *sa) { if (sa->sa_family == AF_INET) { return (((struct sockaddr_in*)sa)->sin_port); } return (((struct sockaddr_in6*)sa)->sin6_port); } #define SIZE6 16 /* Equality of two arrays of size SIZE6 (two IPv6 addresses) */ int eq_6_addr (uint8_t s1[SIZE6], uint8_t s2[SIZE6]) { int i; for(i=0; isa_family == AF_INET && s2->sa_family == AF_INET && ((struct sockaddr_in*)s1)->sin_addr.s_addr == ((struct sockaddr_in*)s2)->sin_addr.s_addr ) || /* IPv6 equality */ ( s1->sa_family == AF_INET6 && s2->sa_family == AF_INET6 && eq_6_addr ( ((struct sockaddr_in6*)s1)->sin6_addr.s6_addr, ((struct sockaddr_in6*)s2)->sin6_addr.s6_addr ) ) ) && ( get_in_port(s1) == get_in_port(s2) ); } /* Initialize server socket */ int server_init (int *p_sfd, char*str_port) { struct addrinfo hints; struct addrinfo *result, *rp; int s; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */ hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */ hints.ai_protocol = 0; /* Any protocol */ hints.ai_canonname = NULL; hints.ai_addr = NULL; hints.ai_next = NULL; s = getaddrinfo(NULL, str_port, &hints, &result); if (s != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); return -1; } /* getaddrinfo() returns a list of address structures. * Try each address until we successfully bind(2). * If socket(2) (or bind(2)) fails, we (close the socket * and) try the next address. */ for (rp = result; rp != NULL; rp = rp->ai_next) { *p_sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (*p_sfd == -1) continue; if (bind(*p_sfd, rp->ai_addr, rp->ai_addrlen) == 0) break; /* Success */ close(*p_sfd); } if (rp == NULL) { /* No address succeeded */ fprintf(stderr, "Could not bind\n"); return -1; } freeaddrinfo(result); /* No longer needed */ return 0; } /* initialize client socket, and fill struct addrinfo *srv (split into two functions!) */ int client_init_session (int *p_sfd, char* str_my_port, struct addrinfo *srv, char *str_server_addr, char *str_server_port) { struct addrinfo hints; struct addrinfo *result, *rp; int s; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */ hints.ai_flags = AI_PASSIVE; /* For wildcard IP address */ hints.ai_protocol = 0; /* Any protocol */ hints.ai_canonname = NULL; hints.ai_addr = NULL; hints.ai_next = NULL; s = getaddrinfo(NULL, str_my_port, &hints, &result); if (s != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); return -1; } /* getaddrinfo() returns a list of address structures. * Try each address until we successfully bind(2). * If socket(2) (or bind(2)) fails, we (close the socket * and) try the next address. */ for (rp = result; rp != NULL; rp = rp->ai_next) { *p_sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (*p_sfd == -1) continue; if (bind(*p_sfd, rp->ai_addr, rp->ai_addrlen) == 0) break; /* Success */ close(*p_sfd); } if (rp == NULL) { /* No address succeeded */ fprintf(stderr, "Could not bind\n"); return -1; } freeaddrinfo(result); /* No longer needed */ /* Second half */ /* get info about the server */ memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */ hints.ai_socktype = SOCK_DGRAM; /* Datagram socket */ hints.ai_flags = 0; hints.ai_protocol = 0; /* Any protocol */ s = getaddrinfo(str_server_addr, str_server_port, &hints, &result); if (s != 0) { fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(s)); return -1; } /* for (rp = result; rp != NULL; rp = rp->ai_next) { int tmp_df = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); if (tmp_df == -1) continue; close(tmp_df); } */ rp = result; if (rp == NULL) { /* No address succeeded */ fprintf(stderr, "Could not connect\n"); return -1; } *srv = *rp; return 0; } network.h0000644000175000017500000000300612175132507012622 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #ifndef _NETWORK_H #define _NETWORK_H #include #include #include #include #include #include #include #define MSG_BUF_SIZE 50000 /* get sockaddr, IPv4 or IPv6 (UGLY): */ void *get_in_addr(struct sockaddr *sa); /* returns port number */ in_port_t get_in_port(struct sockaddr *sa); /* Check if two sockaddr_storage structures match, returns 1 if they do, or 0 otherwise */ int sa_match (struct sockaddr_storage *sa1, struct sockaddr_storage *sa2); int server_init(int*, char*); int client_init_session(int*, char*, struct addrinfo *p_addr, char*, char*); #endif output.c0000644000175000017500000002777612173210021012472 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #include "output.h" #include #include /* Macros to map tiles location (i,j) to its position on the screen */ #define POSY(ui,i,j) ((j)+1) #define POSX(ui,i,j) ((i)*4 + (j)*2 + 1) - (ui->xskip*(CELL_STR_LEN+1)) /* Returns a color_pair number for a player p */ int player_color(int p) { switch(p) { case 0: return 6; // Neutral case 1: return 4; // Green (player) case 2: return 5; // Blue case 3: return 3; // Red case 4: return 6; // Yellow case 5: return 7; // Magenta case 6: return 8; // Cyan case 7: return 2; // Black default: return -1; } } /* Returns output attributes for a player p */ int player_style(int p) { if (p != NEUTRAL) return A_BOLD | COLOR_PAIR(player_color(p)); else return A_NORMAL | COLOR_PAIR(player_color(p)); } void time_to_ymd(unsigned long time, int *y, int *m, int *d) { int year = time/360; int month = time - year*360; int day = month%30 + 1; month = month / 30 + 1; *y = year; *m = month; *d = day; } /* Outputs population at the tile (i,j) */ void output_units(struct ui *ui, struct tile *t, int i, int j) { int p; int num = 0; for(p=0; punits[p][citizen]; } move(POSY(ui,i,j), POSX(ui,i,j)); if (num > 400) addstr(":::"); else if (num > 200) addstr(".::"); else if (num > 100) addstr(" ::"); else if (num > 50) addstr(".:."); else if (num > 25) addstr(".: "); else if (num > 12) addstr(" : "); else if (num > 6) addstr("..."); else if (num > 3) addstr(".. "); else if (num > 0) addstr(" . "); } /* A function to display information about the available keys that can be used by the player */ void output_key (int y, int x, char *key, int key_style, char *s, int s_style) { int keylen = strlen(key); attrset(key_style); mvaddstr(y, x+1, key); attrset(s_style); mvaddch(y, x, '['); mvaddch(y, x+keylen+1, ']'); mvaddstr(y, x+keylen+3, s); } /* the main output function */ void output_grid(struct state *st, struct ui *ui, int ktime) { int i, j; for (i=0; igrid.width; ++i) { for (j=0; jgrid.height; ++j) { move(POSY(ui,i,j), POSX(ui,i,j)-1); switch (st->grid.tiles[i][j].cl) { case mountain: attrset(A_NORMAL | COLOR_PAIR(4)); addstr(" /\\^ "); break; case mine: attrset(A_NORMAL | COLOR_PAIR(4)); addstr(" /$\\ "); move(POSY(ui,i,j), POSX(ui,i,j)+1); if (st->grid.tiles[i][j].pl != NEUTRAL) attrset(A_BOLD | COLOR_PAIR(6)); else attrset(A_NORMAL | COLOR_PAIR(6)); addstr("$"); break; /* case abyss: attrset(A_NORMAL | COLOR_PAIR(6)); addstr(" % "); break; */ case grassland: attrset(A_NORMAL | COLOR_PAIR(4)); addstr(" - "); break; case village: attrset(player_style(st->grid.tiles[i][j].pl)); addstr(" n "); break; case town: attrset(player_style(st->grid.tiles[i][j].pl)); addstr(" i=i "); break; case castle: attrset(player_style(st->grid.tiles[i][j].pl)); addstr(" W#W "); break; default:; } attrset(A_NORMAL | COLOR_PAIR(1)); if (st->grid.tiles[i][j].cl == grassland) { attrset(player_style(st->grid.tiles[i][j].pl)); output_units(ui, &st->grid.tiles[i][j], i, j); attrset(A_NORMAL | COLOR_PAIR(1)); } int p; for (p=0; pcontrolled) { if (st->fg[p].flag[i][j] != 0 && ((ktime + p) / 5)%10 < 10) { attrset(player_style(p)); mvaddch(POSY(ui,i,j), POSX(ui,i,j), 'x'); attrset(A_NORMAL | COLOR_PAIR(1)); } } } /* for of war */ int k; int b = 0; for(k=0; k= 0 && i+di < st->grid.width && j+dj >= 0 && j+dj < st->grid.height && (st->grid.tiles[i+di][j+dj].units[st->controlled][citizen] > 0) ) { b = 1; break; } } if (false && !b){ move(POSY(ui,i,j), POSX(ui,i,j)-1); addstr(" "); } // player 1 flags if (st->fg[st->controlled].flag[i][j] != 0 && (ktime / 5)%10 < 10) { attrset(A_BOLD | COLOR_PAIR(1)); mvaddch(POSY(ui,i,j), POSX(ui,i,j)+2, 'P'); attrset(A_NORMAL | COLOR_PAIR(1)); } } } i = ui->cursor.i; j = ui->cursor.j; attrset(A_BOLD | COLOR_PAIR(1)); mvaddch(POSY(ui,i,j), POSX(ui,i,j)-1, '('); mvaddch(POSY(ui,i+1,j), POSX(ui,i+1,j)-1, ')'); attrset(A_NORMAL | COLOR_PAIR(1)); /* print populations at the cursor */ int p; char buf[32]; int y = POSY(ui,0, st->grid.height) + 1; mvaddstr(y, 0, " Gold:"); sprintf(buf, "%li ", st->country[st->controlled].gold); attrset(player_style(st->controlled)); mvaddstr(y, 8, buf); mvaddstr(y, 8, buf); attrset(A_NORMAL | COLOR_PAIR(1)); mvaddstr(y+1, 0, " Prices: 150, 300, 600."); move(y+2, 1); addstr("Speed: "); attrset(player_style(st->controlled)); switch(st->speed){ case sp_fastest: addstr("Fastest"); break; case sp_faster: addstr("Faster "); break; case sp_fast: addstr("Fast "); break; case sp_normal: addstr("Normal "); break; case sp_slow: addstr("Slow "); break; case sp_slower: addstr("Slower "); break; case sp_slowest: addstr("Slowest"); break; case sp_pause: addstr("Pause "); break; } attrset(A_BOLD | COLOR_PAIR(1)); int text_style = A_NORMAL | COLOR_PAIR(1); int key_style = player_style(st->controlled); output_key (y+4, 1, "Space", key_style, "add/remove a flag", text_style); output_key (y+5, 1, "R or V", key_style, "build", text_style); output_key (y+4, 30, "X", key_style, "remove all flags", text_style); output_key (y+5, 30, "C", key_style, "remove 50\% of flags", text_style); output_key (y+5, 57, "S", key_style, "slow down", text_style); output_key (y+4, 57, "F", key_style, "speed up", text_style); output_key (y+6, 57, "P", key_style, "pause", text_style); mvaddstr(y+1, 30, " Population at the cursor:"); for(p=0; pgrid.tiles[i][j].units[p][citizen]); mvaddstr(y+2, 30 + p*5, buf); /* sprintf(buf, "%10li", st->country[p].gold); mvaddstr(y+2, 10 + p*12, buf); */ } attrset(A_NORMAL | COLOR_PAIR(1)); mvaddstr(y, 65, "Date:"); attrset(key_style); int year, month, day; time_to_ymd(st->time, &year, &month, &day); sprintf(buf, "%i-%02i-%02i ", year, month, day); mvaddstr(y, 72, buf); refresh(); } void output_dialog_quit_on(struct state *st, struct ui *ui) { int y = POSY(ui,st->grid.width/2, st->grid.height/2) ; int x = POSX(ui,st->grid.width/2, st->grid.height/2) - 8; attrset(A_NORMAL | COLOR_PAIR(1)); mvaddstr(y-2, x, " "); mvaddstr(y-1, x, " Quit? [Y/N] "); mvaddstr(y+0, x, " [Q/Esc] "); mvaddstr(y+1, x, " "); int text_style = A_NORMAL | COLOR_PAIR(1); int key_style = player_style(st->controlled); output_key (y-1, x+9, "Y/N", key_style, "", text_style); /* output_key (y+0, x+8, "Q/Esc", key_style, "", text_style); */ attrset(A_NORMAL | COLOR_PAIR(1)); refresh(); } void output_dialog_quit_off(struct state *st, struct ui *ui) { int y = POSY(ui,st->grid.width/2, st->grid.height/2); int x = POSX(ui,st->grid.width/2, st->grid.height/2) - 8; mvaddstr(y-1, x, " "); mvaddstr(y+0, x, " "); refresh(); } #define TIMELINE_HEIGHT 5 /* helper function to output sorted values */ void insert_position(int pl[TIMELINE_HEIGHT], float val[TIMELINE_HEIGHT], int i, int p, float v) { if (i>=TIMELINE_HEIGHT) return; if (pl[i] == 0) { pl[i] = p; val[i] = v; } else { if (val[i] >= v) { insert_position(pl, val, i+1, p, v); } else { int tp = pl[i]; float tv = val[i]; pl[i] = p; val[i] = v; insert_position(pl, val, i+1, tp, tv); } } } void output_timeline(struct state *st, struct ui *ui) { struct timeline *t = &st->timeline; int non_zero[MAX_PLAYER]; int p, i; int v; for(p=0; pmark; ++i) { v = t->data[p][i]; if (v >= 0.1) non_zero[p] = 1; } } float max=0.0; float min=0.0; for(p=0; pdata[p][0]; min = max; } } for(p=0; pmark; ++i) { v = t->data[p][i]; if (v>max) max = v; if (vgrid.height) + 8; int x0 = 2; /* clean plotting area */ int j; for(j=0; jmark; ++i) { time_to_ymd(t->time[i-1], &y1, &m1, &d1); time_to_ymd(t->time[i], &y2, &m2, &d2); if (y1 < y2) { sprintf(buf, "%i", y2); mvaddstr(y0+TIMELINE_HEIGHT-1+1, x0+i+x_shift_year, buf); for(j=0; jmark; ++i) { char c = '-'; for(pp=0; pp<=MAX_PLAYER; ++pp) { p = (pp+i) % MAX_PLAYER; if (pp == MAX_PLAYER) {p = st->controlled; c = '*';} if (non_zero[p]) { attrset(player_style(p)); dx = i; v = (int) round( (TIMELINE_HEIGHT-1) * (t->data[p][i] - min) * one_over_delta ); dy = TIMELINE_HEIGHT-1 - v; dy = IN_SEGMENT(dy, 0, TIMELINE_HEIGHT-1); if (i==t->mark) /* save the row for later use */ store_pl_row[p] = dy; /* 0 = maximum, TIMELINE_HEIGHT-1 = minimum */ mvaddch(y0+dy, x0+dx, c); } } } attrset(A_NORMAL | COLOR_PAIR(1)); sprintf(buf, "%g", max); mvaddstr(y0, x0, buf); sprintf(buf, "%g", min); mvaddstr(y0+TIMELINE_HEIGHT-1, x0, buf); /* add values */ int pl_arr[TIMELINE_HEIGHT]; float val_arr[TIMELINE_HEIGHT]; for(i=0; idata[p][t->mark]); } for (i=0; imark + 3; dy = i; sprintf(buf, "%g", val_arr[i]); attrset(player_style(pl_arr[i])); mvaddstr(y0+dy, x0+dx, buf); } } attrset(A_NORMAL | COLOR_PAIR(1)); } output.h0000644000175000017500000000262612173210021012462 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #ifndef _OUTPUT_H #define _OUTPUT_H #define CELL_STR_LEN 3 #include "grid.h" #include "state.h" /* output_grid(st, ktime) the main function to update the screen, st is the current game state, ktime is the timestep (can be used for animation primarily) */ void output_grid(struct state *st, struct ui *ui, int ktime); void output_dialog_quit_on(struct state *st, struct ui *ui); void output_dialog_quit_off(struct state *st, struct ui *ui); /* plot timeline */ void output_timeline(struct state *st, struct ui *ui); #endif pixmaps/0000755000175000017500000000000012172704547012450 5ustar sicnesssicnesspixmaps/curseofwar-32x32.xpm0000644000175000017500000000242312172704547016136 0ustar sicnesssicness/* XPM */ static char * icon32x32_3_xpm[] = { "32 32 6 1", " c None", ". c #000000", "+ c #FFFFFF", "@ c #FFAE00", "# c #D7970D", "$ c #6BE73F", " ", " ", " ", " . ", " .+..... ", " .@@@@@+. ", " .@@@@@+...... ", " .@@@@@+####. ", " .@@@@@@+###. ", " .@@@@@@+##. ", " .@@@@@@+##. ", " .#.....####. ", " .# ..#####. ", " .# ........ ", " .# ", " .# ", " .# ", " .# ", " ............ ............ ", " .+$$$..+$$$.......+$$$..+$$$. ", " ..$$....$$..+$.+$..$$....$$.. ", " .$$.$$.$$..$$.$$..$$.$$.$$. ", " .$$.$$.$$.$$$$$$$.$$.$$.$$. ", " .$$$$$$$$..$$.$$..$$$$$$$$. ", " ..$$$$$$...$$.$$...$$$$$$.. ", " .$$..$$..$$$$$$$..$$..$$. ", " .$$..$$...$$.$$...$$..$$. ", " ........ ....... ........ ", " ", " ", " ", " "}; pixmaps/curseofwar-16x16.xpm0000644000175000017500000000072312172704547016143 0ustar sicnesssicness/* XPM */ static char * icon16x16_2_xpm[] = { "16 16 6 1", " c None", ". c #000000", "+ c #FFAE00", "@ c #FFFFFF", "# c #D7970D", "$ c #6BE73F", " ...... ", " .++++@..... ", " .++++@###. ", " .++++@###. ", " .++++@##. ", " .++++@##. ", " .+....###. ", " .# ...... ", " .# ", "...#... ... ...", ".$...$. .$...$.", ".$.$.$....$.$.$.", ".$.$.$.$$.$.$.$.", ".$$.$$.$$.$$.$$.", ".$...$....$...$.", "... ... ... ..."}; README0000644000175000017500000001637612173210021011640 0ustar sicnesssicness __ ____ / ] / __ \_ _ ___ ___ ___ __ _| |_ /\ /\___ ___ _/ / \/ | |X _/ __/ __\ / \ / \ \ /\ / /__ \X _/ \ X | | | | |__ | __X | X || | \ V V // _ | | \ \__/\ __X_| \___/___/ \___/| | \ /\ / \___X_| \____/ |/ V V Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. Summary ======= This is a fast-paced action strategy game for Linux implemented using ncurses user interface. Unlike most RTS, you are not controlling units, but focus on high-level strategic planning: Building infrastructure, securing resources, and moving your armies. The core game mechanics turns out to be quite close to WWI-WWII type of warfare, however, there is no explicit reference to any historical period. See "How to play" section for more details. Build, Install, Uninstall ========================= Build: $ make Install: # make install Uninstall: # make uninstall Command line arguments ====================== -W width Map width (default is 21) -H height Map height (default is 21) -S [rhombus|rect|hex] Map shape (rectangle is default). Max number of countries N=4 for rhombus and rectangle, and N=6 for the hexagon. -l [2|3| ... N] Sets L, the number of countries (default is N). -i [0|1|2|3|4] Inequality between the countries (0 is the lowest, 4 in the highest). -q [1|2| ... L] Choose player's location by its quality: 1 = the best available on the map, and L = the worst. Only in the singleplayer mode. -r Absolutely random initial conditions, overrides options -l, -i, and -q. -d [ee|e|n|h|hh] Difficulty level (AI) from the easiest to the hardest (default is normal). -s [p|sss|ss|s|n|f|ff|fff] Game speed from the slowest to the fastest (default is normal). -R seed Specify a random seed (unsigned integer) for map generation. -T Show the timeline. -E [1|2| ... L] Start a server for not more than L clients. -e port Server's port (19140 is default). -C IP Start a client and connect to the provided server's IP-address. -c port Clients's port (19150 is default). -h Display help information How to play =========== A good and easy mode to start playing: $ curseofwar -i4 -q1 -dee Or, on a smaller map: $ curseofwar -i4 -q1 -dee -W16 -H16 Normally, the game starts with 4 small countries in the corners of the map. You start as the ruler of the Green country, and your goal is to conquer the whole map. Tiles ----- The map is made of hexagonal tiles. They are: /\^ Mountains, cannot be populated /$\ Gold mines, cannot be populated too. This is the source of gold for your country. To control a mine, surround it with your army n Villages, have the slowest population growth (+10%) i=i Towns, average population growth (+20%) W#W Fortresses, high population growth (+30%) - Grassland, normal habitable territory People ------ People are your primary resource. Thriving popluation is essential for your victory. Every tile can support at most 499 people from each country. When people from more than one country occupy the same tile, they fight. The country that has the highest population at the tile is called the tile owner. The population of the tile owner is shown on all grassland tiles as follows: . 1 - 3 citizens .. 4 - 6 ... 7 - 12 : 13 - 25 .: 26 - 50 .:. 51 - 100 :: 101 - 200 .:: 201 - 400 ::: 400 - 499 People migrate from highly populated tiles to less populated tiles. Population grows only in cities. In villages by 10%, in towns by 20%, and fortresses by 30% every simulation step. By controlling cities, you control their surrounding territory. Flags ----- Every country can put flags on the map. Flags change migration rates, so that people of your country start gathering at the tiles with flags. Player's flags are shown as white "P" on the right side of a tile. Flags of the computer opponents are shown as "x" on the left side of a tile. The flags can be used to increase population of your own cities, as well as for conquering foreign territories. When countries are fighting for a city, and if the damage to the defender's army is significant, the city can be destroyed: A fortress becomes a town, a town becomes a village, and the village gets completely burnt by the invaders. Countries --------- Computer opponents differ in personality, and it affects the way they fight. Controls ======== Arrow keys and H, J, K, L are for moving the cursor R or V build village -> town -> fortress Space add/remove a flag X remove all your flags C remove a half of your flags S slower F faster Q quit Multiplayer =========== To start a server for two players: $ ./curseofwar -E 2 To start a client and connect to the server: $ ./curseofwar -C To specify ports, use -e option for server's port, and -c option for client's port. By default, servers are using port 19140, and clients are using port 19150. Examples: Start a server for a single client using port 11111 $ ./curseofwar -E 1 -e 11111 To connect to it: $ ./curseofwar -C -e 11111 Alternatively, to connect to it using port 12345 on the client's side: $ ./curseofwar -C -c 12345 -e 11111 Note that all needed map options must be setup when you start a server, the map and other data are transmitted to clients, once they are connected. Example: Server for 3 clients, no computer opponents, hexagonal map, and equal conditions for all: $ ./curseofwar -E3 -l3 -S hex -i0 Game speed cannot be changed by a client, so it must be set initially by the server. Not all data is sent to clients (e.g. info about population is not sent in full). Multiplayer mode is at relatively early development stage. Changes may occure at any moment. When you play with other people, make sure that you are using the same version of the game. Hopefully, game's client-server communication protocol will be improved in future. All communication is made via UDP. Please, report you problems with multiplayer. License ======= Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . server.c0000644000175000017500000000654612170266401012442 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #include "server.h" #include "messaging.h" void server_send_msg_s_state (int sfd, struct client_record cl[], int cl_num, struct state *st) { static uint8_t buf[MSG_BUF_SIZE]; static struct msg_s_data msg_data; int p, i, j; for (p=0; pcountry[p].gold ); msg_data.width = st->fg[p].width; msg_data.height =st->fg[p].height; } msg_data.time = htonl( st->time ); msg_data.control = 0; /* specify for every client */ msg_data.width = st->grid.width; msg_data.height = st->grid.height; for (i=0; igrid.tiles[i][j].cl; int owner = st->grid.tiles[i][j].pl; msg_data.owner[i][j] = owner; msg_data.pop[i][j] = htons( st->grid.tiles[i][j].units[owner][citizen] ); msg_data.flag[i][j] = 0; for (p=0; pfg[p].flag[i][j]) msg_data.flag[i][j] |= (1<grid, &st->country[pl], pl, cm->i, cm->j); break; case MSG_C_FLAG_ON: add_flag (&st->grid, &st->fg[pl], cm->i, cm->j, FLAG_POWER); break; case MSG_C_FLAG_OFF: remove_flag (&st->grid, &st->fg[pl], cm->i, cm->j, FLAG_POWER); break; case MSG_C_FLAG_OFF_ALL: remove_flags_with_prob (&st->grid, &st->fg[pl], 1.0); break; case MSG_C_FLAG_OFF_HALF: remove_flags_with_prob (&st->grid, &st->fg[pl], 0.5); break; case MSG_C_IS_ALIVE: break; case MSG_C_PAUSE: case MSG_C_UNPAUSE: default: break; } } int server_process_msg_c (uint8_t buf[MSG_BUF_SIZE], int nread, struct state *st, int pl) { uint8_t msg; static struct msg_c_data msg_data; if (nread >= 1 + sizeof(struct msg_c_data)) { msg = buf[0]; memcpy(&msg_data, buf+1, sizeof(struct msg_c_data)); process_msg_c(st, pl, msg, &msg_data); } else {return -1;} return msg; } int server_get_msg (uint8_t buf[MSG_BUF_SIZE], int nread) { if (nread>=1) return buf[0]; else return 0; } server.h0000644000175000017500000000304112170266401012432 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #ifndef _SERVER_H #define _SERVER_H /* #include */ #include #include "network.h" #include "common.h" #include "state.h" #define MAX_CLIENT MAX_PLAYER struct client_record { int pl; int id; char* name; struct sockaddr_storage sa; }; /* multiplayer modes: multi_lobby = waiting for clients, multi_play = playing, */ enum server_mode {server_mode_lobby, server_mode_play}; void server_send_msg_s_state (int sfd, struct client_record cl[], int cl_num, struct state *st); int server_process_msg_c (uint8_t buf[MSG_BUF_SIZE], int nread, struct state *st, int pl); int server_get_msg (uint8_t buf[MSG_BUF_SIZE], int nread); #endif state.c0000644000175000017500000002676212173210021012244 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #include "state.h" #include #include enum config_speed faster(enum config_speed sp){ switch (sp) { case sp_pause: return sp_slowest; case sp_slowest: return sp_slower; case sp_slower: return sp_slow; case sp_slow: return sp_normal; case sp_normal: return sp_fast; case sp_fast: return sp_faster; default: return sp_fastest; } } enum config_speed slower(enum config_speed sp){ switch (sp) { case sp_fastest: return sp_faster; case sp_faster: return sp_fast; case sp_fast: return sp_normal; case sp_normal: return sp_slow; case sp_slow: return sp_slower; case sp_slower: return sp_slowest; default: return sp_pause; } } void state_init(struct state *s, int w, int h, enum stencil shape, unsigned int map_seed, int keep_random, int locations_num, int clients_num, int conditions, int inequality, enum config_speed speed, enum config_dif dif, int timeline_flag){ s->speed = speed; s->prev_speed = s->speed; s->dif = dif; s->map_seed = map_seed; s->conditions = conditions; s->inequality = inequality; s->time = (1850 + rand()%100) * 360 + rand()%360; /* player controlled from the keyboard */ s->controlled = 1; /* int players[] = {7, 2, 3, 5}; */ /* int players[] = {2, 3, 4, 5, 6, 7}; */ int all_players[] = {1, 2, 3, 4, 5, 6, 7}; int comp_players[MAX_PLAYER]; int comp_players_num = 7 - clients_num; s->kings_num = comp_players_num; int ui_players[MAX_PLAYER]; int ui_players_num = clients_num; int i; for (i=0; i<7; ++i) { if (iking[j], i+1, opportunist, &s->grid, s->dif); break; case 2: king_init (&s->king[j], i+1, one_greedy, &s->grid, s->dif); break; case 3: king_init (&s->king[j], i+1, none, &s->grid, s->dif); break; case 4: king_init (&s->king[j], i+1, aggr_greedy, &s->grid, s->dif); break; case 5: king_init (&s->king[j], i+1, noble, &s->grid, s->dif); break; case 6: king_init (&s->king[j], i+1, persistent_greedy, &s->grid, s->dif); break; } } } /* Initialize map generation with the map_seed */ srand(s->map_seed); /* Map generation starts */ { int conflict_code = 0; do { grid_init(&s->grid, w, h); /* starting locations arrays */ struct loc loc_arr[MAX_AVLBL_LOC]; int available_loc_num = 0; int d = 2; apply_stencil(shape, &s->grid, d, loc_arr, &available_loc_num); /* conflict mode */ conflict_code = 0; if (!keep_random) conflict_code = conflict(&s->grid, loc_arr, available_loc_num, comp_players, comp_players_num, locations_num, ui_players, ui_players_num, s->conditions, s->inequality); } while(conflict_code != 0 || !is_connected(&s->grid)); } /* Map is ready */ int p; for(p = 0; pfg[p], w, h); s->country[p].gold = 0; } /* kings evaluate the map */ for(p = 0; p < s->kings_num; ++p) { king_evaluate_map(&s->king[p], &s->grid, dif); } /* Zero timeline */ s->show_timeline = timeline_flag; s->timeline.mark = -1; for(i=0; itimeline.time[i] = s->time; for(p=0; ptimeline.data[p][i] = 0.0; } } } void ui_init(struct state *s, struct ui *ui) { /* cursor location */ ui->cursor.i = s->grid.width/2; ui->cursor.j = s->grid.height/2; int i, j; for (i=0; igrid.width; ++i) { for (j=0; jgrid.height; ++j) { if (s->grid.tiles[i][j].units[s->controlled][citizen] > s->grid.tiles[ui->cursor.i][ui->cursor.j].units[s->controlled][citizen]) { ui->cursor.i = i; ui->cursor.j = j; } } } /* find the leftmost visible tile */ ui->xskip = MAX_WIDTH * 2 + 1; for(i=0; igrid.width; ++i) for(j=0; jgrid.height; ++j) if(is_visible(s->grid.tiles[i][j].cl)) { int x = i*2 + j; if (ui->xskip > x) ui->xskip = x; } ui->xskip = ui->xskip/2; } #define GROWTH_1 1.10 #define GROWTH_2 1.20 #define GROWTH_3 1.30 #define ATTACK 0.1 #define MOVE 0.05 #define CALL_MOVE 0.10 float growth(enum tile_class t) { switch(t) { case village: return GROWTH_1; case town: return GROWTH_2; case castle: return GROWTH_3; default: return 0; } } int rnd_round(float x) { int i = (int) x; if ( (float)rand() / (float)RAND_MAX < (x - i) ) i++; return i; } void kings_move(struct state *s) { int i; int ev = 0; for(i=0; ikings_num; ++i) { int pl = s->king[i].pl; place_flags(&s->king[i], &s->grid, &s->fg[pl]); int code = builder_default(&s->king[i], &s->country[pl], &s->grid, &s->fg[pl]); ev = ev || (code == 0); } if (ev) { for(i=0; ikings_num; ++i) { king_evaluate_map(&s->king[i], &s->grid, s->dif); } } } void simulate(struct state *s) { int i, j; struct tile (* t) [MAX_HEIGHT] = s->grid.tiles; int enemy_pop [MAX_PLAYER]; int my_pop [MAX_PLAYER]; int need_to_reeval = 0; /* increment time */ s->time++; /* per tile events */ for(i=0; igrid.width; ++i) { for(j=0; jgrid.height; ++j) { /* mines ownership */ if (t[i][j].cl == mine){ int k; int owner = NEUTRAL; for(k=0; k= 0 && i+di < s->grid.width && j+dj >= 0 && j+dj < s->grid.height && is_inhabitable (t[i+di][j+dj].cl) ) { int pl = t[i+di][j+dj].pl; if (owner == NEUTRAL) owner = pl; else if (owner != pl && pl != NEUTRAL) owner = -1; } } if (owner != -1) t[i][j].pl = owner; else t[i][j].pl = NEUTRAL; if (t[i][j].pl != NEUTRAL) s->country[owner].gold += 1; } /* fight */ int p; int total_pop = 0; for(p=0; p 2.0 * MAX_POP * ATTACK && is_a_city(t[i][j].cl)) { if (rand() % 1 == 0){ need_to_reeval = 1; degrade (&s->grid, i, j); } } /* determine ownership */ if (is_inhabitable(t[i][j].cl)){ t[i][j].pl = NEUTRAL; for(p=0; p t[i][j].units[t[i][j].pl][citizen]) { t[i][j].pl = p; } } } if (is_a_city(t[i][j].cl)) { /* population growth */ int owner = t[i][j].pl; int pop = t[i][j].units[owner][citizen]; float fnpop = (float) pop * growth(t[i][j].cl); int npop = rnd_round(fnpop); npop = MIN(npop, MAX_POP); /* death */ //npop = npop - rnd_round(0.01*pow(pop,1.5)); //npop = npop - rnd_round(1.0e-20 * pow(2.0,pop)); //npop = MAX(npop, 0); t[i][j].units[owner][citizen] = npop; } } } /* migration */ int k, di, dj, p; int i_start, i_end, i_inc; int j_start, j_end, j_inc; if(rand()%2 == 0) { i_start = 0; i_end = s->grid.width; i_inc = 1; } else { i_start = s->grid.width-1; i_end = -1; i_inc = -1; } if(rand()%2 == 0) { j_start = 0; j_end = s->grid.height; j_inc = 1; } else { j_start = s->grid.height-1; j_end = -1; j_inc = -1; } for(i=i_start; i!=i_end; i+=i_inc) { for(j=j_start; j!=j_end; j+=j_inc) { for(p=0; p= 0 && i+di < s->grid.width && j+dj >= 0 && j+dj < s->grid.height && is_inhabitable (t[i+di][j+dj].cl) ) { int pop = t[i][j].units[p][citizen]; int dcall = MAX(0, s->fg[p].call[i+di][j+dj] - s->fg[p].call[i][j]); if (pop > 0) { int dpop = rnd_round (MOVE * initial_pop + CALL_MOVE * dcall * initial_pop); dpop = MIN(dpop, pop); dpop = MIN(dpop, MAX_POP - t[i+di][j+dj].units[p][citizen]); t[i+di][j+dj].units[p][citizen] += dpop; t[i][j].units[p][citizen] -= dpop; } } } } } } /* determine ownership again */ for(i=0; igrid.width; ++i) { for(j=0; jgrid.height; ++j) { if (is_inhabitable(t[i][j].cl)){ t[i][j].pl = NEUTRAL; for(p=0; p t[i][j].units[t[i][j].pl][citizen]) { t[i][j].pl = p; } } } } } /* Kings reevaluate the map */ if(need_to_reeval) { for(i=0; ikings_num; ++i) { king_evaluate_map(&s->king[i], &s->grid, s->dif); } } /* give gold to AI on hard difficulties */ int add_gold = 0; switch(s->dif) { case dif_hard: add_gold = 1; break; case dif_hardest: add_gold = 2; break; default: ; } for(i=0; icontrolled && s->country[i].gold>0) s->country[i].gold += add_gold; } } void update_timeline(struct state *s) { /* shortcut notation */ struct timeline *t = &s->timeline; int p, i, j; /* prepare to update */ if (t->mark+1 < MAX_TIMELINE_MARK) t->mark += 1; else { /* shift all recorded data to empty space */ for(i=0; itime[i] = t->time[i+1]; for(p=0; pdata[p][i] = t->data[p][i+1]; } } } /* insert a new datapoint at position t->mark */ t->time[t->mark] = s->time; /* we compute total population here */ for (p=0; pgrid.tiles[i][j].units[p][citizen]; } } t->data[p][t->mark] = (float)count; } /* call output_timeline to print it out */ } state.h0000644000175000017500000000674112173210021012244 0ustar sicnesssicness/****************************************************************************** Curse of War -- Real Time Strategy Game for Linux. Copyright (C) 2013 Alexey Nikolaev. 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 . ******************************************************************************/ #ifndef _STATE_H #define _STATE_H #include "common.h" #include "grid.h" #include "king.h" /* faster(s) returns a faster speed */ enum config_speed faster(enum config_speed); /* slower(s) returns a slower speed */ enum config_speed slower(enum config_speed); struct ui { struct loc cursor; int xskip; }; /* struct timeline */ struct timeline { float data[MAX_PLAYER][MAX_TIMELINE_MARK]; /* stored data */ unsigned long int time[MAX_TIMELINE_MARK]; /* time when data was recorded */ int mark; /* the most recently updated time mark. It can be used as index in two other fields, i.e. 0 <= mark < MAX_TIMELINE_MARK */ }; /* struct state Game state Members: grid in sthe map grid flag_grid[] is the array of flag grids (different for each player) country[] is the array of countries king is the array of AI opponents kings_num is the number of AI opponents controlled is the player id of the human controlled player condiitions is the initial conditions quality (0==random, 1==best, 4==worst) inequality (from 0 to 4) is the level of countries' inequality speed and dif are the game speed and the difficulty level */ struct state { struct grid grid; /* struct loc cursor; */ struct flag_grid fg [MAX_PLAYER]; struct king king [MAX_PLAYER]; int kings_num; struct timeline timeline; int show_timeline; struct country country [MAX_PLAYER]; unsigned long time; int map_seed; int controlled; int conditions; int inequality; enum config_speed speed; enum config_speed prev_speed; enum config_dif dif; }; /* state_init(&s, w, h, keep_random, speed, dif) initializes state s. w and h are the map dimensions if keep_random == 1, the map is kept random, otherwise city and player placement is not arbitrary, but players have their initial locations in the corners of the map. function conflict() is used to generate this game mode */ void state_init(struct state *s, int w, int h, enum stencil shape, unsigned int map_seed, int keep_random, int locations_num, int clients_num, int conditions, int inequality, enum config_speed speed, enum config_dif dif, int timeline_flag); /* compute the cursor location, and xskip */ void ui_init(struct state *s, struct ui *ui); /* kings_move(&s) Kings build cities and place flags */ void kings_move(struct state *s); /* simulate(&s) Performs one step of the game simulation */ void simulate(struct state *s); /* update_timeline(&s) */ void update_timeline(struct state *s); #endif VERSION0000644000175000017500000000000612175013122012014 0ustar sicnesssicness1.1.8