/* client.c * * "Computer Player" for a simple 2D grid game by Robert Marmorstein. * * Copyright (c) 2012 Robert Marmorstein (marmorsteinrm@longwood.edu) * Released under the terms of the GPL, version 2. See LICENSE file for details. * * For questions about the licensing of this software, contact me by mail: * Ruffner 329, Longwood University, 201 High Street, Farmville, VA 23909 */ #include #include #include #include #include #include #include #include #include "config.h" #include "shmlib.h" #include "commands.h" int main(int argc, char* argv[]) { char* grid; int i, j; int fd; int x, y; int cmd; if (argc < 4) { printf("Syntax: client \n"); exit(-1); } //Parse command line arguments fd = atoi(argv[1]); x = atoi(argv[2]); y = atoi(argv[3]); //Initialize the random number generator -- make sure we use a different seed for each client by adding the arguments together. srandom(fd + time(NULL) + x + y); //Attached to the shared memory grid = attach_map(0, WIDTH, HEIGHT); if (grid == (void *)-1) { perror("shmat"); exit(-1); } //Main loop while(1) { //Pick a random direction cmd = random() % 5; //But if we see the player next to us -- get him! if (grid[x-1 + y*WIDTH] == '+') { cmd = WEST; } if (grid[x + (y-1) * WIDTH] == '+') { cmd = NORTH; } if (grid[x + (y+1)*WIDTH] == '+') { cmd = SOUTH; } if (grid[x+1 + y*WIDTH] == '+') { cmd = EAST; } //Make sure we don't go out of bounds. if (cmd == NORTH && y > 2) { --y; } else if (cmd == SOUTH && y < HEIGHT-2) { ++y; } else if (cmd == WEST && x > 2) { ++x; } else if (cmd == EAST && x < WIDTH-2) { --x; } //Send the command to the server if ( write(fd, &cmd, sizeof(int)) < 0) { perror("write"); } //Then sleep for a bit so the player has a chance! sleep(1); } }