Exemplo n.º 1
0
void
end_of_game(void)
{
  string sTemp;

  if (b9 > 0)
    {
      printf("The Federation is in need of a new starship commander for\n");
      printf("a similar mission.\n\n");
      printf("If there is a volunteer, let him step forward and");
      printf(" enter 'aye':\n");

      reads(sTemp);
      printf("\n");

      if (! strncmp(sTemp, "aye", 3))
        new_game();
    }

  exit(0);
}
Exemplo n.º 2
0
int main(int argc, char **argv) {
    FILE *game_file;
    Game *game;
    int width, height, allow_lines_after_overflow, n, piece_index;
    char *piece_file_name;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s game_file_name\n", argv[0]);
        exit(1);
    }

    initialize_random_generator(time(NULL));

    game_file = open_data_file(argv[1], "r");

    FREAD(&width, sizeof(int), 1, game_file);
    FREAD(&height, sizeof(int), 1, game_file);
    FREAD(&allow_lines_after_overflow, sizeof(int), 1, game_file);
    FREAD(&n, sizeof(int), 1, game_file);

    MALLOCN(piece_file_name, char, n);
    FREAD(piece_file_name, sizeof(char), n, game_file);

    game = new_game(0, width, height, allow_lines_after_overflow, piece_file_name, NULL);

    do {
        FREAD(&game->score, sizeof(int), 1, game_file);
        FREAD(&piece_index, sizeof(int), 1, game_file);
        game_set_current_piece_index(game, piece_index);
        FREAD(game->board->rows, sizeof(int), height, game_file);

        game_print(stdout, game);
    }
    while (!feof(game_file));

    exit_random_generator();

    return 0;
}
Exemplo n.º 3
0
void handler() {
	process_keys();
	update_projectiles();
	update_animations();
	step_monsters();

	game.player.light->update_flicker();
	process_sight();
	draw_lights(game.fov_light, &game.map.block, game.map.lights);
	{
		lightsource *k = game.map.lights.head();
		for (; k; k = k->next()) {
			k->update_flicker();
			draw_light(game.fov_light, &game.map.block, k);
		}
	}

	u32 keys = keysHeld();
	u32 down = keysDown();
	touchPosition touch = touchReadXY();
	if (down & KEY_TOUCH && keys & KEY_R && touch.px != 0 && touch.py != 0) {
		luxel *l = torch.buf.luxat(torch.buf.scroll.x + touch.px/8, torch.buf.scroll.y + touch.py/8);
		iprintf("c:%d,%d,%d v:%d, low:%d\n", l->lr, l->lg, l->lb, l->lval, torch.get_low_luminance());
	}

	refresh(&game.map.block);

	if (game.player.hp <= 0) {
		playerdeath();
		game.player.clear();
		new_game();
	}

	if (game.cooldown <= 0) game.player.regenerate();

	statusbar();
}
Exemplo n.º 4
0
int main(int argc, char *argv[])
	{
	precompute();
#ifdef USE_HASH
	hash_init();
#endif
	// load_endgames();
//	load_bitbases();
	if (argc == 2 && !strcmp(argv[1], "nobook"))
		{
		printf("Skipping opening book\n");
		}
	else if (argc == 2 && !strcmp(argv[1], "makebook"))
		{
		load_opening_book(1);
		opening_book_grow(0);
		return 0;
		}
	else if (argc == 2 && !strcmp(argv[1], "showbook"))
		{
		load_opening_book(1);
		opening_book_grow(1);
		return 0;
		}
	else
		load_opening_book(2);
	new_game();

	int ply;

	int i, j, k;

	FILE * input;
	FILE * output;

	char command[80] = "";
	char buffer[4100] = "";


/*	if (argc == 2 && !strcmp(argv[1], "files"))
		{
		printf("Using files for I/O\n");
		input = fopen("input.txt", "r+");
		output = fopen("output.txt", "w");
		}
	else */
		{
		input = stdin;
		output = stdout;
		}

	if (argc == 2 && !strcmp(argv[1], "bitbases"))
		{
		bitbase_report();
		return 0;
		}

	if (argc == 7 && !strcmp(argv[1], "position"))
		{
		i = bitbase_test(
			atoi(argv[2])
			,atoi(argv[3])
			,atoi(argv[4])
			,atoi(argv[5])
			,atoi(argv[6])
			);
		printf("%s\n", i ? "is a win for black" : "not a win for black");

		int pieces[MAX_BDB_PIECES];
		int total_pieces = 0;

		for (i = 0; i < atoi(argv[2]); ++i) pieces[total_pieces++] = 0;
		for (i = 0; i < atoi(argv[3]); ++i) pieces[total_pieces++] = 1;
		for (i = 0; i < atoi(argv[4]); ++i) pieces[total_pieces++] = 2;
		for (i = 0; i < atoi(argv[5]); ++i) pieces[total_pieces++] = 3;

		position_decode(atoi(argv[6]), pieces, total_pieces);

		print_board(0);

		return 0;
		}

	if (argc == 2 && !strcmp(argv[1], "sanity"))
		{
		sanity_checks();
		memory_report();
		return 0;
		}

	if (argc == 2 && !strcmp(argv[1], "perft"))
		{
		iterative_performance_test();
#ifdef SORT_STATISTIC
	for (i = 0; i < 5; ++i)
		printf("Returns at sort level %d: %d\n"
			, i
			, sort_statistic[i]);
#endif
		return 0;
		}

	if (argc >= 4 && !strcmp(argv[1], "pdn"))
		{
		ply = 0;

		FILE * pdn;

		pdn = fopen(argv[3], "a+");
		if (!pdn)
			{
			printf("error: fopen \"%s\" for append/create\n", argv[3]);
			// printf("err: %d - %s\n", errno, strerror(errno));
			// getcwd(buffer, sizeof(buffer));
			// printf("pwd: %s\n", buffer);
			return 1;
			}
		while (!feof(pdn)) // fixme: this loader sux...
			{
			if (!fgets(buffer, 4096, pdn))
				break;

			//if (!buffer || feof(pdn))
			//	break;

			i = 0;
			while (j = load_move_from_pdn(buffer, command, &i))
				{
				generate_moves(0, 0);
				k = find_move(0, command);
				if (k < 0 || k >= move_counter[0])
					{
					fprintf(output, "error invalid move from pdn (%s)\n"
						, command);
					for (k = 0; k < move_counter[0]; ++k)
						{
						fprintf(output, "move %d ",k);
						print_move(&moves[0][k], 0);
						fprintf(output, "\n");
						}
					}
				else
					{
					++ply;
					//fprintf(output, "executing move at index %d: ", k);
					if (!strcmp(argv[2], "show") || !strcmp(argv[2], "step"))
						{
						if (ply % 2 == 1)
							printf("%3d. ", (ply+1) / 2);
						print_move(&moves[0][k], 0);
						if (ply % 2 == 0)
							{
							printf("\n");
							//print_board(0);
							}
						else
							printf(" ");
						if (!strcmp(argv[2], "step") && ply % 2 == 0)
							{
							print_board(0);
							getc(stdin);
							}
						}
					//fprintf(output, "\n");
					move_do(&moves[0][k], 0);
					move_list_push(&moves[0][k]);
					}
				}
			if (feof(pdn))
				break;
			}
		fclose(pdn);

		if (!strcmp(argv[2], "play"))
			{
			pdn = fopen(argv[3], "a");
			if (!pdn)
				{
				printf("error: fopen \"%s\" for append\n", argv[3]);
				return 1;
				}

			if (argc >= 5 && strcmp(argv[4], "hint") && strcmp(argv[4], "move"))
				{
				generate_moves(0, 0);
				i = find_move(0, argv[4]);
				if (i < 0 || i >= move_counter[0])
					{
					print_moves(0);
					i = -1;
					}
				else
					{
					move_do(&moves[0][i], 0);
					move_list_push(&moves[0][i]);
					fprintf(pdn, "%s ", argv[4]);
					if (moves[0][i].same_player_square != -1)
						i = -1;
					}
				}

			if (i != -1)
				{
				if (argc >= 6)
					strength = atoi(argv[5]);
				if (argc >= 7)
					thinking_time = atoi(argv[6]);

				if (strength == 1)
					thinking_time = 1;

				if (!strcmp(argv[4], "hint"))
					bestmove(0, 0);
				else
					while (bestmove(pdn, 1));
				}

			fclose(pdn);
			fprintf(output, "boardok ");
			for (i = 0; i < 64; ++i)
				fprintf(output, "%d", board[i]);
			fprintf(output, " %d", state.tactical_square);
			fprintf(output, " %d", state.side_to_move);
			fprintf(output, " %d", state.this_piece_must_take);
			fprintf(output, "\n");
			}
		else
			{
			print_board(0);
//debug_moves = 1;
			generate_moves(0, 0);
			if (!strcmp(argv[2], "show"))
				print_moves(0);
			}

		if (!strcmp(argv[2], "load"))
			{
			printf("PDN loaded\n");
			command[0] = 0;
			buffer[0] = 0;
			}
		else
			return 0;
		}

	for (;;)
		{
		fscanf(input, "%20s", command);

		if (parse(command, "quit"))
			break;
		else if (parse(command, "gnt"))
			fprintf(output, "id name GNTredux\nid author QuakePhil\ngntok\n");
		else if (parse(command, "new"))
			new_game();
		else if (parse(command, "flipside"))
			state.side_to_move ^= 1;
		else if (parse(command, "flipkings"))
			{
			for (i = 0; i < 64; ++i) if (initial_board[i] != 4)
				{
				if (initial_board[i] < 2)
					initial_board[i] += 2;
				else
					initial_board[i] -= 2;
				}
			new_game();
			}
		else if (parse(command, "flipboardonly"))
			{ // fixme: need to re-do materials here?
			int temp[64];
			int flip_piece[5] = {1,0,3,2,4};
			j = 64;
			for (i = 0; i < 64; ++i)
				temp[--j] = flip_piece[board[i]];
			for (i = 0; i < 64; ++i)
				board[i] = temp[i];
			state.side_to_move ^= 1;
			}
		else if (parse(command, "rand"))
			rand_board();
		else if (parse(command, "think"))
			{
			bestmove(0, 0);
			}
		else if (parse(command, "go"))
			{
			bestmove(0, 1);
			}
		else if (parse(command, "perft"))
			{
			iterative_performance_test();
			}
		else if (parse(command, "ping"))
			{
			fprintf(output, "pong %.6lf\n", timer());
			}
		else if (parse(command, "pboard"))
			print_board(0);
		else if (parse(command, "board"))
			{
			fprintf(output, "boardok ");
			for (i = 0; i < 64; ++i)
				fprintf(output, "%d", board[i]);
			fprintf(output, " %d", state.tactical_square);
			fprintf(output, " %d", state.side_to_move);
			fprintf(output, " %d", state.this_piece_must_take);
			fprintf(output, "\n");
			}
		else if (parse(command, "time"))
			{
			fscanf(input, "%d", &thinking_time);
			printf("Think time limit set to: %d seconds\n", thinking_time);
			}
		else if (parse(command, "pdn"))
			{
			fscanf(input, "%20s", buffer);
			generate_moves(0, 0);
			i = find_move(0, buffer);
			if (i < 0 || i >= move_counter[0])
				fprintf(output, "error invalid move\n");
			else
				{
				move_do(&moves[0][i], 0);
				move_list_push(&moves[0][i]);
				//fprintf(output, "executing move at index %d: ", i);
				//print_move(&moves[0][i], 0);
				//fprintf(output, "\n");
				fprintf(output, "done\n");
				}
			}
		else if (parse(command, "do") || parse(command, "toggle"))
			{
			fscanf(input, "%d", &i);
			fprintf(output, "executing move %d\n", i);
			generate_moves(0, 0);
			if (i < 0)
				fprintf(output, "error move can't be negative\n");
			else if (i >= move_counter[0])
				fprintf(output, "error no such move\n");
			else
				{
				move_do(&moves[0][i], 0);
				move_list_push(&moves[0][i]);

				if (parse(command, "toggle"))
					{
					print_board(0);
					fprintf(output, "undoing move %d\n", i);
					move_undo(&moves[0][i], 0);
					print_board(0);
					}
				}
			fprintf(output, "done\n");
			}
		else if (parse(command, "list"))
			{
			print_move_list();
			}
		else if (parse(command, "pbook"))
			{
			print_book();
			}
		else if (parse(command, "moves"))
			{
			generate_moves(0, 0);
			for (i = 0; i < move_counter[0]; ++i)
				{
				fprintf(output, "move %d ",i);
				print_move(&moves[0][i], 1);
				fprintf(output, "\n");
				}
			fprintf(output, "movesok\n");
			}
		else // if (!strcmp(command, "help"))
			{
			// fprintf(output, "?\n");
			}

		fflush(output);
		}

#ifdef HASH_STATISTIC
	printf("Hash saves:      %d\n", hash_saves);
	printf("Hash collisions: %d\n", hash_collisions);
	printf("Hash probes:     %d\n", hash_probes);
	printf("Hash hits:       %d\n", hash_hits);
#endif

#ifdef SORT_STATISTIC
	for (i = 0; i < 5; ++i)
		printf("Returns at sort level %d: %d\n"
			, i
			, sort_statistic[i]);
#endif

	fclose(output);
	fclose(input);

	return 0;
	}
