Skip to content

Instantly share code, notes, and snippets.

@lrewega
Created August 4, 2011 13:56
Show Gist options
  • Select an option

  • Save lrewega/1125201 to your computer and use it in GitHub Desktop.

Select an option

Save lrewega/1125201 to your computer and use it in GitHub Desktop.
Sample 3D Tron bot
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int move( int * map, int w, int h, int d, int p [2][3] ) {
int x, y, z, i;
int moves[3][3] = { { 1, 0, 0 }, { 0, 1, 0 }, { 0, 0, 1 } };
/* Move to the first available empty space that isn't a player */
for( i = 0; i < 6; ++i ) {
int j = i > 2 ? -1 : 1;
x = p[0][0] + moves[i%3][0] * j;
y = p[0][1] + moves[i%3][1] * j;
z = p[0][2] + moves[i%3][2] * j;
if( x >= 0 && x < w &&
y >= 0 && y < h &&
z >= 0 && z < d &&
map[ z * w * h + y * w + x ] == 0 &&
p[1][0] != x && p[1][1] != y && p[1][2] != z ) {
return i+1;
}
}
/* Otherwise... */
return 1;
}
int main( int argc, char * argv [] ) {
if( argc != 2 ) {
fprintf( stderr, "usage: %s username\n", argv[0] );
fflush( stderr );
return 1;
}
fprintf( stdout, "%s\n", argv[1] );
fflush( stdout );
int w, h, d;
int * map;
int p [2] [3];
int num_items = fscanf( stdin, "%d %d %d\n", &w, &h, &d );
if( feof( stdin ) || num_items < 2 ) {
fprintf( stderr, "error: server: no room available\n" );
fflush( stderr );
return 0;
}
if( NULL == ( map = calloc( sizeof(int), w * h * d ) ) ) {
fprintf( stderr, "error: calloc: out of memory\n" );
fflush( stderr );
return 1;
}
while(1) {
int x = 0, y = 0, z = 0, c;
while( z < d && ( c = fgetc( stdin ) ) != EOF ) {
switch( c ) {
case '\n':
if( x != w ) {
fprintf( stderr, "error: server: bad map: unexpected end of line\n" );
fflush( stderr );
return 0;
}
++y;
if( y >= h ) {
++z;
y = 0;
}
x = 0;
break;
case '#':
case ' ':
case '1':
case '2':
if ( x >= w ) {
fprintf( stderr, "error: server: bad map: unexpected tile\n" );
fflush( stderr );
return 0;
}
map[ d * w * h + y * w + x ] = ( c == '#' ? 1 : 0 );
if( c == '1' || c == '2' ) {
p[c - 1][0] = x;
p[c - 1][1] = y;
p[c - 1][2] = z;
}
++x;
break;
default:
fprintf( stderr, "error: server: bad map: unexpected character %d\n", c );
fflush( stderr );
return 0;
}
}
fprintf( stdout, "%d\n", move( map, w, h, d, p ) );
fflush( stdout );
int state;
num_items = fscanf( stdin, "%d\n", &state );
if( feof( stdin ) || num_items < 1 ) {
fprintf( stderr, "error: server: failed mysteriously\n" );
fflush( stderr );
return 0;
}
if( state != 0 ) {
fprintf( stderr, state == 1 ? "supreme victory\n" : "a blowing defeat!\n" );
fflush( stderr );
return 0;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment