Skip to content

Commit

Permalink
Optimize insert_tile_rand()
Browse files Browse the repository at this point in the history
Though this function isn't called very often, so I doubt it has a measurable
impact on the total performance.

Also, the result of the draw_tile() function is now always (explicitly or
implicitly) converted to board_t. So we can as well immediately return a
board_t.
  • Loading branch information
m9710797 authored and nneonneo committed Apr 13, 2014
1 parent 81e1048 commit ff38663
Showing 1 changed file with 15 additions and 15 deletions.
30 changes: 15 additions & 15 deletions 2048.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -411,27 +411,28 @@ int ask_for_move(board_t board) {
}

/* Playing the game */
static int draw_tile() {
static board_t draw_tile() {
return (unif_random(10) < 9) ? 1 : 2;
}

static board_t insert_tile_rand(board_t board, int tile) {
static board_t insert_tile_rand(board_t board, board_t tile) {
int index = unif_random(count_empty(board));
for(int i=0; i<16; i++) {
if(((board >> (4*i)) & 0xf) != 0)
continue;
if(index == 0) {
board |= ((board_t)tile) << (4*i);
break;
board_t tmp = board;
while (true) {
while ((tmp & 0xf) != 0) {
tmp >>= 4;
tile <<= 4;
}
index--;
if (index == 0) break;
--index;
tmp >>= 4;
tile <<= 4;
}

return board;
return board | tile;
}

static board_t initial_board() {
board_t board = board_t(draw_tile()) << (4 * unif_random(16));
board_t board = draw_tile() << (4 * unif_random(16));
return insert_tile_rand(board, draw_tile());
}

Expand Down Expand Up @@ -464,9 +465,8 @@ void play_game(get_move_func_t get_move) {
continue;
}

int tile = draw_tile();
if(tile == 2)
scorepenalty += 4;
board_t tile = draw_tile();
if (tile == 2) scorepenalty += 4;
board = insert_tile_rand(newboard, tile);
}

Expand Down

0 comments on commit ff38663

Please sign in to comment.