C# 控制台 完整游戏循环机制 贪吃蛇Demo

6 篇文章 0 订阅
2 篇文章 0 订阅
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp6
{
    class Program
    {

        public static Game m_game;
        public static ConsoleKeyInfo Input_Key = new ConsoleKeyInfo();
        public static bool Is_Input_Key_Down = false;
        static void Main(string[] args)
        {
            m_game = new Game();
            m_game.Game_Init();
            string oldstr_panel = "";
            var lastTime = DateTime.Now;
            double deltaTime = 0;
            while (true)
            {
                deltaTime = (DateTime.Now - lastTime).TotalMilliseconds / 1000;
                lastTime = DateTime.Now;

                //非阻塞读取键盘输入
                if (Console.KeyAvailable)
                {
                    Input_Key = Console.ReadKey(true);
                    Is_Input_Key_Down = true;
                }
                else
                {
                    Is_Input_Key_Down = false;
                }
                //游戏循环
                m_game.Game_Update(deltaTime);

                //画面渲染
                string str_panel = m_game.Game_Draw();
                if (str_panel != oldstr_panel)
                {
                    oldstr_panel = str_panel;
                    Console.Clear();
                    Console.Write(oldstr_panel);
                }
            }
        }
    }

    public class Point
    {
        public int x;
        public int y;
    }
    //游戏逻辑类
    public class Game
    {
        public Point[] player_points; //蛇的全身身体
        public int player_score = 0;  //蛇的分数 
        public int player_flag = 1;  //1 上 2 下 3 左 4 右

        public int map_width = 0;
        public int map_height = 0;

        public Point apple_point ;

        private double player_move_timer = 0;
        private string[][] map_chars;
        private Random rnd = new Random();

        //游戏初始化
        public void Game_Init()
        {
            map_height = 10;
            map_width = 10;
            map_chars = new string[map_height][];
            for(int i = 0; i < map_height; i++)
            {
                map_chars[i] = new string[map_width];
            }

            player_points = new Point[map_height * map_width];
            player_points[0] = new Point() { x = 0, y = 0 };
            apple_point = new Point() { x = 0, y = 0 };
        }

        //游戏渲染
        public string Game_Draw()
        {
            Map_Draw();
            Player_Draw();
            Apple_Draw();

            string str_map = "";
            int i = 0;
            for (int y = 0; y < map_height; y++)
            {
                for(int x= 0; x< map_width; x++)
                {
                    str_map += map_chars[y][x];
                }
                str_map += "\n";
            }

            return str_map;
        }

        private void Apple_Draw()
        {
            Set_Map(apple_point.x, apple_point.y, "○");
        }

        public void Game_Update(double deltaTime)
        {
            player_move_timer += deltaTime;
            if(player_move_timer >= 0.2)
            {
                player_move_timer = 0;
                Player_Movement();
            }

            if (Program.Is_Input_Key_Down)
            {
                switch (Program.Input_Key.KeyChar)
                {
                    case 'w':player_flag = 1; break;
                    case 's':player_flag = 2; break;
                    case 'a':player_flag = 3; break;
                    case 'd':player_flag = 4; break;
                } 
            }
        }

        public void Player_Movement()
        {
            for (int i = player_points.Length - 1; i > 0; i--)
            {
                if (player_points[i] != null)
                {
                    player_points[i].x = player_points[i - 1].x;
                    player_points[i].y = player_points[i - 1].y;
                }
            }
            switch (player_flag)
            {
                case 1: player_points[0].y--; break;
                case 2: player_points[0].y++; break;
                case 3: player_points[0].x--; break;
                case 4: player_points[0].x++; break;
            }
            if (player_points[0].x == apple_point.x && player_points[0].y == apple_point.y)
            {
                Player_Eat_Apple();
            }
        }

        public void Player_Eat_Apple()
        {
            player_score++;
            for (int i = 0; i < player_points.Length; i++)
            {
                if (player_points[i] == null)
                {
                    player_points[i] = new Point()
                    {
                        x = player_points[i - 1].x,
                        y = player_points[i - 1].y
                    };
                    break;
                }
            }
            Random_Apple_Point();
        }

        public void Random_Apple_Point()
        {
            List<Point> points = new List<Point>();
            for(int y = 0; y < map_height; y++)
            {
                for(int x = 0; x < map_width; x++)
                {
                    if(map_chars[y][x]!= "■")
                    {
                        points.Add(new Point { x = x, y = y });
                    }
                }
            }
            apple_point =  points[rnd.Next(points.Count)];
        }

        private void Map_Draw()
        {
            for(int y = 0; y < map_height; y++)
            {
                for(int x = 0; x < map_width; x++)
                {
                    Set_Map(x, y, "..");
                }
            }

        }

        private void Player_Draw()
        {
            for (int i = 0; i < player_points.Length; i++)
            {
                if (player_points[i] != null)
                {
                    Set_Map(player_points[i].x, player_points[i].y, "■");
                }
            }
        }

        public void Set_Map(int x,int y,string info)
        {
            if (x < 0 || x >= map_width || y < 0 || y >= map_height) return;
             map_chars[y][x] = info;
        }
    }
}

 

  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是基于C#控制台应用的贪吃蛇游戏的代码实现。 ```csharp using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleSnake { class Program { static void Main(string[] args) { Console.CursorVisible = false; //隐藏光标 Console.SetWindowSize(60, 30); //设置窗口大小 Console.SetBufferSize(60, 30); //设置缓冲区大小 //画边框 for (int i = 0; i < 60; i++) { Console.SetCursorPosition(i, 0); Console.Write("#"); Console.SetCursorPosition(i, 29); Console.Write("#"); } for (int i = 0; i < 30; i++) { Console.SetCursorPosition(0, i); Console.Write("#"); Console.SetCursorPosition(59, i); Console.Write("#"); } //初始化蛇 List<Point> snake = new List<Point>(); snake.Add(new Point(30, 15)); snake.Add(new Point(29, 15)); snake.Add(new Point(28, 15)); snake.Add(new Point(27, 15)); snake.Add(new Point(26, 15)); //初始化食物 Point food = new Point(RandomNumber(1, 58), RandomNumber(1, 28)); Console.SetCursorPosition(food.x, food.y); Console.Write("*"); //初始化方向 Direction direction = Direction.Right; //初始化分数 int score = 0; while (true) { //获取键盘输入 if (Console.KeyAvailable) { ConsoleKeyInfo key = Console.ReadKey(true); switch (key.Key) { case ConsoleKey.UpArrow: if (direction != Direction.Down) direction = Direction.Up; break; case ConsoleKey.DownArrow: if (direction != Direction.Up) direction = Direction.Down; break; case ConsoleKey.LeftArrow: if (direction != Direction.Right) direction = Direction.Left; break; case ConsoleKey.RightArrow: if (direction != Direction.Left) direction = Direction.Right; break; } } //移动蛇 Point head = snake[0]; Point newHead = new Point(head.x, head.y); switch (direction) { case Direction.Up: newHead.y--; break; case Direction.Down: newHead.y++; break; case Direction.Left: newHead.x--; break; case Direction.Right: newHead.x++; break; } snake.Insert(0, newHead); Console.SetCursorPosition(newHead.x, newHead.y); Console.Write("@"); if (newHead.x == food.x && newHead.y == food.y) //吃到食物 { food = new Point(RandomNumber(1, 58), RandomNumber(1, 28)); Console.SetCursorPosition(food.x, food.y); Console.Write("*"); score += 10; } else //没有吃到食物 { Point tail = snake[snake.Count - 1]; Console.SetCursorPosition(tail.x, tail.y); Console.Write(" "); snake.RemoveAt(snake.Count - 1); } //判断是否撞到边框或自己 if (newHead.x == 0 || newHead.x == 59 || newHead.y == 0 || newHead.y == 29) break; for (int i = 1; i < snake.Count; i++) { if (newHead.x == snake[i].x && newHead.y == snake[i].y) { Console.SetCursorPosition(0, 31); Console.Write("Game Over! Your score is: " + score); return; } } //延迟一段时间 System.Threading.Thread.Sleep(100); } } static int RandomNumber(int min, int max) //生成指定范围内的随机数 { Random random = new Random(); return random.Next(min, max + 1); } } enum Direction //方向枚举 { Up, Down, Left, Right } class Point //坐标类 { public int x; public int y; public Point(int x, int y) { this.x = x; this.y = y; } } } ``` 希望这个代码对你有帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值