The method of realizing 2048 games by using C language _c language

Source: Internet
Author: User
Tags clear screen rand

Preparatory work

First of all, because here is only in the C language verification algorithm, so there is no good interface to do optimization, ugly is deserved.


Knowing how the game works, you can actually describe the game as four identical operations with directions:

1. Move all numbers in one Direction to no vacancy in the middle

2, add the adjacent two identical numbers and then put them in a position closer to the front of the moving direction.

In addition, you need to determine whether the current input of the player can be executed, if you do not wait for the user to perform the next record.

Also need to control the process of the game, if you can continue to play, then run the player to continue to enter the next instruction, and if not, then prompts can not continue the game.

The first problem is the input of the cursor key. The cursor key belongs to the function key, which is certainly not readable using the regular scanf, while the getch() standard input in bytes is used closer to the hardware. When using a getch() function for standard input, if the user enters a function key, such as the cursor key, home, PgUp, PgDn, end and so on, getch() will be able to read the two characters. When you encounter a function key input, you can write a test program to obtain the corresponding key data:

#include <stdio.h>
int main () {
 while (1) {
  printf ("%d\n", Getch ());
 }

This data extractor is then run, and the program will output the Getch data in an integer format, in a byte line. Here I query to 2048 need to use the four key ↑↓←→ corresponding two bytes is:

Keys First byte Second byte
224 72
224 80
224 75
224 77

And then there's the main code of the game.

#include <stdio.h>//Standard input/output #include <stdlib.h>//Basic tool functions #define BOOL int//C There is no Boolean type, make it yourself #define TRUE 1  The two values of bool #define FALSE 0 int map[4][4]= {0};
 
Map, default 0 is considered empty typedef enum {//define a direction type enum variable unknow, up, down, left, right} Direction;  void Printmap (); Draw graphics Direction getnextdirection (); Read the next user operation from the keyboard bool Canmove (Direction Direction);   Determines whether the operation void Doaction () can be performed in the specified direction;  Game event void Move (Direction Direction);    Mobile digital void putnew ();   Put a new number int main () {//main function Direction nextStep;
 Next int i,j;
 Srand (Time (0));    Putnew ();
 The game starts by default put two digit putnew ();    Printmap (); Print lattice while (1) {if (!canmove) &&!canmove (left) &&!canmove (down) &&!canmove;  Can not move in any direction, then terminate the game nextstep=getnextdirection ();  Gets the next user action if (nextstep==unknow) continue; If you do not know what button the user pressed or the user randomly presses, then enter the new cycle if (!canmove (nextStep)) continue;    Enter the new loop system (the "CLS") if the next step cannot be continued;   For Windows, execute the command line command CLS clear screen doaction (nextStep);
Perform an action  Putnew ();    Put a new number printmap ();   Print lattice} printf ("You died!");     Tip Game Over while (1);
 Wait for game to end} void Printmap () {int i,j;
 printf ("*-------*-------*-------*-------*\n");
  For (i=0 i<4; i++) {printf ("|");
   For (j=0 j<4; j + +) {map[i][j]?printf ("%d", Map[i][j]):p rintf ("");
   printf ("\t|");
  if (j>2) printf ("\ n");
 printf ("*-------*-------*-------*-------*\n");
 } void Doaction (Direction Direction) {int i,j,k; /** * To facilitate the handling of problems, the movement of each direction is simplified to three steps * 1. Merge the numbers into One Direction * 2. Process the same number to eliminate and set the elimination data to 0 * 3. Merge the numbers into One Direction again///1. Move numbers, cancel spaces between digits m
 Ove (direction); 2. In accordance with the direction of the same digital switch (direction) {case up:////Column enumeration for (i=0;i<4;i++) {//per-row for each element for (j=0;j<3;j++) {//IF
     Element Non-zero, and current and next same, current doubling, next 0 if (Map[j][i]&&map[j][i]==map[j+1][i]) {map[j][i]+=map[j+1][i];
    map[j+1][i]=0;
 }} break; Case left://Ibid. (i=0;i<4;i++) for (j=0;j<3;j++) if (map[i][j]&&map[i][j]==map[i][j+1)) {MAP[i] [j]+=MAP[I][J+1];
    map[i][j+1]=0;
 } break; Case down://Ibid. (i=0;i<4;i++) for (j=3;j>0;j--) if (map[j][i]&&map[j][i]==map[j-1][i)) {MAP[j]
     [I]+=map[j-1][i];
    map[j-1][i]=0;
 } break; Case right://Ibid. (i=0;i<4;i++) for (j=3;j>0;j--) if (map[i][j]&&map[i][j]==map[i][j-1)) {MAP[i
     ][J]+=MAP[I][J-1];
    map[i][j-1]=0;
 } break;
//3. Move the number to cancel the newly generated vacancy motion (direction) due to the previous step 0 process;
 } void Move (Direction Direction) {//mobile digital int i,j,k; switch (direction) {case up://Column enumeration for (i=0;i<4;i++)//For each element of each row for (j=0;j<4;j++)//If Non-zero, then the current position should be canceled, and the Element moves forward if (!
     Map[j][i]) {for (k=j;k<3;k++) {map[k][i]=map[k+1][i];
    }//Newly generated empty position 0 map[k][i]=0;
 } break; Case left://Ibid. (i=0;i<4;i++) for (j=0;j<4;j++) if (!
     Map[i][j]) {for (k=j;k<3;k++) {map[i][k]=map[i][k+1];
    } map[i][k]=0;
 } break; Case down://ditto for (i=0;i<4;i++) for (j=3;j>=0;j--) if (!
     Map[j][i]) {for (k=j;k>0;k--) {map[k][i]=map[k-1][i];
    } map[k][i]=0;
 } break; Case right://Ibid. (i=0;i<4;i++) for (j=3;j>=0;j--) if (!
     Map[i][j]) {for (k=j;k>0;k--) {map[i][k]=map[i][k-1];
    } map[i][k]=0;
 } break;
 } bool Canmove (Direction Direction) {//To determine whether a specified direction can be operated int i,j;
    switch (direction) {case up://Check each column for (i=0;i<4;i++) {//) first to exclude a string of empty at the far end, directly point J to the first non 0 element for (j=3;j>=0;j--)
  if (Map[j][i]) break; J>0 represents that this column is not all 0 if (j>0)//check each remaining element in turn, meets the empty directly returns True for (; j>=0;j--) if (!
  Map[j][i]) return true;
  Check to see if the adjacent elements have the same non-0 digit for (j=3;j>0;j--) if (Map[j][i]&&map[j][i]==map[j-1][i]) return true in turn;
 } break;
   Case down://AS-is (i=0;i<4;i++) {for (j=0;j<4;j++) if (map[j][i)); if (j<4) for (; j<4;j++) if (!
   Map[j][i]) return true;
   for (j=0;j<3;j++) if (Map[j][i]&&map[j][i]==map[j+1][i])  return true;
 } break;
   Case left://-ditto for (i=0 i<4; i++) {for (j=3;j>=0;j--) if (map[i][j)); if (j>=0) for (; j>=0;j--) if (!
   MAP[I][J]) return true;
  for (j=0;j<3;j++) if (Map[i][j]&&map[i][j]==map[i][j+1]) return true;
 } break;
   Case right://-ditto for (i=0 i<4; i++) {for (j=0;j<4;j++) if (map[i][j)); if (j<4) for (; j<4;j++) if (!
   MAP[I][J]) return true;
   for (j=0;j<3;j++) {if (map[i][j]&&map[i][j]==map[i][j+1]) return true;
 }} break;
Returns a result that cannot be executed after the allowed condition has been checked;
 Direction getnextdirection () {//The first byte must be 224, otherwise the input is not a function key if (Getch ()!=224) return unknow;
 According to the second byte corresponding to the user's operation switch (Getch ()) {case 72:return up;
 Case 80:return down;
 Case 75:return left;
 Case 77:return right;
 Default:return Unknow;
 } void Putnew () {//To facilitate operation, temporarily store all the free grid pointers, so that you can use a linear memory random access to any vacancy in the random access.
 Int* Boxes[16]={null}; For the purpose of temporary preservation.The address of the int* target;
 Statistics a total number of valid space int count=0;
 int i,j; Statistical Vacancy, find the vacancy that saves the address and accumulates the counter for (i=0;i<4;i++) for (j=0;j<4;j++) if (!
    Map[i][j]) {boxes[count]=&map[i][j];
   count++;
  if (count) {//If there is a vacancy, then the random assignment is performed on this one, which is the same for each probability Target=boxes[rand ()%count];
 50% may appear 2 50% may appear 4 *target=rand ()%2?2:4; }
}

Summarize

The above is the entire content of this article, small series Think like Tetris, 2048 of these slightly biased algorithm of the small game is a programmer must write several small programs. Hope this article for everyone's study or work can help, if there is doubt you can message exchange.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.