Exemplo n.º 5
0
Arquivo: script.c Projeto: EXio4/Lex4
void cmd_loadmap(char *fname) {
	new_game(0);
	new_level(fname, -2, 0);
}
Exemplo n.º 6
0
static void
game_new_callback (GtkWidget *widget, void *data)
{
	new_game ();
}
Exemplo n.º 7
0
static void
new_game_cb (GtkAction * action, gpointer data)
{
  new_game ();
}
Exemplo n.º 8
0
void AppWindow::createActions() {
    // Creates a new action for quiting and pushes it onto the menu actions vector
    quitAct = new QAction(tr("&Quit"), this);
    m_menu_actions.push_back(quitAct);

    // We set the accelerator keys
    // Alternatively, you could use: setShortcuts(Qt::CTRL + Qt::Key_P);
    quitAct->setShortcuts(QKeySequence::Quit);

    // Set the tip
    quitAct->setStatusTip(tr("Exits the file"));

    // Connect the action with the signal and slot designated
    connect(quitAct, SIGNAL(triggered()), this, SLOT(close()));

    newGameAct = new QAction(tr("&New Game (N)"), this);
    m_menu_actions.push_back(newGameAct);
    connect(newGameAct, SIGNAL(triggered()), this, SLOT(new_game()));

    resetAct = new QAction(tr("&Reset (R)"), this);
    m_menu_actions.push_back(resetAct);
    connect(resetAct, SIGNAL(triggered()), this, SLOT(reset()));

    wireAct = new QAction(tr("&Wire-frame (W)"), this);
    m_draw_actions.push_back(wireAct);
    wireAct->setCheckable(true);
    connect(wireAct, SIGNAL(triggered()), this, SLOT(wire_frame()));


    faceAct = new QAction(tr("&Face (F)"), this);
    m_draw_actions.push_back(faceAct);
    faceAct->setCheckable(true);
    connect(faceAct, SIGNAL(triggered()), this, SLOT(face()));


    multiAct = new QAction(tr("&Multicoloured (M)"), this);
    m_draw_actions.push_back(multiAct);
    multiAct->setCheckable(true);
    connect(multiAct, SIGNAL(triggered()), this, SLOT(multi_coloured()));

    QActionGroup* drawGroup = new QActionGroup(this);

    drawGroup->setExclusive(true);
    drawGroup->addAction(wireAct);
    drawGroup->addAction(faceAct);
    drawGroup->addAction(multiAct);

    faceAct->setChecked(true);


    slowSpeedAct = new QAction(tr("&Slow (1)"), this);
    m_speed_actions.push_back(slowSpeedAct);
    slowSpeedAct->setCheckable(true);
    connect(slowSpeedAct, SIGNAL(triggered()), this, SLOT(slowSpeed()));

    normalSpeedAct = new QAction(tr("&Medium (2)"), this);
    m_speed_actions.push_back(normalSpeedAct);
    normalSpeedAct->setCheckable(true);
    connect(normalSpeedAct, SIGNAL(triggered()), this, SLOT(normalSpeed()));

    fastSpeedAct = new QAction(tr("&Fast (3)"), this);
    m_speed_actions.push_back(fastSpeedAct);
    fastSpeedAct->setCheckable(true);
    connect(fastSpeedAct, SIGNAL(triggered()), this, SLOT(fastSpeed()));

    QActionGroup* speedGroup = new QActionGroup(this);

    speedGroup->setExclusive(true);
    speedGroup->addAction(slowSpeedAct);
    speedGroup->addAction(normalSpeedAct);
    speedGroup->addAction(fastSpeedAct);

    normalSpeedAct->setChecked(true);




}
Exemplo n.º 9
0
void init_game(nstate *state)
{
	GR_WM_PROPERTIES props;

	if(GrOpen() < 0) {
		fprintf(stderr, "Couldn't connect to Nano-X server\n");
		exit(1);
	}

	state->main_window = GrNewWindow(GR_ROOT_WINDOW_ID,
					MAIN_WINDOW_X_POSITION,
					MAIN_WINDOW_Y_POSITION,
					MAIN_WINDOW_WIDTH,
					MAIN_WINDOW_HEIGHT, 0,
					MAIN_WINDOW_BACKGROUND_COLOUR, 0);
	/* set title */
	props.flags = GR_WM_FLAGS_TITLE | GR_WM_FLAGS_PROPS;
	props.props = GR_WM_PROPS_BORDER | GR_WM_PROPS_CAPTION;
	props.title = "Nano-Tetris";
	GrSetWMProperties(state->main_window, &props);
	GrSelectEvents(state->main_window, GR_EVENT_MASK_EXPOSURE |
					GR_EVENT_MASK_CLOSE_REQ |
					GR_EVENT_MASK_KEY_DOWN |
					GR_EVENT_MASK_TIMEOUT);

	state->score_window = GrNewWindow(state->main_window,
					SCORE_WINDOW_X_POSITION,
					SCORE_WINDOW_Y_POSITION,
					SCORE_WINDOW_WIDTH,
					SCORE_WINDOW_HEIGHT, 0,
					SCORE_WINDOW_BACKGROUND_COLOUR, 0);
	GrSelectEvents(state->score_window, GR_EVENT_MASK_EXPOSURE);
	GrMapWindow(state->score_window);
	state->scoregcf = GrNewGC();
	GrSetGCForeground(state->scoregcf, SCORE_WINDOW_FOREGROUND_COLOUR);
	GrSetGCBackground(state->scoregcf, SCORE_WINDOW_BACKGROUND_COLOUR);
	state->scoregcb = GrNewGC();
	GrSetGCForeground(state->scoregcb, SCORE_WINDOW_BACKGROUND_COLOUR);

	state->next_shape_window = GrNewWindow(state->main_window,
					NEXT_SHAPE_WINDOW_X_POSITION,
					NEXT_SHAPE_WINDOW_Y_POSITION,
					NEXT_SHAPE_WINDOW_WIDTH,
					NEXT_SHAPE_WINDOW_HEIGHT, 0,
					NEXT_SHAPE_WINDOW_BACKGROUND_COLOUR, 0);
	GrSelectEvents(state->next_shape_window, GR_EVENT_MASK_EXPOSURE);
	GrMapWindow(state->next_shape_window);
	state->nextshapegcf = GrNewGC();
	state->nextshapegcb = GrNewGC();
	GrSetGCForeground(state->nextshapegcb,
				NEXT_SHAPE_WINDOW_BACKGROUND_COLOUR);

	state->new_game_button = GrNewWindow(state->main_window,
					NEW_GAME_BUTTON_X_POSITION,
					NEW_GAME_BUTTON_Y_POSITION,
					NEW_GAME_BUTTON_WIDTH,
					NEW_GAME_BUTTON_HEIGHT, 0,
					BUTTON_BACKGROUND_COLOUR, 0);
	GrSelectEvents(state->new_game_button, GR_EVENT_MASK_EXPOSURE |
					GR_EVENT_MASK_BUTTON_DOWN);
	GrMapWindow(state->new_game_button);
	state->buttongcf = GrNewGC();
	GrSetGCForeground(state->buttongcf, BUTTON_FOREGROUND_COLOUR);
	GrSetGCBackground(state->buttongcf, BUTTON_BACKGROUND_COLOUR);
	state->buttongcb = GrNewGC();
	GrSetGCForeground(state->buttongcb, BUTTON_BACKGROUND_COLOUR);

	state->pause_continue_button = GrNewWindow(state->main_window,
					PAUSE_CONTINUE_BUTTON_X_POSITION,
					PAUSE_CONTINUE_BUTTON_Y_POSITION,
					PAUSE_CONTINUE_BUTTON_WIDTH,
					PAUSE_CONTINUE_BUTTON_HEIGHT, 0,
					BUTTON_BACKGROUND_COLOUR, 0);
	GrSelectEvents(state->pause_continue_button, GR_EVENT_MASK_EXPOSURE |
					GR_EVENT_MASK_BUTTON_DOWN);

	state->anticlockwise_button = GrNewWindow(state->main_window,
					ANTICLOCKWISE_BUTTON_X_POSITION,
					ANTICLOCKWISE_BUTTON_Y_POSITION,
					ANTICLOCKWISE_BUTTON_WIDTH,
					ANTICLOCKWISE_BUTTON_HEIGHT, 0,
					BUTTON_BACKGROUND_COLOUR,
					0);
	GrSelectEvents(state->anticlockwise_button, GR_EVENT_MASK_EXPOSURE |
					GR_EVENT_MASK_BUTTON_DOWN);

	state->clockwise_button = GrNewWindow(state->main_window,
					CLOCKWISE_BUTTON_X_POSITION,
					CLOCKWISE_BUTTON_Y_POSITION,
					CLOCKWISE_BUTTON_WIDTH,
					CLOCKWISE_BUTTON_HEIGHT, 0,
					BUTTON_BACKGROUND_COLOUR,
					0);
	GrSelectEvents(state->clockwise_button, GR_EVENT_MASK_EXPOSURE |
					GR_EVENT_MASK_BUTTON_DOWN);

	state->left_button = GrNewWindow(state->main_window,
					LEFT_BUTTON_X_POSITION,
					LEFT_BUTTON_Y_POSITION,
					LEFT_BUTTON_WIDTH,
					LEFT_BUTTON_HEIGHT, 0,
					BUTTON_BACKGROUND_COLOUR,
					0);
	GrSelectEvents(state->left_button, GR_EVENT_MASK_EXPOSURE |
					GR_EVENT_MASK_BUTTON_DOWN);

	state->right_button = GrNewWindow(state->main_window,
					RIGHT_BUTTON_X_POSITION,
					RIGHT_BUTTON_Y_POSITION,
					RIGHT_BUTTON_WIDTH,
					RIGHT_BUTTON_HEIGHT, 0,
					BUTTON_BACKGROUND_COLOUR,
					0);
	GrSelectEvents(state->right_button, GR_EVENT_MASK_EXPOSURE |
					GR_EVENT_MASK_BUTTON_DOWN);

	state->drop_button = GrNewWindow(state->main_window,
					DROP_BUTTON_X_POSITION,
					DROP_BUTTON_Y_POSITION,
					DROP_BUTTON_WIDTH,
					DROP_BUTTON_HEIGHT, 0,
					BUTTON_BACKGROUND_COLOUR,
					0);
	GrSelectEvents(state->drop_button, GR_EVENT_MASK_EXPOSURE |
					GR_EVENT_MASK_BUTTON_DOWN);

	state->well_window = GrNewWindow(state->main_window,
					WELL_WINDOW_X_POSITION,
					WELL_WINDOW_Y_POSITION,
					WELL_WINDOW_WIDTH,
					WELL_WINDOW_HEIGHT, 0,
					WELL_WINDOW_BACKGROUND_COLOUR, 0);
	GrSelectEvents(state->well_window, GR_EVENT_MASK_EXPOSURE);
	GrMapWindow(state->well_window);
	state->wellgc = GrNewGC();

	GrMapWindow(state->main_window);

	state->state = STATE_STOPPED;
	state->score = 0;
	read_hiscore(state);
	state->level = 0;
	state->running_buttons_mapped = 0;

	srandom(time(0));

	choose_new_shape(state);
	new_game(state);
}
Exemplo n.º 10
0
int main()
{
    remove(sr_go_1);
    remove(sr_go_2);
    remove(kl_stop_1);
    remove(kl_stop_2);
    int ready1,ready2;
    //new_game
     new_game();
     countpoints();
    //in file
    file_in();
    fkl1= fopen(kl_1,"w"); fclose(fkl1);
    fkl2= fopen(kl_2,"w"); fclose(fkl1);
    if((fstop1 = fopen(kl_stop_1,"w"))==0){ printf("\nstopfile(1) error"); Sleep(3000);exit(1);}
    else fclose(fstop1);
    if((fstop2 = fopen(kl_stop_2,"w"))==0){ printf("\nstopfile(2) error"); Sleep(3000);exit(1);}
    else fclose(fstop2);
    while(1)
    { printf("1");
            remove(sr_go_1); remove(sr_go_2);
            while((fstop1 = fopen(kl_stop_1,"w"))==0) printf("\nTry open kl_stop_1"); 
            while((fstop2 = fopen(kl_stop_2,"w"))== 0) printf("\nTry open kl_stop_2") ; 
            fclose(fstop1);
            fclose(fstop2);
            ready1= 0; ready2= 0;
            while(ready1*ready2 == 0)
            { 
               //printf("2");
               Sleep(500);
                 if(ready1 == 0) 
                 { 
                           srgo1 = fopen(sr_go_1,"r"); 
                           if(srgo1!= 0)
                             {
                                   check_file(1);
                                   ready1 = 1; 
                                   printf("\nready 1");
                                   fclose(srgo1);
                                   if(remove(sr_go_1) !=0) printf("\ncant del sr_go_1");
                             }
                           
                 }
                 if(ready2 == 0)
                 {
                           srgo2 = fopen(sr_go_2,"r"); 
                           if(srgo2!=0)
                           {
                                      check_file(2);
                                      ready2 = 1;
                                      printf("\nready 2");
                                      fclose(srgo2);  
                                      if(remove(sr_go_2) !=0) printf("\ncant del sr_go_2");
                           }
                           
                 }
            }
            //countwar
            WarCount();
            countmaps();
            if(countpoints()== 1); // конец игры
            file_in();
    }
}
Exemplo n.º 11
0
void game() {
	mc = get_click();
	if (mc != MCNone) {
		switch (mc) {
			case MCBoard: {
				if (drawn_proposed_by_me || drawn_proposed_by_him) break;
				switch (ggs) {
					case GGStartStepWhite: start_step(White, MyColor); break;
					case GGStartStepBlack: start_step(Black, MyColor); break;
					case GGStepWhite: step(White); break;
					case GGStepBlack: step(Black); break;
					default: {}
				}
				break;
			}
			case MCNG: {
				if (ggs == GGSTART) {
					if (NG_is_sent == 0) {
						debug_print("NG", 2, Dmy);
						send_str("NG", 2);
						NG_is_sent = 1;
					}
					new_game();
				}
				break;
			}
			case MCD2: {
				if (ggs != GGSTART && ggs != GGNEW && ggs != GGCONNECT) {
					if (drawn_proposed_by_him) {
						debug_print("D2", 2, Dmy);
						send_str("D2", 2);
						debug_print("Я подтверждаю ничью", 19, 4);
						ggs = GGNEW;
					} else if (!drawn_proposed_by_me && ((ggs == GGStartStepWhite || ggs == GGStepWhite) && MyColor == White) ||
							   ((ggs == GGStartStepBlack || ggs == GGStepBlack) && MyColor == Black)) {
						debug_print("D2", 2, Dmy);
						send_str("D2", 2);
						debug_print("Я предлагаю ничью", 17, 4);
						drawn_proposed_by_me = 1;
					}
				}
				break;
			}
			case MCD3: {
				if (drawn_proposed_by_him) {
					debug_print("D3", 2, Dmy);
					send_str("D3", 2);
					debug_print("Я не согласен на ничью", 22, 4);
					drawn_proposed_by_him = 0;
				}
				break;
			}
			case MCFF: {
				if (ggs != GGSTART && ggs != GGNEW && ggs != GGCONNECT && !drawn_proposed_by_him && !drawn_proposed_by_me) {
					debug_print("FF", 2, Dmy);
					send_str("FF", 2);
					debug_print("Я сдаюсь", 8, 4);
					ggs = GGNEW;
				}
				break;
			}
			default: {}
		}
	}

	get_command();
	if (!isNewCommand) return;
	if (getst == GETERR) {
		debug_print("GETERR", 6, 4);
		error();
	}
	switch (comm) {
		case COMX: {
			if (drawn_proposed_by_me || drawn_proposed_by_him) {error(); break;}
			switch (ggs) {
				case GGStartStepWhite: start_step(White, HisColor); break;
				case GGStartStepBlack: start_step(Black, HisColor); break;
				case GGStepWhite: step(White); break;
				case GGStepBlack: step(Black); break;
				default: {}
			}
			break;
		}
		case COMNG: {
			if (ggs == GGSTART) {
				NG_is_received = 1;
				new_game();	
			} else {
				if (NG_is_sent == 1 && NG_is_received == 1) {
					NG_during_game = 1;
					ggs = GGNEW;
				} else error();
			}
			break;
		}
		case COMD0: {
			if (ggs == GGSTART || ggs == GGNEW || ggs == GGCONNECT) ggs = GGCONNECT;
			else ggs = GGNEW;
			break;
		}
		case COMD2: {
			if (drawn_proposed_by_me) {
				debug_print("Противник согласился на ничью", 29, 4);
				ggs = GGNEW;
			} else if (ggs != GGSTART && ggs != GGNEW && ggs != GGCONNECT && !drawn_proposed_by_him && !drawn_proposed_by_me) {
				debug_print("Противник предложил ничью", 25, 4);
				drawn_proposed_by_him = 1;
			} else error();
			break;
		}
		case COMD3: {
			if (drawn_proposed_by_me) {
				debug_print("Противник отклонил ничью", 24, 4);
				drawn_proposed_by_me = 0;
			} else error();
			break;
		}
		case COMFF: {
			if (ggs == GGSTART || ggs == GGNEW || ggs == GGCONNECT) {error(); break;}
			debug_print("Противник сдался", 16, 4);
			ggs = GGNEW;
			break;
		}
		case COMEX: {
			debug_print("Противник ушел", 14, 4);
			ggs = GGCONNECT;
			break;
		}
		case COMC0: { 
			ggs = GGCONNECT;
			break;
		}
		case COMCx: { 
			ggs = GGCONNECT;
			break;
		}
		default: {}
	}
}
Exemplo n.º 12
0
Arquivo: main.c Projeto: needs/anko
int main(int argc, char **argv)
{
	world_t world;
	game_t game;
	double last_time = 0;
	double current_time = 0;
	float deltatime = 0;
	float sleep_time;

	if (config_from_file("anko.cfg", 1) == 2)
		return EXIT_FAILURE;
	if (config_from_args(argc, argv))
		return EXIT_FAILURE;

	if (!init())
		goto err_init;
	if (!new_game(&game, config.board_width, config.board_height, &config.gen_params, config.sim_speed * 1000))
		goto err_game;
	if (!create_world(&world, &game))
		goto err_world;
	if ((current_ui = init_ui_game(&world)) == NULL)
		goto err_ui;

	world_set_active_player(&world, add_player(&game, TEAM_BURNER));
	events_link_frame(&current_ui); // link window event to game ui frame
	glClearColor(0, 0, 0, 1);

	last_time = 0;
	while(!glfwWindowShouldClose(window)) {
	    current_time = glfwGetTime();
		deltatime = current_time - last_time;
		update_speed(deltatime);
		glfwPollEvents();

		// Update
		update_ui(current_ui, deltatime);
		update_world(&world);
		if (update_game(&game, deltatime * 1000))
			refresh_world(&world);
		if(should_quit)
			glfwSetWindowShouldClose(window, GL_TRUE);

		// Rendering
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		draw_ui(current_ui);
		font_swap_buffers();
		glfwSwapBuffers(window);

		// Update speed and sleep if necessary
		last_time = current_time;
		sleep_time = (current_time + MAX_MSPF - glfwGetTime()) * 1000 * 1000;
		if(sleep_time > 0)
			usleep(sleep_time);
	}

	destroy_ui(current_ui);
	game_over(&game);
	end_of_the_world(&world); // Tin tin tin
	terminate();

	return EXIT_SUCCESS;
err_ui:
	end_of_the_world(&world);
err_world:
	game_over(&game);
err_game:
	terminate();
err_init:
	return EXIT_FAILURE;
}
Exemplo n.º 13
0
void useCE(std::string startPolicyFile,
           std::string piecesFile,
           unsigned int nbGames,
           unsigned int nbLearnGames,
           unsigned int boardWidth,
           unsigned int boardHeight,
           int randomSeed,
           ExperimentOptionType<double> initialSigma,
           unsigned int maxIterations,
           unsigned int maxAgents,
           StoppingCriteria stoppingCriteria,
           std::ostream & out,
           std::string outname,
           shark::CrossEntropy::SamplingNoise noiseType,
           double noise,
           ExperimentOptionType<unsigned int> lambda,
           ExperimentOptionType<unsigned int> offspring
)
{
    out << "Running Cross Entropy with following configurations" << std::endl;
    out << "Start policy       : " << startPolicyFile << std::endl;
    out << "Pieces             : " << piecesFile << std::endl;
    out << "Game evaluations   : " << nbGames << std::endl;
    out << "Game learning games: " << nbLearnGames << std::endl;
    out << "Game board with    : " << boardWidth << std::endl;
    out << "Game board height  : " << boardHeight << std::endl;
    out << "Random seed        : " << randomSeed << std::endl;
    if (initialSigma.used())
        out << "initialSigma       : " << initialSigma() << std::endl;
    out << "MaxIterations      : " << maxIterations << std::endl;

    initialize_random_generator( randomSeed );
    shark::Rng::seed( randomSeed );
    shark::CrossEntropy ce;

    Game *game = new_game(0, 10, 20, 0, piecesFile.c_str(), NULL);
    GamesStatistics *stats = games_statistics_new(NULL, nbGames, NULL);

    MDPTetris objFun(10,20, nbGames, game, stats, startPolicyFile);
    if ( outname.size() > 0 )
    {
        objFun.setGamedataFilename(outname);
    }


    ce.init(objFun);

    ce.lambda() = 100;
    ce.mu() = 10;
    ce.setSamplingNoisetype(noiseType);
    ce.SamplingNoiseTerm() = noise;

    out << "NoiseType          : " << noiseType << std::endl;
    out << "Noise              : " << noise << std::endl;

    if (initialSigma.used())
    {
        ce.setSigma(initialSigma());
    }

    if(lambda.used())
    {
        ce.lambda() = lambda();
    }
    if(offspring.used())
    {
        ce.mu() = offspring();
    }

    // Still need to set the initial sigma vector


    int t = 0;
    int generation = 0;
    double bestScore = 0.0;

    bool running = true;


    /* Report header for CSV output */
    if ( outname.size() > 0 )
    {
        /* Write the header */
        std::ofstream fs;
        fs.open (outname.c_str());

        fs << "generation,agents,minScore,maxScore,meanScore,standardDeviation,";
        for (int i = 0; i < objFun.numberOfVariables()-1; i++)
        {
            fs << "w" << i << ",";
        }
        fs << "w" << objFun.numberOfVariables()-1 << std::endl;

        fs.close();
    }

    while (running)
    {
        _DUMP(generation);
        ce.step(objFun);
        t += ce.lambda() * nbGames;

        if ( outname.size() > 0 )
        {

            /* Set the number of games for the learning curve */
            objFun.setNbGames(nbLearnGames);
            MDPTetris::MDPTetrisDetailedResult report = objFun.evalDetailed(ce.mean());
            objFun.setNbGames(nbGames);


            std::ofstream fs;
            fs.open (outname.c_str(), std::ios::app);
            fs << generation << ","
            << t << ","
            << report.minScore() << ","
            << report.maxScore() << ","
            << report.mean() << ","
            << report.standardDeviation() << ","
            << report.printWeights(",") << std::endl;
        }

        if (TETRIS_MAX_SCORE - ce.solution().value > bestScore)
        {
            bestScore = TETRIS_MAX_SCORE - ce.solution().value;
            shark::RealVector solution = ce.solution().point;
            _DUMP(bestScore);
            _DUMP(t);
            _DUMP(solution);
        }
        generation++;
        if (stoppingCriteria == STOP_BY_ITERATION && generation > maxIterations)
        {
            running = false;
        }
        else if (stoppingCriteria == STOP_BY_AGENTS_EVALUATED && t > maxAgents)
        {
            running = false;
        }
    }


}
Exemplo n.º 14
0
void NewGameDialog::init_()
{
	scenario_list_ = (CEGUI::Listbox*)window_->getChild("SCENARIO_INPUT");

	window_->getChild("16x16")->subscribeEvent(
		CEGUI::PushButton::EventClicked,
		[this](const CEGUI::EventArgs&) -> bool {
			window_->getChild("WIDTH_INPUT")->setText("16");
			window_->getChild("HEIGHT_INPUT")->setText("16");
			return true;
		}
	);

	window_->getChild("32x32")->subscribeEvent(
		CEGUI::PushButton::EventClicked,
		[this](const CEGUI::EventArgs&) -> bool {
			window_->getChild("WIDTH_INPUT")->setText("32");
			window_->getChild("HEIGHT_INPUT")->setText("32");
			return true;
		}
	);

	window_->getChild("64x64")->subscribeEvent(
		CEGUI::PushButton::EventClicked,
		[this](const CEGUI::EventArgs&) -> bool {
			window_->getChild("WIDTH_INPUT")->setText("64");
			window_->getChild("HEIGHT_INPUT")->setText("64");
			return true;
		}
	);

	auto game = GUI::instance().game_;
	auto log = &GUI::instance().log_;
	auto window = GUI::instance().window_;
	window_->getChild("CREATE")->subscribeEvent(
		CEGUI::PushButton::EventClicked,
		[this, game, log, window](const CEGUI::EventArgs&) -> bool {
			if(scenario_list_->getSelectedCount() != 1)
			{
				log->set_visible(true);
				log->print("\\[ERROR\\] You need to choose exactly one scenario.");
				return false;
			}

			try
			{
				// Converts text from edit boxes to uints, sadly no implicit conversion
				// from CEGUI::String to std::string exists :(.
				std::size_t w{
					(std::size_t)std::stoul(window_->getChild("WIDTH_INPUT")->getText().c_str())
				};
				std::size_t h{
					(std::size_t)std::stoul(window_->getChild("HEIGHT_INPUT")->getText().c_str())
				};

				if(w >= 10 && w <= 64 && h >= 10 && h <= 64)
				{
					game->wave_system_->set_wave_table(get_selected_scenario_table());
					game->new_game(w, h);
				}
				else
					throw std::out_of_range{"(" + std::to_string(w) + ", " + std::to_string(h) + ") != (10, 64)"};
			}
			catch(std::invalid_argument&)
			{
				log->set_visible(true);
				log->print("\\[ERROR\\] Invalid new game dimensions.");
				return false;
			}
			catch(std::out_of_range&)
			{
				log->set_visible(true);
				log->print("\\[ERROR\\] Game dimensions out of range.");
				return false;
			}

			window_->getChild("WIDTH_INPUT")->setText("");
			window_->getChild("HEIGHT_INPUT")->setText("");
			window_->setVisible(false);
		    window->getChild("MAIN_MENU")->setVisible(false);
			window->getChild("TOOLS")->setVisible(true);
			window->getChild("ENTITY_VIEW")->setVisible(true);
			window->getChild("GAME_LOG")->setVisible(true);
			window->getChild("NEXT_WAVE")->setVisible(true);
			game->set_state(GAME_STATE::RUNNING);
			return true;
		}
	);
}
Exemplo n.º 15
0
int menu_clic(SDL_Surface *screen, Menu *menu, int *page, Curseur c, Plateau *p, bool *tourJ1, Item *items[], TTF_Font *font, SDL_Color *color, Item** message, bool* game, int* mode) {
    for (int i = 0; i < menu[*page]->size; i++) {
        if (mnit_is_over(menu[*page]->items[i], &c)) {
            switch (*page) {
                case 0:
                    switch (i) {
                        case 0:
                            menu[0]->on_screen = false;
                            menu[1]->on_screen = true;
                            *page = 1;
                            return 1;
                        case N_MAINMENU - 1:
                            return 0;
                        default:
                            break;
                    }
                    break;
                case 1:
                    switch (i) {
                        case 0:
                            menu[1]->on_screen = false;
                            menu[2]->on_screen = true;
                            *page = 2;
                            return 1;
                        case 1:
                            new_game(p);
                            int res = save_charger(p, tourJ1, "./saves/save.txt", mode);
                            if (res != 0) {
                                menu[0]->on_screen = true;
                                menu[1]->on_screen = false;
                                res_placer_pion(*p, res-1, tourJ1, message, game, NULL, *mode);
                                *page = 0;
                                if (res >= 2) {
                                    afficher_message(message, res+1);
                                    *game = false;
                                } else
                                    *game = true;
                            }
                            return 1;
                        default:
                            break;
                    }
                    break;
                case 2:
                    switch (i) {
                        case 0:
                            *game = true;
                            *tourJ1 = true;
                            menu[0]->on_screen = true;
                            menu[2]->on_screen = false;
                            *page = 0;
                            for (i = 0; i < N_ITEM; i++)
                                items[i]->on_screen = true;
                            new_game(p);
                            return 2;
                        case 1:
                            menu[2]->on_screen = false;
                            menu[3]->on_screen = true;
                            *page = 3;
                            return 1;
                        default:
                            break;
                    }
                    break;
                case 3:
                    *game = true;
                    *tourJ1 = true;
                    switch (i) {
                        case 0:
                            menu[0]->on_screen = true;
                            menu[3]->on_screen = false;
                            *page = 0;
                            *mode = 1;
                            for (i = 0; i < N_ITEM; i++)
                                items[i]->on_screen = true;
                            new_game(p);
                            return 2;
                        case 1:
                            menu[0]->on_screen = true;
                            menu[3]->on_screen = false;
                            *page = 0;
                            *mode = 2;
                            for (i = 0; i < N_ITEM; i++)
                                items[i]->on_screen = true;
                            new_game(p);
                            return 2;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
            break;
        }
    }
    return true;
}
Exemplo n.º 16
0
// Main loop the game
int game_loop() {
    SDL_Rect dest;
    int x, y, aux;
    SDL_Event event;
    unsigned long t1, t2;
    int no_unselect = 0;

    // Main loop
    t1 = SDL_GetTicks();
    while (1) {

        // Restart the game
        if (game_state.state == NEW_GAME){
            if (gm == GM_MULTIPLAYER) {
                aux = BOARD_RESTARTED;
                write_socket(&aux, sizeof(int));
                new_game(false, GM_MULTIPLAYER, false);
            } else {
                new_game(false, GM_SINGLE, false);
            }
        } else if (game_state.state == GAME_LOSE || game_state.state == GAME_WIN || game_state.state == GAME_EXIT) {
	    if (gm == GM_MULTIPLAYER) {
		if (game_state.state == GAME_EXIT) {
			aux = END_GAME; 
        	        write_socket(&aux, sizeof(int));
		}
		finish_attack(game_state.state == GAME_WIN);
	    }
            dest.x = 386;
            dest.y = 151;
            dest.w = dest.h = 0;
            if (game_state.state != GAME_EXIT) {
                SDL_BlitSurface(game_state.state == GAME_WIN ? win : lose, NULL, screen, &dest);
                SDL_Update(386, 151, 365, 178);
                SDL_Delay(4000);
            }
            return (game_state.state == GAME_LOSE);
        }
        
        if (SDL_PollEvent(&event)) {

            
            switch (event.type) { 
                // Key pressed
                case SDL_KEYDOWN:
                    if (event.key.state == SDL_PRESSED) {

                        // Quit
                        if (event.key.keysym.sym == SDLK_ESCAPE
                                || event.key.keysym.sym == SDLK_BACKSPACE
                                || event.key.keysym.sym == SDLK_F4
                                || event.key.keysym.sym == SDLK_F5 
                                || event.key.keysym.sym == SDLK_F6) {
		            game_state.state = GAME_EXIT;
                        }
                    }
                
                // Quit the game
                case SDL_QUIT:
		    game_state.state = GAME_EXIT;
                    break;

		// Window focus change
#if 0
		case SDL_ACTIVEEVENT:
		    if (event.active.gain == 0 && gm != GM_MULTIPLAYER) {
		        game_state.state = GAME_EXIT;
		    }
		    break;
#endif
                    
                // Button pressed
                case SDL_MOUSEBUTTONUP:
                case SDL_FINGERUP:
                    no_unselect = 1;
                    if (game_state.state == UNSELECTED_FIRST) {
                        game_state.state = IDLE;
                        break;
                    }
                case SDL_MOUSEBUTTONDOWN:
                case SDL_FINGERDOWN:

                    if (event.type == SDL_FINGERDOWN) {
                        event.button.x = event.tfinger.x;
                        event.button.y = event.tfinger.y;
                    }
    
                    // Diamond area
                    if (event.button.x >= BOARD_OFFSETX 
                       && event.button.x < BOARD_WIDTH * DIAMOND_WIDTH + BOARD_OFFSETX 
                       && event.button.y >= BOARD_OFFSETY 
                       && event.button.y < BOARD_HEIGHT * DIAMOND_HEIGHT + BOARD_OFFSETY) {
                        
                        x = (event.button.x - BOARD_OFFSETX) / DIAMOND_WIDTH;
                        y = (event.button.y - BOARD_OFFSETY) / DIAMOND_HEIGHT;
                        
                        if (game_state.state == IDLE) {
                            game_state.state = SELECTED_FIRST;
                            game_state.x_first = x;
                            game_state.y_first = y;
                            draw = true;
                        }
                        else if (game_state.state == SELECTED_FIRST) {
                            if(game_state.x_first == x && game_state.y_first == y && !no_unselect) {
                                game_state.state = UNSELECTED_FIRST;
                                draw = true;
                            } else if ((abs(game_state.x_first - x) == 1
                                     && (game_state.y_first == y))
                                     || ((game_state.x_first == x)
                                     && (abs(game_state.y_first - y) == 1))){
                                game_state.state = SELECTED_SECOND;
                                game_state.x_second = x;
                                game_state.y_second = y;
                                draw = true;
                            } else  {
                                game_state.x_first = x;
                                game_state.y_first = y;
                                draw = true;
                            }
                        }
                    } else if (event.button.x >= BACK2_OFFSETX
                            && event.button.y >= BACK2_OFFSETY
                            && event.button.x < BACK2_OFFSETX2
                            && event.button.y < BACK2_OFFSETY2) {
			game_state.state = GAME_EXIT;
                        break;
                    }
                    no_unselect = 0;
                    break;
            }
        }
        
        // Update screen and reset timer
	time_tick();
        if (draw_screen()) {
            t1 = SDL_GetTicks();
        }

        // Calculate time and send attack for multiplayer
        if (gm == GM_MULTIPLAYER) {
		update_player();
            if (ss == SS_CLOSE) {
                return 0;
            } else {
                t2 = SDL_GetTicks();
    	        if (t2 - t1 >= 3500 || combo_score > 310) {
    	            t1 = t2;
                    total_score += combo_score;

                    // Update life
		    if (combo_score) {
			    if (total_score >= 1400) {
				    total_score = 1400;
				    game_state.state = GAME_WIN;
			    } else start_attack(1);
	                    dest.x = LIFE_ENEMYX - total_score / 10;
	                    dest.y = LIFEY;
        	            dest.w = total_score / 10;
                	    dest.h = LIFE_HEIGHT;
	                    SDL_FillRect(screen, &dest, SDL_MapRGB(screen->format, 255, 0, 0));
        	            SDL_Update(LIFE_ENEMYX - LIFE_WIDTH, LIFEY, LIFE_WIDTH, LIFE_HEIGHT);
			    write_socket(&combo_score, sizeof(int));
	    	            combo_score = 0;

        	            // Erase progress bar
                	    dest.x = 21;
	                    dest.y = 335;
        	            dest.w = 311;
                	    dest.h = 36;
	                    SDL_BlitSurface(bg, &dest, screen, &dest);
        	            SDL_Update(dest.x, dest.y, dest.w, dest.h);
		    }
    	        }
            }

	// Timer for single player
	} else {
		t2 = SDL_GetTicks();
		if (t2 - t1 >= timer_delay) {
			t1 = t2;
			single_timer -= 2;
			if (single_timer <= 0) game_state.state = GAME_LOSE;
			draw_timer_bar(true);
		}
	}

    }
}
Exemplo n.º 17
0
int real_main() {
    srand48(time(NULL));

    if (!al_init()) {
        puts("Could not initialise allegro");
        return 1;
    }
    if (!al_install_keyboard()) {
        puts("Could not initialise allegro keyboard subsystem");
        return 1;
    }
    keys = malloc(sizeof(ALLEGRO_KEYBOARD_STATE));
    if (!init_font()) {
        puts("Could not initialise allegro font subsystem");
        return 1;
    }

    al_set_new_display_flags(ALLEGRO_FULLSCREEN_WINDOW);

    ALLEGRO_DISPLAY* display = al_create_display(1, 1);
    if (!display) {
        puts("Could not initialise allegro display");
        return 1;
    }

    Vector size = new_vector();
    size.x = al_get_display_width(display);
    size.y = al_get_display_height(display);

    Game* game = new_game(size);
    int i;
    for (i = 0; i < ASTEROIDN; i++)
        spawn_asteroid(game);

    ALLEGRO_TIMER* timer = al_create_timer(1.0/FPS);

    ALLEGRO_EVENT_QUEUE *timereq = al_create_event_queue();
    ALLEGRO_EVENT_QUEUE *genericeq = al_create_event_queue();
    if (!timereq || !genericeq) {
        puts("Could not create allegro event queue");
        return 1;
    }
    al_register_event_source(timereq, al_get_timer_event_source(timer));

    al_register_event_source(genericeq, al_get_keyboard_event_source());
    al_register_event_source(genericeq, al_get_display_event_source(display));

    al_start_timer(timer); // Start generating timer events
    ALLEGRO_EVENT *timerevent = malloc(sizeof(ALLEGRO_EVENT));
    ALLEGRO_EVENT *genericevent = malloc(sizeof(ALLEGRO_EVENT));

    float last_drawn, now;
    last_drawn = now = al_get_time();
    while (game->status != Quit) {
        al_get_keyboard_state(keys);

        al_wait_for_event(timereq, NULL);
        al_get_next_event(timereq, timerevent);
        // No need to fill up the queue if we are late drawing frames
        al_flush_event_queue(timereq);

        handle_key_status(game, keys);

        while(al_get_next_event(genericeq, genericevent))
            switch(genericevent->type) {
            case ALLEGRO_EVENT_KEY_DOWN:
                handle_key_event(game, genericevent->keyboard.keycode);
                break;

            case ALLEGRO_EVENT_DISPLAY_RESIZE:
                game->size.x = genericevent->display.x;
                game->size.y = genericevent->display.y;
                al_acknowledge_resize(display);
                break;

            case ALLEGRO_EVENT_DISPLAY_CLOSE:
                game->status = Quit;
                break;
            }

        now = al_get_time();
        update_game(game, now - last_drawn);
        last_drawn = now;

        draw_game(game, game->status == Playing ? 1 : 0.2);
        switch(game->status) {
        case Playing:
            break;
        case Paused:
            draw_paused(game);
            break;
        case Won:
            draw_won(game);
            break;
        case Lost:
            draw_lost(game);
            break;
        default:
            break;
        }

        al_flip_display();
    }

    free(timerevent);
    free(genericevent);
    delete_game(game);
    return 0;
}
Exemplo n.º 18
0
game new_game_hr(int nb_pieces, piece *pieces) {
    return new_game(RH_WIDTH, RH_HEIGHT, nb_pieces, pieces);
}
Exemplo n.º 19
0
/* Event handler in Podzilla compiling style */
static int tuxchess_handle_event(GR_EVENT *event)
{
	int ret = 0;
	switch (event->type)
	{
	case GR_EVENT_TYPE_KEY_DOWN:
		switch (event->keystroke.ch)
		{
		case'm':
			do_menu();
			ret |= KEY_CLICK;
			break;

		case'w':
			if (end == 0) {
				do_rev();
				ret |= KEY_CLICK;
			}
			break;

		case'f':
			if (end == 0) {
				do_fwd();
				ret |= KEY_CLICK;
			}
			break;

		case'\r':
			if (end == 0) {
				do_action();
			}
			else if (end == 1) {
				draw_end(end_type);
			}
			else {
				new_game();
			}
			ret |= KEY_CLICK;
			break;

		case'l':
			if (end == 0) {
				do_left();
				ret |= KEY_CLICK;
			}
			break;

		case'r':
			if (end == 0) {
				do_right();
				ret |= KEY_CLICK;
			}
			break;

		default:
			ret |= KEY_UNUSED;
			break;
		}
		break;
	default:
		ret |= EVENT_UNUSED;
		break;
	}

	return ret;
}
Exemplo n.º 20
0
void main(int argc, char **argv) {

	uint8_t starter;

	/* Initialization of the random generator */
	// srand(gettimeofday());

	char name[20];

	VERBOSE = false;
	NICE = false;
	
	int i;
	for (i = 1; i < argc; i++) {
		if (strcmp(argv[i], "-v") == 0) {
			VERBOSE = true;
		} else if (strcmp(argv[i], "-vv") == 0) {
			VERBOSE = true;
			NICE = true;
		}
	}

	if (VERBOSE) {
		if (NICE)
			printf("Good morning stranger! What's your name? ");
		else
			printf("[USERNAME] ");
	}

	/* WARNING: buffer overflow possible here (mouahaha) */
	scanf("%s", name);

	if (VERBOSE) {
		if (NICE)
			printf("Nice to meet you %s! I am Anastasia.\n", name);
	}

	starter = (rand() < 0.5)?0:1;

	if (VERBOSE && NICE) {
		if (starter == IA_ID)
			printf("I will play first.\n");
		else
			printf("You will play first.\n");
	}

	game_t *game = new_game(starter, name);

	while (!game_over(game)) { 
		if (VERBOSE && !NICE) {
			printf("*** NEW ROUND ***\n");
		}
		new_round(game);
	}

	if (VERBOSE && NICE) {
		printf("It is over. You played well %s. Come back see me soon!\n", name);
		/* Machine learning powa */
#if LEARN
		learn_from_game(&game);
#endif
	}

}
Exemplo n.º 21
0
/*
 * main -- Main program.
 */
int main(void) {
	uint8_t chars_into_escape_sequence = 0;
	int8_t moveStatus = 0;

	char c;

	/* Initialise our main clock */
	init_timer();

	/* Initialise serial I/O */
	init_serial_stdio(19200, 0);

	/* Make the display_row() function be called every 2ms.
	** (This function returns a timer number, but we ignore 
	** this since we'll never do anything with it.)
	*/
	execute_function_periodically(2, display_row);

	/* Register the time_increment() function to be called every 500ms.
	** This function just sets a variable (timePassedFlag).
	*/
	mainTimerNum = execute_function_periodically(500, time_increment);

	//4209435
	/* setup AVR to handle sounds*/
	init_sound();

	/*
	** Turn on interrupts (needed for timer and serial input/output to work)
	*/
	sei();
	
	/*
	** Display splash screen 
	*/
	splash_screen();
	show_instruction(NEWGAME);
	
	/*
	** Perform necessary initialisations for a new game.
	*/
	new_game();
		
	/*
	** Event loop - wait for a certain amount of time to pass or wait
	** for a character to arrive from standard input. The time_passed_flag
	** is set within the function time_increment() below - which is setup
	** to be called periodically.
	*/
	for(;;) {
		if(timePassedFlag) {
			moveStatus = move_snake();
			timePassedFlag = 0;
		} else if(input_available()) {
			/* Read the input from our terminal and handle it */
			c = fgetc(stdin);			
			if(chars_into_escape_sequence == 0 && c == '\x1b') {
				/*
				** Received ESCAPE character - we're one character into
				** an escape sequence
				*/
				chars_into_escape_sequence = 1;
			} else if(chars_into_escape_sequence == 1 && c == '[') {
				/* 
				** We're now two characters into an escape sequence
				*/
				chars_into_escape_sequence = 2;
			} else if (chars_into_escape_sequence == 2) {
				/* We're two characters into an escape sequence and
				** have received another - see if it is as expected.
				*/
				if (c == 'C') {
					/* Cursor right key pressed - Set next direction to
					** be moved to RIGHT */
					set_snake_dirn(RIGHT);
				}  
				if (c == 'D') {
					/* Cursor left key pressed - Set next direction to
					** be moved to LEFT */
					set_snake_dirn(LEFT);
				}  
				if (c == 'A') {
					/* Cursor up key pressed - Set next direction to
					** be moved to UP */
					set_snake_dirn(UP);
				}  
				if (c == 'B') {
					/* Cursor down key pressed - Set next direction to
					** be moved to DOWN */
					set_snake_dirn(DOWN);
				}

				/* else, unknown escape sequence */

				/* We're no longer part way through an escape sequence */
				chars_into_escape_sequence = 0; 
			} else if(chars_into_escape_sequence != 0) {
				/*
				** We started an escape sequence but didn't get a character
				** we recognised - discard it and assume that we're not
				** in an escape sequence.
				*/
				chars_into_escape_sequence = 0;
			} else if (c == ' ') {
				/* Space character received - move snake immediately */
				moveStatus = move_snake();
			} else {					
				if(c == 'N' || c == 'n'){	
					show_instruction(NEWGAME);				
					new_game();
				} else if(c == 'P' || c == 'p'){
					moveStatus = 0;
					pause_game();
				} else if(c == 'M' || c == 'm'){
					toggle_sound();
					display_sound_status();
				}
			}
		}

		switch(moveStatus){
			case ATE_FOOD:
				if(sound_status())
					play_sound();
				moveStatus = MOVE_OK;
				break;
		}

		if(moveStatus < 0) {
			/* Move failed - game over */
			handle_game_over();
			moveStatus = 0;
			update_score();
		}
	}
}
Exemplo n.º 22
0
CheckersGame::CheckersGame(){
    new_game();
    curState = getComputerState();
}
Exemplo n.º 23
0
static gboolean
cb_button_release (GtkWidget *widget, GdkEventMotion *event, gpointer data) {

    gui_world *world = (gui_world *)data;

    if (world->graphics->user_points->len < 50) {
        world->graphics->message = (char *)malloc(20 * sizeof(char));
        strcpy(world->graphics->message, "Size Too Small");

        g_array_free (world->graphics->user_points, TRUE);
        initialize_array(world);

        return TRUE;
    }

    else if (!world->draw_success) {
        world->graphics->message = (char *)malloc(20 * sizeof(char));
        strcpy(world->graphics->message, "Drew Outside Box");

        g_array_free (world->graphics->user_points, TRUE);
        initialize_array(world);

        return TRUE;
    }

    else {
        free(world->graphics->message);
        world->graphics->message = NULL;
    }

    if (world -> try_number > 3) {
        if (world->graphics->message != NULL) {
            free (world->graphics->message);
        }
        world->graphics->message = (char *)malloc(20 * sizeof(char));
        strcpy(world->graphics->message, "You Lose!");

        g_array_free (world->graphics->user_points, TRUE);

        initialize_array(world);

        new_game (world);
        return FALSE;
        //gtk_main_quit();
    }

    (world -> try_number)++;

    int skip_interval = world->graphics->user_points->len / DESIRED_NUMBER_VERTICES;

    int counter = 0;

    for (int i = 0; i < world->graphics->user_points->len; i++) {

        counter++;

        if (counter % skip_interval != 0) {

            g_array_remove_index (world->graphics->user_points, i);
            i--;
        }
    }

    create_user_object ((cpVect *)world->graphics->user_points->data, world->graphics->user_points->len, world->color, world->physics, PLAYER_BOX_COLLISION_NUMBER, 0.7, world->mass);

    g_array_free (world->graphics->user_points, TRUE);

    initialize_array(world);

    return TRUE;

}
Exemplo n.º 24
0
int main(int argc, char **argv)
{
    game_params *p;
    game_state *s;
    char *id = NULL, *desc, *err;
    int grade = FALSE;
    int ret, diff, really_show_working = FALSE;

    while (--argc > 0) {
        char *p = *++argv;
        if (!strcmp(p, "-v")) {
            really_show_working = TRUE;
        } else if (!strcmp(p, "-g")) {
            grade = TRUE;
        } else if (*p == '-') {
            fprintf(stderr, "%s: unrecognised option `%s'\n", argv[0], p);
            return 1;
        } else {
            id = p;
        }
    }

    if (!id) {
        fprintf(stderr, "usage: %s [-g | -v] <game_id>\n", argv[0]);
        return 1;
    }

    desc = strchr(id, ':');
    if (!desc) {
        fprintf(stderr, "%s: game id expects a colon in it\n", argv[0]);
        return 1;
    }
    *desc++ = '\0';

    p = default_params();
    decode_params(p, id);
    err = validate_desc(p, desc);
    if (err) {
        fprintf(stderr, "%s: %s\n", argv[0], err);
        return 1;
    }
    s = new_game(NULL, p, desc);

    /*
     * When solving an Easy puzzle, we don't want to bother the
     * user with Hard-level deductions. For this reason, we grade
     * the puzzle internally before doing anything else.
     */
    ret = -1;			       /* placate optimiser */
    solver_show_working = FALSE;
    for (diff = 0; diff < DIFFCOUNT; diff++) {
	memcpy(s->grid, s->clues->immutable, p->w * p->w);
	ret = solver(p->w, s->clues->clues, s->grid, diff);
	if (ret <= diff)
	    break;
    }

    if (diff == DIFFCOUNT) {
	if (grade)
	    printf("Difficulty rating: ambiguous\n");
	else
	    printf("Unable to find a unique solution\n");
    } else {
	if (grade) {
	    if (ret == diff_impossible)
		printf("Difficulty rating: impossible (no solution exists)\n");
	    else
		printf("Difficulty rating: %s\n", towers_diffnames[ret]);
	} else {
	    solver_show_working = really_show_working;
	    memcpy(s->grid, s->clues->immutable, p->w * p->w);
	    ret = solver(p->w, s->clues->clues, s->grid, diff);
	    if (ret != diff)
		printf("Puzzle is inconsistent\n");
	    else
		fputs(game_text_format(s), stdout);
	}
    }

    return 0;
}
Exemplo n.º 25
0
void startup_menu(void)
{


 reset_menu_palette();


 menu_select = 0;
 key_wait = 30;

// int counter;

 menu_counter = 0;
 counter2 = 0;

 arena.difficulty = 0;

 int y1 = 170;
 int y2 = 190 + menu_select * 30;
 int y3 = 218 + menu_select * 30;
 int y4 = 218 + menu_select * 30;

 int anykey = 0;

 int i;

//#define TEST_MUSIC


#ifdef TEST_MUSIC

 arena.level = 3;

 init_beat_new_level();

#endif

 init_menu_circles();

 while (TRUE)
 {


#ifdef TEST_MUSIC
run_beat();

#endif



 clear_to_color(display, COL_BACK1);


 run_menu_background();



 menu_counter += 4;
 if (menu_counter >= 40)
  menu_counter = 0;

 counter2 ++;
 if (counter2 >= 256)
  counter2 = 0;

// textprintf_centre_ex(display, font, 300, 190, -1, -1, "W H I T E   B U T T E R F L Y");
 draw_rle_sprite(display, white_RLE, 150, 150);

 int my = 300;

 y1 = my - 23;
 y2 = my - 10 + menu_select * 30;
 y3 = my + 19 + menu_select * 30;
 y4 = my + 150;


// rectfill(display, 370, y1, 600, y2, COL_COL1);
 TRANS_MODE
 rectfill(display, 370, y2 + 9, 640, y3 - 2, TRANS_BLUE3);
 rect(display, 368, y2 + 7, 641, y3 - 0, TRANS_BLUE3);
 END_TRANS
// rectfill(display, 370, y3, 600, y4, TRANS_DGREEN);


 textprintf_ex(display, font, 400, my, -1, -1, "START GAME");
 switch(arena.difficulty)
 {
      case 0: textprintf_ex(display, font, 400, my + 30, -1, -1, "DIFFICULTY - NORMAL"); break;
      case 1: textprintf_ex(display, font, 400, my + 30, -1, -1, "DIFFICULTY - HARD"); break;
      case 2: textprintf_ex(display, font, 400, my + 30, -1, -1, "DIFFICULTY - PUNISHMENT"); break;
 }
// textprintf_ex(display [2], font, 400, 260, -1, -1, "STAGE - %i", arena.starting_level);
 textprintf_ex(display, font, 400, my + 90, -1, -1, "SET  KEYS");
 textprintf_ex(display, font, 400, my + 120, -1, -1, "OPTIONS");
 textprintf_ex(display, font, 400, my + 150, -1, -1, "EXIT");

// textprintf_ex(display, font, 40, 10, -1, -1, "%i", joy[0].stick[options.joy_stick].axis[0].pos);
// textprintf_ex(display, font, 40, 30, -1, -1, "%i", joy[0].stick[options.joy_stick].axis[1].pos);

/*
 if (options.joystick)
  textprintf_ex(display, font, 400, my + 120, -1, -1, "CALIBRATE JOYSTICK");
   else
   {
    textprintf_ex(display, font, 400, my + 120, -1, -1, "NO JOYSTICK");
    drawing_mode(DRAW_MODE_TRANS, NULL, 0, 0);
    rectfill(display, 399, my + 110, 530, my + 135, CONVERT_WHITE_TO_GREY);
    drawing_mode(DRAW_MODE_SOLID, NULL, 0, 0);
   }
*/
 if (options.joystick)
 {
  if (options.key_or_joy == 1)
  textprintf_ex(display, font, 400, my + 60, -1, -1, "CONTROLS - JOYSTICK");
   else
    textprintf_ex(display, font, 400, my + 60, -1, -1, "CONTROLS - KEYBOARD");
 }
  else
  {
   textprintf_ex(display, font, 400, my + 60, -1, -1, "NO JOYSTICK");
   drawing_mode(DRAW_MODE_TRANS, NULL, 0, 0);
   rectfill(display, 399, my + 50, 530, my + 75, CONVERT_WHITE_TO_GREY);
   drawing_mode(DRAW_MODE_SOLID, NULL, 0, 0);

  }


// textprintf_ex(display, font, 5, 5, -1, -1, "%i", any_joystick_input());



 my = 330;

 y2 = my + 7 + arena.just_got_highscore * 30;
 y3 = my + 29 + arena.just_got_highscore * 30;


 if (arena.just_got_highscore > 0)
 {
   rectfill(display, 0, y2 - 5, 250, y3, COL_COL3);
   rect(display, -1, y2 - 5 - 2, 250 + 2, y3 + 2, COL_COL4);
 }

// textprintf_right_ex(display, font, 137, my, -1, -1, "HIGH");
// textprintf_ex(display, font, 157, my, -1, -1, "SCORES");

 textprintf_centre_ex(display, font, 147, my, -1, -1, "HIGHSCORES");

 textprintf_right_ex(display, font, 137, my + 40, -1, -1, "NORMAL");
 textprintf_ex(display, font, 157, my + 40, -1, -1, "%i", options.highscore [0]);

 textprintf_right_ex(display, font, 137, my + 70, -1, -1, "HARD");
 textprintf_ex(display, font, 157, my + 70, -1, -1, "%i", options.highscore [1]);

 textprintf_right_ex(display, font, 137, my + 100, -1, -1, "PUNISHMENT");
 textprintf_ex(display, font, 157, my + 100, -1, -1, "%i", options.highscore [2]);

 textprintf_right_ex(display, font, 600, 570, -1, -1, "COPYRIGHT 2009 LINLEY HENZELL");

// should print last score here...

 anykey = 0;

  for (i = KEY_A; i < KEY_CAPSLOCK + 1; i ++)
  {
   if (key [i])
   {
    anykey = 1;
   }
  }

  if (anykey == 0 && (options.joystick == 0 || any_joystick_input() == 0))
   key_wait = 0;



 if (key_wait == 0)
 {
  if (menu_command(MC_UP))
  {
   menu_select --;
   if (menu_select < 0)
    menu_select = MENU_EXIT;
   if (menu_select == MENU_JOY_OR_KEYS && options.joystick == 0)
    menu_select = MENU_JOY_OR_KEYS - 1;
   key_wait = 7;
  }
  if (menu_command(MC_DOWN))
  {
   menu_select ++;
   if (menu_select > MENU_EXIT)
    menu_select = 0;
   if (menu_select == MENU_JOY_OR_KEYS && options.joystick == 0)
    menu_select = MENU_KEYS;
   key_wait = 7;
  }
  if (menu_command(MC_LEFT))
  {
//   if (menu_select == 2)
//    arena.starting_level = 1;
   if (menu_select == MENU_JOY_OR_KEYS)
   {
    if (options.key_or_joy == 0)
     options.key_or_joy = 1;
      else
       options.key_or_joy = 0;
   }
   if (menu_select == MENU_DIFFICULTY)
   {
    arena.difficulty --;
    if (arena.difficulty < 0)
     arena.difficulty = 0;
   }
   key_wait = 7;
  }
  if (menu_command(MC_RIGHT))
  {
//   if (menu_select == 2)
//    arena.starting_level = 2;
   if (menu_select == MENU_JOY_OR_KEYS)
   {
    if (options.key_or_joy == 0)
     options.key_or_joy = 1;
      else
       options.key_or_joy = 0;
   }
   if (menu_select == MENU_DIFFICULTY)
   {
    arena.difficulty ++;
    if (arena.difficulty > 2)
     arena.difficulty = 2;
   }
   key_wait = 7;
  }

//  if (key [KEY_ESC])
//   exit(0);
  if (menu_command(MC_SELECT))
  {
   if (menu_select == MENU_EXIT)
   {
    goodbye_menu_circles();
    return;
   }

   if (menu_select == MENU_KEYS)
   {
    key_wait = 10;
    define_keys();
    key_wait = 10;
   }

   if (menu_select == MENU_OPTIONS)
   {
    key_wait = 10;
    set_options();
    key_wait = 10;
   }

/*   if (menu_select == MENU_CALIBRATE)
   {
    jstick_calibrate();
    key_wait = 20;
    ticked = 0;
   }*/

   if (menu_select == MENU_START)
   {
    arena.level = 1;//arena.starting_level;
    ticked = 0;
    key_wait = 30;
    if (ship_select() == 1)
    {
     vsync();
//     clear_bitmap(screen);
//     clear_bitmap(display);
     player.type = PTYPE_BASIC;
//     player.type = PTYPE_BOMBER;
//     player.type = PTYPE_ANENOME;
//     player.type = PTYPE_HAND;
     player.weapon_level = 0;
     int ship_select = select_a_ship();
     if (ship_select != -1)
     {
      switch(ship_select)
      {
       default:
       case 0: player.type = PTYPE_BASIC; break;
       case 1: player.type = PTYPE_ANENOME; break;
       case 2: player.type = PTYPE_BOMBER; break;
       case 3: player.type = PTYPE_HAND; break;
       case 4: player.type = PTYPE_SQUID; break;
      }
      if (arena.level == 1)
       arena.from_start = 1;
        else
         arena.from_start = 0;
      arena.cleared = 0;
      arena.unlocked = 0;
      menu_counter = 0;
      goodbye_menu_circles();
      new_game();
      game_loop();
      if (arena.level == 4)
       congratulations();
      arena.target_palette = PAL_MENU;
      arena.shift_palette = 2;
      init_menu_circles();
//     reset_menu_palette();
      key_wait = 10; // was 1
//      flower_dir *= -1;
      ticked = 0;
     }
    }
     else key_wait = 20;
   }
    else
     key_wait = 20;
  }
 }
  else
   key_wait --;




    do
    {
        thing ++;
    } while (ticked == 0);
    ticked = 0;

 if (arena.shift_palette > 0 && menu_counter % 12 == 0)
 {
  run_palette_shift();
  build_new_palette(0, 0, 0, 0);
  set_palette(palet);
  if (arena.shift_palette == 1)
   arena.shift_palette = 0;
 }

 vsync();
 blit(display, screen, 0, 0, 100, 0, 600, 600);



 };


}
Exemplo n.º 26
0
void test_game_suite__000(void) {
    new_game();
    Position *p = start();

    Move m0 = new_move(p, E2, E4);
    Move m1 = new_move(p, E7, E5);
    Move m2 = new_move(p, G1, F3);
    Move m3 = new_move(p, B8, C6);
    Move m4 = new_move(p, F1, B5);
    save_best(0, m0);
    save_best(1, m1);
    save_best(2, m2);
    save_best(3, m3);
    save_best(4, m4);

    cl_check(game.pv[0].size == 1);
    cl_check(game.pv[0].moves[0] == m0);
    cl_check(game.pv[1].size == 2);
    cl_check(game.pv[1].moves[0] == (Move)0);
    cl_check(game.pv[1].moves[1] == m1);
    cl_check(game.pv[2].size == 3);
    cl_check(game.pv[2].moves[0] == (Move)0);
    cl_check(game.pv[2].moves[1] == (Move)0);
    cl_check(game.pv[2].moves[2] == m2);
    cl_check(game.pv[3].size == 4);
    cl_check(game.pv[3].moves[0] == (Move)0);
    cl_check(game.pv[3].moves[1] == (Move)0);
    cl_check(game.pv[3].moves[2] == (Move)0);
    cl_check(game.pv[3].moves[3] == m3);
    cl_check(game.pv[4].size == 5);
    cl_check(game.pv[4].moves[0] == (Move)0);
    cl_check(game.pv[4].moves[1] == (Move)0);
    cl_check(game.pv[4].moves[2] == (Move)0);
    cl_check(game.pv[4].moves[3] == (Move)0);
    cl_check(game.pv[4].moves[4] == m4);

    Move m5 = new_move(p, A7, A6);
    save_best(1, m5);

    cl_check(game.pv[0].size == 1);
    cl_check(game.pv[0].moves[0] == m0);
    cl_check(game.pv[1].size == 3);                       // <--
    cl_check(game.pv[1].moves[0] == (Move)0);
    cl_check(game.pv[1].moves[1] == m5);                  // <--
    cl_check(game.pv[1].moves[2] == game.pv[2].moves[2]); // <--
    cl_check(game.pv[2].size == 3);
    cl_check(game.pv[2].moves[0] == (Move)0);
    cl_check(game.pv[2].moves[1] == (Move)0);
    cl_check(game.pv[2].moves[2] == m2);
    cl_check(game.pv[3].size == 4);
    cl_check(game.pv[3].moves[0] == (Move)0);
    cl_check(game.pv[3].moves[1] == (Move)0);
    cl_check(game.pv[3].moves[2] == (Move)0);
    cl_check(game.pv[3].moves[3] == m3);
    cl_check(game.pv[4].size == 5);
    cl_check(game.pv[4].moves[0] == (Move)0);
    cl_check(game.pv[4].moves[1] == (Move)0);
    cl_check(game.pv[4].moves[2] == (Move)0);
    cl_check(game.pv[4].moves[3] == (Move)0);
    cl_check(game.pv[4].moves[4] == m4);
}
Exemplo n.º 27
0
int
main (int argc, char *argv [])
{
	GtkWidget *label;
	GnomeClient *client;

	gnome_score_init("same-gnome");

	bindtextdomain (PACKAGE, GNOMELOCALEDIR);
	textdomain (PACKAGE);

	gnome_init_with_popt_table ("same-gnome", VERSION, argc, argv, options, 0, NULL);

	gnome_window_icon_set_default_from_file (GNOME_ICONDIR"/gnome-gsame.png");
	client= gnome_master_client ();

	gtk_signal_connect (GTK_OBJECT (client), "save_yourself",
			    GTK_SIGNAL_FUNC (save_state), argv[0]);
	gtk_signal_connect (GTK_OBJECT (client), "die",
			    GTK_SIGNAL_FUNC (client_die), NULL);

	if (GNOME_CLIENT_RESTARTED (client)){
		gnome_config_push_prefix (gnome_client_get_config_prefix (client));
	    
		restart ();
		restarted = 1;
		
		gnome_config_pop_prefix ();
	}

	srand (time (NULL));

	app = gnome_app_new("same-gnome", _("Same Gnome"));

        gtk_window_set_policy(GTK_WINDOW(app), FALSE, FALSE, TRUE);
	gtk_signal_connect (GTK_OBJECT(app), "delete_event",
			    (GtkSignalFunc)game_quit_callback, NULL);

	appbar = gnome_appbar_new(FALSE, TRUE, GNOME_PREFERENCES_USER);
	gnome_app_set_statusbar(GNOME_APP (app), GTK_WIDGET(appbar));

	gnome_appbar_set_status(GNOME_APPBAR (appbar),
				_("Welcome to Same Gnome!"));

	gnome_app_create_menus(GNOME_APP(app), mainmenu);

	gnome_app_install_menu_hints(GNOME_APP (app), mainmenu);
  
        vb = gtk_vbox_new (FALSE, 0);
	gnome_app_set_contents (GNOME_APP (app), vb);

	if (!fname) {
		fname = gnome_config_get_string
			("/same-gnome/Preferences/Scenario=stones.png");
	}

	create_same_board (fname);

	label = gtk_label_new (_("Score: "));
	scorew = gtk_label_new ("");
	set_score (score);

	gtk_box_pack_start(GTK_BOX(appbar), label, FALSE, TRUE, 0);
	gtk_box_pack_start(GTK_BOX(appbar), scorew, FALSE, TRUE, 0);
	
	if (!restarted)
		new_game ();
	
	g_free (fname);

	gtk_widget_show (vb);
	gtk_widget_show (GTK_WIDGET(label));
	gtk_widget_show (GTK_WIDGET(scorew));
        gtk_widget_show (app);

	gtk_main ();
	return 0;
}
Exemplo n.º 28
0
/**
 * @brief Creates a new standard Tetris game.
 * 
 * The standard configuration is: 20 rows, 10 columns and the 7 standard pieces.
 * The pieces are loaded from the file \c pieces4.dat,
 * so this file is supposed to be in the current directory.
 *
 * @return the game created
 * @see new_game(), new_game_from_parameters(), new_game_copy(), free_game()
 */
Game *new_standard_game() {

  return new_game(0, 10, 20, 0, "pieces4.dat", NULL);

}
Exemplo n.º 29
0
/* 
 * ===  FUNCTION  ======================================================================
 *         Name:  read_guess
 *  Description:  Reads the guess into the external variable current_char and updates
 *                external variable letters_used array to keep track on used chars; 
 *                checks for bad guess and dublicates.
 * =====================================================================================
 */
void read_guess (void)
{
  
  bool bad_char, dublicated_char;
  char ch, letter_ch, letter; 
  int i, chars_read = 0;
  
  if (game_over){
 
    /* Checks if user wishes to play more*/
    while (chars_read < 1){ 
      bad_char = false;
      printf("Do you wanna play again? yes[y], no[n]: ");
     
      letter_ch = tolower(getchar());   
      switch (letter_ch){
        case '0': exit (EXIT_SUCCESS);
        case 'y': letter = 'y'; break;
        case 'n': letter = 'n'; break;  
        default: bad_char = true;                
      }
   
      while ((ch = getchar()) != '\n')
        if (ch != ' ') bad_char = true;
    
      if (bad_char){
        printf(ANSI_COLOR_RED "Bad char; ignored.\n" ANSI_COLOR_RESET);   
      }else{
        if(letter == 'y'){
          new_game();
          chars_read++;
        }else{
          exit (EXIT_SUCCESS);
        } 
      }   
    }
    chars_read = 0;
  }
  /* input for char to guess */
  while (chars_read < 1){
    
    bad_char = false;
    dublicated_char = false;
           
    printf("Enter a char: ");
    
    letter_ch = tolower(getchar());
    switch (letter_ch){
      case '0': exit (EXIT_SUCCESS);
      case 'a': letter = 'a'; break;
      case 'b': letter = 'b'; break;
      case 'c': letter = 'c'; break;
      case 'd': letter = 'd'; break;
      case 'e': letter = 'e'; break;
      case 'f': letter = 'f'; break;
      case 'g': letter = 'g'; break; 
      case 'h': letter = 'h'; break;
      case 'i': letter = 'i'; break;
      case 'j': letter = 'j'; break;
      case 'k': letter = 'k'; break;
      case 'l': letter = 'l'; break;
      case 'm': letter = 'm'; break;
      case 'n': letter = 'n'; break;
      case 'o': letter = 'o'; break;
      case 'p': letter = 'p'; break;
      case 'q': letter = 'q'; break;    
      case 'r': letter = 'r'; break;
      case 's': letter = 's'; break;
      case 't': letter = 't'; break; 
      case 'u': letter = 'u'; break;
      case 'v': letter = 'v'; break;          
      case 'w': letter = 'w'; break;
      case 'x': letter = 'x'; break;
      case 'y': letter = 'y'; break;
      case 'z': letter = 'z'; break;          
      default:  bad_char = true;          
    }

    /* Check for dublicated chars*/
    for (i=0; i <= 26; i++){     
      if (letters_used[i][0] == letter && letters_used[i][1] == true)
        dublicated_char = true;      
    }

    while ((ch = getchar()) != '\n')
        if (ch != ' ') bad_char = true;

    if (bad_char)
      printf(ANSI_COLOR_RED "Bad char; ignored.\n" ANSI_COLOR_RESET);   
    else if(dublicated_char)
      printf(ANSI_COLOR_RED "Dublicated char; ignored.\n" ANSI_COLOR_RESET);
    else {
     count++;
      chars_read++;
      current_char = letter;
      /* insert char into letters_used array */
      for (i = 0; i <= 26; i++){      
        if (letters_used[i][0] == letter)
          letters_used[i][1] = true;      
      }      
    }     
  }


}		/* -----  end of function read_guess  ----- */
Exemplo n.º 30
0
// Show and loop main menu
void show_menu_loop() {
    char *ip = "";
    FILE *han;
    SDL_Event event;
    int createserver = 0;
    SDL_Thread *ReadThread;
    //GConfClient *gcc = NULL;

    // Init GConf
    //g_type_init();
    //gcc = gconf_client_get_default();
    //createserver = gconf_client_get_bool(gcc, BATTLEGWELED_CREATESERVER, NULL);
    //ip = gconf_client_get_string(gcc, BATTLEGWELED_SERVERIP, NULL);

    // Single player
    if (!createserver && !strcmp(ip, "")) {
	han = fopen("/tmp/.battlegweled-save", "rb");
	if (han) {
		fread(&total_score, sizeof(int), 1, han);
		fread(&single_timer, sizeof(int), 1, han);
		fread(&timer_delay, sizeof(int), 1, han);
		fread(&score, sizeof(int), 1, han);
       		fread(nb_of_tiles, sizeof(nb_of_tiles), 1, han);
       		fread(matrix, BOARD_WIDTH * BOARD_HEIGHT, sizeof(int), han);
       		fclose(han);
       		new_game(true, GM_SINGLE, true);
    	} else new_game(true, GM_SINGLE, false); 
       	if (game_loop()) {
		flush_callback(0);
		quit_callback(0);
	} else exit_callback(0);
    } else {
	    int joined;
	    if (createserver) create_game();
	    else joined = join_game(ip);

            while (1) {

	        // If connected then start the game
	        if (ss == SS_CONNECTED) {
	            new_game(true, GM_MULTIPLAYER, false);
	            ReadThread = SDL_CreateThread(multi_player_loop, "ReadThread", NULL);
	            game_loop();
	            //SDL_KillThread(ReadThread);
                    SDL_WaitThread(ReadThread, NULL);
		    break;
                }

		if (ss == SS_ERROR || (SDL_PollEvent(&event) && ((event.key.state == SDL_PRESSED && (event.key.keysym.sym == SDLK_ESCAPE
			|| event.key.keysym.sym == SDLK_F4 || event.key.keysym.sym == SDLK_F5 || event.key.keysym.sym == SDLK_F6))
			|| event.type == SDL_QUIT || (event.type == SDL_MOUSEBUTTONDOWN && event.button.x >= BACK_OFFSETX
			&& event.button.y >= BACK_OFFSETY && event.button.x < BACK_OFFSETX2 && event.button.y < BACK_OFFSETY2)))) {
                        SDL_WaitThread(ThreadConnect, NULL);
                        SDL_WaitThread(ThreadAccept, NULL);
			//if (ThreadConnect) SDL_KillThread(ThreadConnect);
                        //if (ThreadAccept) SDL_KillThread(ThreadAccept);
			break;
                }

		// Update screen
        	draw_waiting_screen();
        }
	quit_callback(0);
    }
}