C#之控制台版本得贪吃蛇

news2024/10/6 14:32:34

贪吃蛇小时候大家都玩过,具体步骤如下:
1.给游戏制造一个有限得空间。
2.生成墙壁,小蛇碰撞到墙壁或者咬到自己的尾巴,游戏结束。
3.生成随机的食物。
4.吃掉食物,增加自身的体长,并生成新的食物。

具体代码如下:
定义一个小蛇类,该类包含吃东西,移动,检测碰撞等方法。

class Snake
{
    private List<Point> _body;
    private Direction _direction;
    private int _step = 1;
    private Point _tail;

    public Snake(Point tail, int length, Direction direction)
    {
        _direction = direction;
        _body = new List<Point>();
        for (int i = 0; i < length; i++)
        {
            Point p = new Point(tail.X, tail.Y, tail.Symbol);
            p.Move(i, _direction);
            _body.Add(p);
        }
        _tail = _body.First();
    }

    public void Move()
    {
        Point head = GetNextPoint();
        _body.Add(head);
        _tail.Clear();
        _tail = _body.First();
        _body.RemoveAt(0);
        head.Draw();
    }

    public bool Eat(Point food)
    {
        Point head = GetNextPoint();
        if (head.IsHit(food))
        {
            food.Symbol = head.Symbol;
            _body.Add(food);
            return true;
        }
        return false;
    }

    public void HandleKey(ConsoleKey key)
    {
        if (key == ConsoleKey.LeftArrow && _direction != Direction.Right)
        {
            _direction = Direction.Left;
        }
        else if (key == ConsoleKey.RightArrow && _direction != Direction.Left)
        {
            _direction = Direction.Right;
        }
        else if (key == ConsoleKey.UpArrow && _direction != Direction.Down)
        {
            _direction = Direction.Up;
        }
        else if (key == ConsoleKey.DownArrow && _direction != Direction.Up)
        {
            _direction = Direction.Down;
        }
    }

    public Point GetNextPoint()
    {
        Point head = _body.Last();
        Point nextPoint = new Point(head.X, head.Y, head.Symbol);
        nextPoint.Move(_step, _direction);
        return nextPoint;
    }

    public void Draw()
    {
        foreach (Point p in _body)
        {
            p.Draw();
        }
    }

    public bool IsHitTail()
    {
        Point head = _body.Last();
        for (int i = 0; i < _body.Count - 2; i++)
        {
            if (head.IsHit(_body[i]))
            {
                return true;
            }
        }
        return false;
    }
}

定义一个墙体类:

class Walls
{
    private List<Point> _wallList;

    public Walls(int mapWidth, int mapHeight)
    {
        _wallList = new List<Point>();

        DrawHorizontalLine(0);
        DrawHorizontalLine(mapHeight - 1);
        DrawVerticalLine(0);
        DrawVerticalLine(mapWidth - 1);
    }

    private void DrawHorizontalLine(int y)
    {
        for (int x = 0; x < Console.WindowWidth; x++)
        {
            Point p = new Point(x, y, '#');
            p.Draw();
            _wallList.Add(p);
        }
    }

    private void DrawVerticalLine(int x)
    {
        for (int y = 0; y < Console.WindowHeight; y++)
        {
            Point p = new Point(x, y, '#');
            p.Draw();
            _wallList.Add(p);
        }
    }

    public bool IsHit(Snake snake)
    {
        Point head = snake.GetNextPoint();
        return IsHit(head);
    }

    private bool IsHit(Point p)
    {
        return _wallList.Any(w => w.IsHit(p));
    }

    public void Draw()
    {
        foreach (Point p in _wallList)
        {
            p.Draw();
        }
    }
}

定义一个创建食物类:

class FoodCreator
{
    private readonly int _mapWidth;
    private readonly int _mapHeight;
    private readonly char _symbol;

    public FoodCreator(int mapWidth, int mapHeight, char symbol)
    {
        _mapWidth = mapWidth;
        _mapHeight = mapHeight;
        _symbol = symbol;
    }

    public Point CreateFood()
    {
        int x = new Random().Next(2, _mapWidth - 2);
        int y = new Random().Next(2, _mapHeight - 2);
        return new Point(x, y, _symbol);
    }
}

定义一个枚举,表示方向:

enum Direction
{
    Left,
    Right,
    Up,
    Down
}

定义一个坐标类应用重绘:

class Point
{
    public int X { get; set; }
    public int Y { get; set; }
    public char Symbol { get; set; }

    public Point(int x, int y, char symbol)
    {
        X = x;
        Y = y;
        Symbol = symbol;
    }

    public void Draw()
    {
        Console.SetCursorPosition(X, Y);
        Console.Write(Symbol);
    }

    public void Clear()
    {
        Symbol = ' ';
        Draw();
    }

