2048 console version (C #)

Source: Internet
Author: User

Opening

2048 the game is very popular now, and many people should have already played it. In the blog Park, I also saw a simulated version of the GDI + 2048 game. For now, I am not doing so many animations. After all, it is a little stuff. Here I will present a "console version 2048".

Download the program source code: http://pan.baidu.com/s/1mg8zntu

The program structure is relatively simple, with a total of more than 200 lines of code and few comments. You can probably understand it. Here I will explain the meaning of each method in the program:
The Main method program entry, RePaint is similar to the refreshing interface in Win32 program, SquareRot90 rectangular matrix rotates 90 degrees clockwise (the parameter can be negative, indicating a counter-clockwise ). Merge moves to the left, merges the elements with the same values in the cell, and sorts them out (place all elements to the left). RandomPoint randomly generates points from the null position of the matrix (value: 0) A random vertex is generated. If no null position exists, null is returned. CanMove is also a method to determine whether the game can continue to move. IsEquals checks whether the values of the two matrices are the same. CopyToB copies the matrix.
The flowchart is as follows: Code onMain Function
static void Main(string[] args){    int[,] a = new int[4, 4];    a[1, 2] = 2;    a[2, 2] = 2;    a[2, 1] = 2;    RePaint(a);    while (true)    {        ConsoleKeyInfo key = Console.ReadKey();        switch (key.Key)        {            case ConsoleKey.UpArrow:                a = SquareRot90(a, 3);                a = Merge(a);                a = SquareRot90(a, -3);                break;            case ConsoleKey.DownArrow:                a = SquareRot90(a, 1);                a = Merge(a);                a = SquareRot90(a, -1);                break;            case ConsoleKey.LeftArrow:                a = Merge(a);                break;            case ConsoleKey.RightArrow:                a = SquareRot90(a, 2);                a = Merge(a);                a = SquareRot90(a, -2);                break;        }        Point cp = RandomPoint(a);        if (cp != null)        {            a[cp.X, cp.Y] = 2;            RePaint(a);        }        if (cp == null && !CanMove(a))        {            RePaint(a, "Game Over");        }    }}

  

Matrix Rotation Method
/// Rotate the rectangle 90 ° clockwise /// </summary> /// <param name = "rotNum"> Number of rotations </param> public static int [,] squareRot90 (int [,] a, int rotNum) {while (rotNum <0) {rotNum + = 4 ;}for (int rot_ I = 0; rot_ I <rotNum; rot_ I ++) {int [,] B = new int [. getLength (1),. getLength (0)]; for (int I = 0; I <. getLength (0); I ++) {for (int j = 0; j <. getLength (1); j ++) {B [j,. getLength (0)-I-1] = a [I, j] ;}} a = B;} return ;}

  

Random Point Method
public static Point RandomPoint(int[,] a){    List<Point> lstP = new List<Point>();    for (int i = 0; i < a.GetLength(0); i++)    {        for (int j = 0; j < a.GetLength(1); j++)        {            if (a[i, j] == 0)            {                lstP.Add(new Point(i, j));            }        }    }    if (lstP.Count == 0)    {        return null;    }    int rnd = new Random().Next(lstP.Count);    return lstP[rnd];}

  

Left-side Matrix Synthesis Method
Public static int [,] Merge (int [,] a) {for (int I = 0; I <. getLength (0); I ++) {int lastNum = 0; int last_j = 0; for (int j = 0; j <. getLength (1); j ++) // merge {if (lastNum! = A [I, j] & a [I, j]! = 0) {lastNum = a [I, j]; last_j = j;} else if (lastNum = a [I, j]) {a [I, last_j] = 0; a [I, j] = lastNum + a [I, j] ;}} last_j = 0; for (int j = 0; j <. getLength (1); j ++) // sort {if (a [I, j]! = 0) {a [I, last_j] = a [I, j]; if (last_j! = J) a [I, j] = 0; last_j ++; }}return ;}

  

Can I continue to move the CanMove method?
public static bool CanMove(int[,] a){    bool res = false;    int[,] b = CopyToB(a);    b = Merge(b);    if (!IsEquals(a, b))        res = true;    b = CopyToB(a);    b = SquareRot90(b, 1);    b = Merge(b);    b = SquareRot90(b, -1);    if (!IsEquals(a, b))        res = true;    b = CopyToB(a);    b = SquareRot90(b, 2);    b = Merge(b);    b = SquareRot90(b, -2);    if (!IsEquals(a, b))        res = true;    b = CopyToB(a);    b = SquareRot90(b, 3);    b = Merge(b);    b = SquareRot90(b, -3);    if (!IsEquals(a, b))        res = true;    return res;}

  

The IsEquals Method Used in CanMove to determine that the matrix is equal
public static bool IsEquals(int[,] a, int[,] b){    bool res = true;    for (int i = 0; i < a.GetLength(0); i++)    {        for (int j = 0; j < a.GetLength(1); j++)        {            if (b[i, j] != a[i, j])            {                res = false;                break;            }        }        if (!res)            break;    }    return res;}

  

CopyToB, matrix replication method used in CanMove
public static int[,] CopyToB(int[,] a){    int[,] b = new int[a.GetLength(0), a.GetLength(1)];    for (int i = 0; i < a.GetLength(0); i++)    {        for (int j = 0; j < a.GetLength(1); j++)        {            b[i, j] = a[i, j];        }    }    return b;}

  

Two RePain methods, re-print, the previous expression GameOver
public static void RePaint(int[,] a, string s){    while (true)    {        Console.Clear();        RePaint(a);        Console.WriteLine("\n\n\n\n\t\t" + s + "\n\n");        Console.ReadKey();    }}public static void RePaint(int[,] a){    Console.Clear();    for (int j = 0; j < a.GetLength(1); j++)    {        Console.Write("───");    }    Console.Write("\n");    for (int i = 0; i < a.GetLength(0); i++)    {        Console.Write("│");        for (int j = 0; j < a.GetLength(1); j++)        {            string s = "";            if (a[i, j] == 0)                s = "   ";            else if (a[i, j] < 10)                s = " " + a[i, j] + " ";            else if (a[i, j] < 100)                s = "" + a[i, j] + " ";            else                s = "" + a[i, j];            Console.Write(s + "│");        }        Console.Write("\n");        for (int j = 0; j < a.GetLength(1); j++)        {            Console.Write("───");        }        Console.Write("\n");    }}

  

Auxiliary Class Point
class Point{    public Point(int x, int y)    {        this.X = x;        this.Y = y;    }    public int X    {        get;        set;    }    public int Y    {        get;        set;    }}

  

ConclusionIn fact, writing a game is not as easy as you think. To solve problems such as algorithms, you must carefully design it in advance and use a piece of paper as a design drawing, which will greatly improve the work efficiency. I posted the game "defending radish" in the game before, but it was not sorted out due to time delay. After the completion of the game, I must sort it out and share it with you. Now the function is basically done, here first paste a reduced version of the game program, link: http://pan.baidu.com/s/1sjvxO7N. What are the program's problems and bugs? I hope you can leave a message. After the source code is compiled, upload it again. In a few days, there will be a blue bridge cup competition. Haha, I'm coming from Beijing. Download the program source code: http://pan.baidu.com/s/1mg8zntu

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.