Java实现的Android贪吃蛇小游戏代码示例

ChatGPT4o 使用 ChatGPT 4o 回答

问题:

贪吃蛇小游戏app用Javaeclipse开发Androidapp,之前的代码有很多报错而且语句不通,只需要实现移动、撞墙死亡、吃食物增长并且计分的功能即可,给出MainActivity和layout的代码

回答:

好的,下面是一个简单的贪吃蛇小游戏的实现代码,包括MainActivitylayout文件。这个示例代码实现了蛇的移动、撞墙死亡、吃食物增长以及计分功能。

MainActivity.java

package com.example.snakegame;

import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private SnakeView snakeView;
    private TextView scoreTextView;
    private Handler handler = new Handler();
    private Runnable gameRunnable;
    private int score = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        snakeView = findViewById(R.id.snakeView);
        scoreTextView = findViewById(R.id.scoreTextView);

        gameRunnable = new Runnable() {
            @Override
            public void run() {
                if (snakeView.update()) {
                    score++;
                    scoreTextView.setText("Score: " + score);
                    handler.postDelayed(this, 500);
                } else {
                    // Game over
                    scoreTextView.setText("Game Over! Final Score: " + score);
                }
            }
        };

        snakeView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        snakeView.changeDirection(event.getX(), event.getY());
                        break;
                }
                return true;
            }
        });

        startGame();
    }

    private void startGame() {
        score = 0;
        scoreTextView.setText("Score: " + score);
        snakeView.initGame();
        handler.post(gameRunnable);
    }
}

SnakeView.java

package com.example.snakegame;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class SnakeView extends View {

    private List<Point> snake;
    private Point food;
    private int direction;
    private int width, height, unitSize;
    private Paint paint;
    private Random random;

    public SnakeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        paint = new Paint();
        random = new Random();
        unitSize = 50;
        initGame();
    }

    public void initGame() {
        snake = new ArrayList<>();
        snake.add(new Point(5, 5));
        direction = 0;
        generateFood();
    }

    private void generateFood() {
        int x = random.nextInt(width / unitSize);
        int y = random.nextInt(height / unitSize);
        food = new Point(x, y);
    }

    public void changeDirection(float x, float y) {
        if (x > getWidth() / 2) {
            direction = (direction + 1) % 4;
        } else {
            direction = (direction + 3) % 4;
        }
    }

    public boolean update() {
        Point head = snake.get(0);
        Point newHead = new Point(head.x, head.y);

        switch (direction) {
            case 0: newHead.y -= 1; break;
            case 1: newHead.x += 1; break;
            case 2: newHead.y += 1; break;
            case 3: newHead.x -= 1; break;
        }

        if (newHead.x < 0 || newHead.x >= width / unitSize || newHead.y < 0 || newHead.y >= height / unitSize) {
            return false; // Game over
        }

        for (Point p : snake) {
            if (p.equals(newHead)) {
                return false; // Game over
            }
        }

        snake.add(0, newHead);

        if (newHead.equals(food)) {
            generateFood();
        } else {
            snake.remove(snake.size() - 1);
        }

        invalidate();
        return true;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        width = w;
        height = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        paint.setColor(Color.GREEN);
        for (Point p : snake) {
            canvas.drawRect(p.x * unitSize, p.y * unitSize, (p.x + 1) * unitSize, (p.y + 1) * unitSize, paint);
        }

        paint.setColor(Color.RED);
        canvas.drawRect(food.x * unitSize, food.y * unitSize, (food.x + 1) * unitSize, (food.y + 1) * unitSize, paint);
    }

    private static class Point {
        int x, y;

        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) return true;
            if (obj == null || getClass() != obj.getClass()) return false;
            Point point = (Point) obj;
            return x == point.x && y == point.y;
        }
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/scoreTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Score: 0"
        android:textSize="24sp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="16dp"/>

    <com.example.snakegame.SnakeView
        android:id="@+id/snakeView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/scoreTextView"
        android:layout_marginTop="16dp"/>

</RelativeLayout>

这个示例代码实现了一个基���的贪吃蛇游戏。蛇可以移动,吃到食物后会增长,撞墙或撞到自己会导致游戏结束。你可以根据需要进一步扩展和优化这个代码。