    public void Move(int offset, Direction direction)
    {
        if (direction == Direction.Right)
        {
            X += offset;
        }
        else if (direction == Direction.Left)
        {
            X -= offset;
        }
        else if (direction == Direction.Up)
        {
            Y -= offset;
        }
        else if (direction == Direction.Down)
        {
            Y += offset;
        }
    }

    public bool IsHit(Point p)
    {
        return p.X == X && p.Y == Y;
    }
}

函数入口:



class Program
{
    static void Main()
    {
        Console.Title = "贪吃蛇游戏";
        Console.CursorVisible = false;
        Console.SetWindowSize(40, 20);
        Console.SetBufferSize(40, 20);

        Walls walls = new Walls(40, 20);
        walls.Draw();

        Snake snake = new Snake(new Point(6, 5, '*'),1,Direction.Down);
        snake.Draw();

        FoodCreator foodCreator = new FoodCreator(40, 20, '$');
        Point food = foodCreator.CreateFood();
        food.Draw();

        while (true)
        {
            if (walls.IsHit(snake) || snake.IsHitTail())
            {
                break;
            }

            if (snake.Eat(food))
            {
                food = foodCreator.CreateFood();
                food.Draw();
            }
            else
            {
                snake.Move();
            }

            System.Threading.Thread.Sleep(100);

            if (Console.KeyAvailable)
            {
                ConsoleKeyInfo key = Console.ReadKey();
                snake.HandleKey(key.Key);
            }
        }

        WriteGameOver();
        Console.ReadLine();
    }

    static void WriteGameOver()
    {
        int xOffset = 10;
        int yOffset = 8;
        Console.ForegroundColor = ConsoleColor.Red;
        Console.SetCursorPosition(xOffset, yOffset++);
        WriteText("========", xOffset, yOffset++);
        WriteText("GAME OVER", xOffset + 1, yOffset++);
        yOffset++;
        WriteText("========", xOffset, yOffset++);
    }

    static void WriteText(String text, int xOffset, int yOffset)
    {
        Console.SetCursorPosition(xOffset, yOffset);
        Console.WriteLine(text);
    }
}

运行效果图:
请添加图片描述
请添加图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/850684.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

一文解决JWT相同签名不匹配问题【JWT signature does not match locally computed signature.】

今天做项目的时候&#xff0c;涉及到一个支付记账的功能&#xff0c;想着不能将这些金额数据显示暴露的通过常规的请求体封装来进行传输&#xff0c;想着要是被中途抓包修改了不就麻烦了&#xff0c;所以考虑到这种安全性的需求&#xff0c;就利用上了JWT来进行数据的封装传递&…

IO学习-消息队列

1&#xff0c;要求用消息队列实现AB进程间的对话 a,A进程先发送一句话给B进程&#xff0c;B进程接收后打印。 b,B进程回复一句话给A进程&#xff0c;A进程接收后打印。 c,重复a,b步骤&#xff0c;当收到quit后要结束进程。 A进程 B进程 运行结果&#xff1a; 2&#xff0c;…

力扣 494. 目标和

题目来源&#xff1a;https://leetcode.cn/problems/target-sum/description/ C题解&#xff08;来源代码随想录&#xff09;&#xff1a;将该问题转为01背包问题。 假设加法的总和为x&#xff0c;那么减法对应的总和就是sum - x。所以我们要求的是 x - (sum - x) target。x …

学会RabbitMQ的延迟队列,提高消息处理效率

系列文章目录 手把手教你&#xff0c;本地RabbitMQ服务搭建&#xff08;windows&#xff09; 消息队列选型——为什么选择RabbitMQ RabbitMQ灵活运用&#xff0c;怎么理解五种消息模型 RabbitMQ 能保证消息可靠性吗 推或拉&#xff1f; RabbitMQ 消费模式该如何选择 死信是什么…

[CVPR-23-Highlight] Magic3D: High-Resolution Text-to-3D Content Creation

目录 Abstract Background: DreamFusion High-Resolution 3D Generation Coarse-to-fine Diffusion Priors Scene Models Coarse-to-fine Optimization NeRF optimization Mesh optimization Experiments Controllable 3D Generation Personalized text-to-3D Prom…

自动化实践-全量Json对比在技改需求提效实践

1 背景 随着自动化测试左移实践深入&#xff0c;越来越多不同类型的需求开始用自动化测试左移来实践&#xff0c;在实践的过程中也有了新的提效诉求&#xff0c;比如技改类的服务拆分项目或者BC流量拆分的项目&#xff0c;在实践过程中&#xff0c;这类需求会期望不同染色环境…

当前服务器版本不支持该功能,请联系经销商升级服务器 - - 达梦数据库报错

当前服务器版本不支持该功能&#xff0c;请联系经销商升级服务器 - - 达梦数据库报错 环境介绍1 搭建测试环境2 报错内容3 标准版介绍 环境介绍 某项目使用标准版数据库中&#xff0c;使用insert into 正常操作表&#xff0c;插入数据时报错&#xff0c;表为普通表。 1 搭建测…

【云原生•监控】基于Prometheus实现自定义指标弹性伸缩(HPA)

