Skip to content

Commit

Permalink
Obtimize horizontal movement function.
Browse files Browse the repository at this point in the history
  • Loading branch information
Silica163 committed May 5, 2023
1 parent ea0fe4c commit ed98689
Showing 1 changed file with 32 additions and 23 deletions.
55 changes: 32 additions & 23 deletions 2048.c
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ int main(){
int game_state[ROW][COL];
createMap(&game_state);
print_state(&game_state);
move(&game_state,4);
print_state(&game_state);
move(&game_state,3);
print_state(&game_state);
return 0;
while(1){
unsigned int dir;
print_state(&game_state);
printf("up[1] down[2] right[3] left[4] : ");
scanf("%u",&dir);
move(&game_state,dir);
}
return 0;
}

Expand All @@ -34,7 +36,7 @@ void print_state(int (*state)[ROW][COL]){
void createMap(int (*state)[ROW][COL]){
for(int r = 0;r < ROW;r++){
for( int c = 0;c < COL;c++ ){
(*state)[r][c] = (c == r)*((c+1) >> 1)*2;
(*state)[r][c] = ( c << r) ^ (r << c);
}
}
}
Expand All @@ -45,23 +47,30 @@ void move(int (*st)[ROW][COL],unsigned int dir){
// 1 2 3 4
//move left

for(int r = 0 ; r < ROW && dir == 4;r++){
for(int c = 0;c < COL;c++){
if((*st)[r][c] != 0 && c != 0){
for(int c2 = 0;c2 < COL;c2++)if((*st)[r][c2] == 0){
(*st)[r][c2] = (*st)[r][c];
(*st)[r][c] = 0;
break;
}
}
}
}
for(int r = 0 ; r < ROW && dir == 3;r++){
for(int c = COL-1 ; c >= 0;c--){
if((*st)[r][c] != 0 && c != COL-1){
for(int c2 = COL-1 ; c2 >=0 ;c2--)if((*st)[r][c2] == 0){
(*st)[r][c2] = (*st)[r][c];
(*st)[r][c] = 0;
int up = dir ==1;
int down = dir == 2;
int right = dir == 3;
int left = dir == 4;

int cEdge1 = (COL-1) * right;
int cEdge2 = COL * left ;

// move horizontal
for(int r = 0 ; r < ROW ;r++){
for(
int c = cEdge1;
( c < cEdge2 && left) || (c >= cEdge2 && right);
c += (-1 * right) + (1 * left)
){
int *now = &(*st)[r][c];
if(*now != 0 && c != cEdge1 ){
for(
int c2 = cEdge1 ;
(c2 < c && left) || (c2 >= c && right );
c2 += (-1 * right) + (1 * left)
)if((*st)[r][c2] == 0){
(*st)[r][c2] = *now;
*now = 0;
break;
}
}
Expand Down

0 comments on commit ed98689

Please sign in to comment.