C#console version of the greedy snake

Source: Internet
Author: User

This time in the work of C # wrote a simple greedy program, the general is WinForm form, this time to get a console version, because C # console is all input output stream, to do this in the cmd window to do this has the foreground UI interface program should not be suitable, But remember the previous DOS version of the system, I think it should be able to do, so it took a few nights to get such a thing, the first screenshot:

The interface is relatively simple, a CMD window, the other is composed of various shapes of characters, do this console of the greedy snake has the following several places to note:

1. Understand console this thing, it is a standard I/O input output stream;

2. The console has 2 terms: Screen buffer and console window, we generally get the size of the console size rather than buffer size, this can look at MSDN;

3. There are a few questions about the greedy snake itself: how to let the snake move. How to judge a snake to eat food. How to tell if a snake touches a border. Wait a minute, let's talk about it in detail.

First of all, I would like to say that no matter what the program or software, design data structure is very important, the design of the database is good, the problem becomes simple, really so.

According to object-oriented requirements, design snake class, because the console program is all in the form of characters, so the painting snake must be a bit, dot composition line, first design point class is as follows:

1.point.cs

Using System;
Using System.Collections.Generic;
Using System.Linq;

Using System.Text; namespace Snake {///<summary>///class Point///</summary> public class Point:icomparabl
        e<point> {private int x = 0;
            <summary>///Gets or sets the x///</summary> public int x {
            get {return x;}
        set {x = value;}
        private int y = 0;
            <summary>///Gets or sets the y///</summary> public int y {
            get {return y;}
        set {y = value;} }///<summary>///Compare The two point///</summary>///<param name= "O Ther ">other point</param>///<returns>-1 if x < other. X && y < other. Y, 0 if x = = other. X && y = other. Y, otherwise 1</returns> public int CompareTo (poinT other} {if (x < other). X && y < other.
            Y) {return-1; else if (x = = other. X && y = other.
            Y) {return 0;
            else {return 1;
 }
        }
    }
}


Here it is necessary to say that this point inherits the IComparable interface, for the following comparison and to determine whether the snake touches other objects or itself, so that you can design the Snake.cs class below.

2.snake.cs

using System using System.Collections.Generic; using System.Linq; using System.Text;
        namespace Snake {///<summary>///class Snake///</summary> public class Snake {
        Private point head = NULL;
        <summary>///Gets or sets the snake ' s head///</summary> public Point head
            {get {return head;}
        set {head = value;}
        Private point[] BODY = null;
        <summary>///Gets or sets the snake ' s body///</summary> public point[] Body
            {get {return body;}
        set {BODY = value;}
        Private point tail = null;
        <summary>///Gets or sets the snake ' s tail///</summary> public point tail
            {get {return tail;}
        set {tail = value;} }
    }
}


Why should there be a snake head, a snake body and a snake tail? In simple terms, according to the object-oriented words you will think, complex to see the logic of the code processing, here is not much to say, their own experience. Next comes the food class Food.cs.

3.food.cs

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;

Namespace Snake
{
    ///<summary>
    ///class Food
    ///</summary> public
    class Food
    {
        private point position = null;
        <summary>
        ///Gets or sets the food ' s position
        ///</summary> public point
        position
        {Get
            {return position;}
            set {position = value;}}}


Food is just one point in a position that's enough, no other attributes. This basic data structure is constructed, and the rest is how to link these structures to construct the logic of the game, first of all, enter the game, must be the key to control the movement of the snake, the console has such a judge keyboard input methods and attributes, as follows:

Consolekey key = Console.readkey (true). Key;
Consolekey This class has attributes that are judged by which key is pressed on the keyboard, which can be seen on MSDN. Consolekey this is done and then to see how to draw the game interface, this is not too complex, the console class has such a method is as follows:
Console.setcursorposition (i, j);

Sets the location where the cursor is located, this can be written to the character again, and without this method, we need to repaint the entire interface every time the snake moves, which can cause a problem: the console window screen will always flash, because we are drawing the entire console, with this method, We just need to refresh the local area on it, like the snake moving we just need to update the position of the snake. Finally, how do you deal with snakes when they touch food and borders? When the snake touches the food, then we can take food as the current snake head, before the snake head as the first node of the body of the snake, so that the length of the snake body 1, the snake tail or the original snake tail, when the snake head hit the border game on the end. Also, when the snake moves without touching the food or the border, the snake's head becomes the point at which the snake is currently moving, and the first point of the snake's body becomes the point of the previous snake's head, and so on, and so on, the snake moves in a position as before. Well, probably so much, and finally the interface, the code is as follows:
      
        <summary>///Draw Console UI///</summary> private void Drawconso
            Leui () {console.clear ();

            Point temppoint = null;
            Console.setcursorposition (0, 0);
            Console.WriteLine ("Name:" + name);
            Console.setcursorposition (0, 1);
            Console.WriteLine ("Score:" + Score);
            Console.setcursorposition (0, 2);
            Console.WriteLine ("Press R-restart game after you losed the game, press E to exit game");
                for (int i = 0; i < uiwidth i + + 2) {console.setcursorposition (I, 3);
            Console.Write (".");
                for (int i = 2; i < Uiheight. i++) {for (int j = 0; J < Uiwidth; J +)
                    {temppoint = new point ();
                    Temppoint.x = j;

                    Temppoint.y = i; if (temppoint.CompareTo (currentfood.position) = = 0) {console.setcursorposition (J, I);
                    Console.Write (Getfoodelement ());
                        else if (Temppoint.compareto (currentsnake.head) = = 0) {
                        Console.setcursorposition (J, I);
                    Console.Write (Getheadelement ());
                        else if (Issnakebodycoverpoint (Currentsnake.body, temppoint)) {
                        Console.setcursorposition (J, I);
                    Console.Write (Getbodyelement ());
                        else if (Temppoint.compareto (currentsnake.tail) = = 0) {
                        Console.setcursorposition (J, I);
                    Console.Write (Gettailelement ()); }
                }
            }
        }


Some of these methods see the name to know what meaning, this implementation is relatively simple, here is not code ...

SOURCE download

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.