【云原生•监控】基于Prometheus实现自定义指标弹性伸缩(HPA) 什么是弹性伸缩 「Autoscaling即弹性伸缩&#xff0c;是Kubernetes中的一种非常核心的功能&#xff0c;它可以根据给定的指标&#xff08;例如 CPU 或内存&#xff09;自动缩放Pod副本&#xff0c;从而可以更好地管…

new function是什么?(小写function)

参考链接&#xff1a;https://juejin.cn/post/7006232342398238733

【SpringBoot笔记】定时任务(cron)

定时任务就是在固定的时间执行某个程序&#xff0c;闹钟的作用。 1.在启动类上添加注解 EnableScheduling 2.创建定时任务类 在这个类里面使用表达式设置什么时候执行 cron 表达式&#xff08;也叫七子表达式&#xff09;&#xff0c;设置执行规则 package com.Lijibai.s…

地震预警系统全平台开通攻略

大家好&#xff0c;我是熊哥。 最近地震频发&#xff0c;做为一个有社为责任感的人&#xff0c;我认为我有必要为大家总结这一份安全手册&#xff1b;做为一个小V有必要让更多的人看见&#xff0c;积德攒人品。希望大家平安健康。 效果 在地震来临前&#xff0c;手机、电视会…

每天一道leetcode:剑指 Offer 59 - II. 队列的最大值(中等)

今日份题目&#xff1a; 请定义一个队列并实现函数 max_value 得到队列里的最大值&#xff0c;要求函数max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。 若队列为空&#xff0c;pop_front 和 max_value 需要返回 -1 示例1 输入: ["MaxQueue",&qu…

centos7实现负载均衡

目录 一、基于 CentOS 7 构建 LVS-DR 集群。 1.1 配置lvs负载均衡服务 1.1.1 下载ipvsadm 1.1.2 增加vip 1.1.3 配置ipvsadm 1.2 配置rs1 1.2.1 编写测试页面 1.2.2 手工在RS端绑定VIP、添加路由 1.2.3 抑制arp响应 1.3 配置rs2 1.4 测试 二、配置nginx负载…

Springboot后端通过路径映射获取本机图片资源

项目场景&#xff1a; 项目中对图片的处理与查看是必不可少的&#xff0c;本文将讲解如何通过项目路径来获取到本机电脑的图片资源 如图所示&#xff0c;在我的本机D盘的图片测试文件夹(文件夹名字不要有中文)下有一些图片&#xff0c; 我们要在浏览器上访问到这些图片&#…

Flutter系列文章-实战项目

在本篇文章中&#xff0c;我们将通过一个实际的 Flutter 应用来综合运用最近学到的知识&#xff0c;包括保存到数据库、进行 HTTP 请求等。我们将开发一个简单的天气应用&#xff0c;可以根据用户输入的城市名获取该城市的天气信息&#xff0c;并将用户查询的城市列表保存到本地…

灵活利用ChatAI,减轻工作任务—语言/翻译篇

前言 ChatAI在语言和翻译方面具有重要作用。它能够帮助用户进行多语言交流、纠正错误、学习新语言、了解不同文化背景&#xff0c;并提供文本翻译与校对等功能。通过与ChatAI互动&#xff0c;我们能够更好地利用技术来拓展自己在语言领域的能力和知识&#xff0c;实现更加无障…

P11-Transformer学习1.1-《Attention Is All You Need》

Transformer目录:《Transformer Paper》1.0 CV Transformer必读论文5篇_汉卿HanQ的博客-CSDN博客 前文参考:Transformer1.0-预热_汉卿HanQ的博客-CSDN博客 全文1w3字左右&#xff0c;按照论文翻译个人理解精读&#xff0c;如果对你有所帮助&#xff0c;欢迎点个赞哦&#xff…

【C语言】初识C语言+进阶篇导读

✨个人主页&#xff1a; Anmia.&#x1f389;所属专栏&#xff1a; C Language &#x1f383;操作环境&#xff1a; Visual Studio 2019 版本 本篇目的是面向编程新手&#xff0c;没接触过编程的人。以及C进阶的导读。 内容是C语言重要知识点的简单解释&#xff0c;不做详解。给…

征稿 | 第三届粤港澳大湾区人工智能与大数据论坛(AIBDF 2023)

第三届粤港澳大湾区人工智能与大数据论坛&#xff08;AIBDF 2023&#xff09; 2023 3rd Guangdong-Hong Kong-Macao Greater Bay Area Artificial Intelligence And Big Data Forum 本次高端论坛围绕建设国家数字经济创新发展试验区进行选题。全面贯彻落实党的二十大精神&…

001-Spring boot 启动内置Web容器分析

目录 代码入口上下文容器 加载web容器 代码入口 上下文容器 SpringApplication.run(App.class); //追踪下去发现 context createApplicationContext();createApplicationContext()&#xff1a; return this.applicationContextFactory.create(this.webApplicationType);这里…