Android 教你完成最简单的贪吃蛇示例

本文将指导你如何在Android平台上构建一个简单的贪吃蛇游戏。通过手指点击操作,处理屏幕点击事件,测量屏幕尺寸,绘制游戏元素,生成并更新蛇与食物的位置,以及处理游戏结束条件。核心代码涉及蛇集合的动态更新,线程运行以不断改变蛇头位置,实现游戏循环。
摘要由CSDN通过智能技术生成

Android 教你完成最简单的贪吃蛇示例

先来看下实际效果图

在这里插入图片描述

先来初始化下

    init {
   
        biankuangPaint = Paint()
        biankuangPaint!!.strokeWidth = 1f
        biankuangPaint!!.color = context?.let {
    ContextCompat.getColor(it, R.color.w66) }!!
        foodPaint = Paint()
        foodPaint!!.color = ContextCompat.getColor(context, R.color.colorAccent)
        snackPaint = Paint()
        snackPaint!!.color = ContextCompat.getColor(context, R.color.snake_color)
        val bitmap = BitmapFactory.decodeResource(resources, R.mipmap.snake1)
        snakeHead = ImageUtils.resizeBitmap(bitmap, foodWidth - 2 * wcharJaine, foodWidth - 2 * wcharJaine)
        val bitmap2 = BitmapFactory.decodeResource(resources, R.mipmap.mushroom)
        val mushroom = ImageUtils.resizeBitmap(bitmap2, foodWidth - 2 * wcharJaine, foodWidth - 2 * wcharJaine)
        val bitmap3 = BitmapFactory.decodeResource(resources, R.mipmap.qingwa)
        val quinta = ImageUtils.resizeBitmap(bitmap3, foodWidth - 2 * wcharJaine, foodWidth - 2 * wcharJaine)
        val bitmap4 = BitmapFactory.decodeResource(resources, R.mipmap.mouse)
        val mouse = ImageUtils.resizeBitmap(bitmap4, foodWidth - 2 * wcharJaine, foodWidth - 2 * wcharJaine)
        foodBitmapArray[0] = mushroom
        foodBitmapArray[1] = quinta
        foodBitmapArray[2] = mouse
        currentFoodBitmap = foodBitmapArray[0]
        for (i in currentXIndex downTo 1) {
   
            pjPoints?.add(PjPoint(i, 1))
        }
    }

由于贪吃蛇是用手指点击操作的,所以要对屏幕点击做处理(判断当前手指距离蛇头点击是横向多点还是纵向多点)

   override fun onTouchEvent(event: MotionEvent): Boolean {
   
        val action = event.action
        if (action == MotionEvent.ACTION_DOWN) {
   
            val pressX = event.x.toInt()
            val pressY = event.y.toInt<
  • 5
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值