Android 教你完成最简单的贪吃蛇示例
先来看下实际效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8d0d1aad5f4910f916e5500e99f4bb12.gif)
先来初始化下
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<