安卓实现贪吃蛇游戏的全部代码
时间: 2023-10-29 22:15:59 浏览: 149
好的,以下是一个简单的安卓贪吃蛇游戏的全部代码:
1. activity_main.xml
```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/score_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score: 0"
android:textSize="24sp"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp" />
<FrameLayout
android:id="@+id/game_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/score_textview"
android:background="@android:color/darker_gray" />
<Button
android:id="@+id/start_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start"
android:layout_centerInParent="true" />
</RelativeLayout>
```
2. SnakeGameView.java
```java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class SnakeGameView extends SurfaceView implements Runnable {
private final int BLOCK_SIZE = 50;
private final int NUM_BLOCKS_WIDE = 10;
private final int NUM_BLOCKS_HIGH = 20;
private Thread gameThread = null;
private SurfaceHolder surfaceHolder;
private volatile boolean playing;
private boolean paused = true;
private Canvas canvas;
private Paint paint;
private long fps;
private int score;
private int highScore[] = new int[4];
private enum Direction {
UP, RIGHT, DOWN, LEFT
}
private Direction direction = Direction.RIGHT;
private int[] snakeXs;
private int[] snakeYs;
private int snakeLength;
private List<Point> apples = new ArrayList<>();
private int numApples;
public SnakeGameView(Context context) {
super(context);
surfaceHolder = getHolder();
paint = new Paint();
snakeXs = new int[200];
snakeYs = new int[200];
numApples = 0;
highScore[0] = 0;
highScore[1] = 0;
highScore[2] = 0;
highScore[3] = 0;
newGame();
}
@Override
public void run() {
while (playing) {
long frameStartTime = System.currentTimeMillis();
if (!paused) {
update();
draw();
}
long timeThisFrame = System.currentTimeMillis() - frameStartTime;
if (timeThisFrame > 0) {
fps = 1000 / timeThisFrame;
}
}
}
public void pause() {
playing = false;
try {
gameThread.join();
} catch (InterruptedException e) {
// Error
}
}
public void resume() {
playing = true;
gameThread = new Thread(this);
gameThread.start();
}
private void newGame() {
snakeLength = 1;
snakeXs[0] = NUM_BLOCKS_WIDE / 2;
snakeYs[0] = NUM_BLOCKS_HIGH / 2;
spawnApple();
score = 0;
}
private void spawnApple() {
Random random = new Random();
int appleX = random.nextInt(NUM_BLOCKS_WIDE - 1) + 1;
int appleY = random.nextInt(NUM_BLOCKS_HIGH - 1) + 1;
for (Point apple : apples) {
if (apple.x == appleX && apple.y == appleY) {
spawnApple();
}
}
apples.add(new Point(appleX, appleY));
numApples++;
}
private void eatApple(int appleIndex) {
snakeLength++;
apples.remove(appleIndex);
score += 10;
spawnApple();
}
private void moveSnake() {
for (int i = snakeLength; i > 0; i--) {
snakeXs[i] = snakeXs[i-1];
snakeYs[i] = snakeYs[i-1];
}
switch (direction) {
case UP:
snakeYs[0]--;
break;
case RIGHT:
snakeXs[0]++;
break;
case DOWN:
snakeYs[0]++;
break;
case LEFT:
snakeXs[0]--;
break;
}
}
private boolean detectDeath() {
boolean dead = false;
if (snakeXs[0] == -1 || snakeXs[0] >= NUM_BLOCKS_WIDE || snakeYs[0] == -1 || snakeYs[0] >= NUM_BLOCKS_HIGH) {
dead = true;
}
for (int i = snakeLength - 1; i > 0; i--) {
if (i > 4 && snakeXs[0] == snakeXs[i] && snakeYs[0] == snakeYs[i]) {
dead = true;
}
}
return dead;
}
private void update() {
if (snakeXs[0] == apples.get(0).x && snakeYs[0] == apples.get(0).y) {
eatApple(0);
}
moveSnake();
if (detectDeath()) {
newGame();
}
}
private void draw() {
if (surfaceHolder.getSurface().isValid()) {
canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK);
paint.setColor(Color.WHITE);
paint.setTextSize(40);
canvas.drawText("Score: " + score, 10, 50, paint);
for (Point apple : apples) {
paint.setColor(Color.RED);
canvas.drawRect(apple.x * BLOCK_SIZE,
apple.y * BLOCK_SIZE,
(apple.x + 1) * BLOCK_SIZE,
(apple.y + 1) * BLOCK_SIZE,
paint);
}
for (int i = 0; i < snakeLength; i++) {
if (i == 0) {
paint.setColor(Color.GREEN);
} else {
paint.setColor(Color.WHITE);
}
canvas.drawRect(snakeXs[i] * BLOCK_SIZE,
snakeYs[i] * BLOCK_SIZE,
(snakeXs[i] + 1) * BLOCK_SIZE,
(snakeYs[i] + 1) * BLOCK_SIZE,
paint);
}
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
public void pauseGame() {
paused = true;
}
public void startGame() {
paused = false;
}
public void moveRight() {
if (direction != Direction.LEFT) {
direction = Direction.RIGHT;
}
}
public void moveLeft() {
if (direction != Direction.RIGHT) {
direction = Direction.LEFT;
}
}
public void moveUp() {
if (direction != Direction.DOWN) {
direction = Direction.UP;
}
}
public void moveDown() {
if (direction != Direction.UP) {
direction = Direction.DOWN;
}
}
}
```
3. MainActivity.java
```java
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements View.OnTouchListener, View.OnClickListener {
private SnakeGameView snakeGameView;
private Button startButton;
private final int MOVE_RIGHT = 0;
private final int MOVE_LEFT = 1;
private final int MOVE_UP = 2;
private final int MOVE_DOWN = 3;
private Handler handler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MOVE_RIGHT:
snakeGameView.moveRight();
break;
case MOVE_LEFT:
snakeGameView.moveLeft();
break;
case MOVE_UP:
snakeGameView.moveUp();
break;
case MOVE_DOWN:
snakeGameView.moveDown();
break;
}
return true;
}
});
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
snakeGameView = findViewById(R.id.game_frame);
snakeGameView.setOnTouchListener(this);
startButton = findViewById(R.id.start_button);
startButton.setOnClickListener(this);
}
@Override
protected void onResume() {
super.onResume();
snakeGameView.resume();
}
@Override
protected void onPause() {
super.onPause();
snakeGameView.pause();
}
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
if (motionEvent.getX() >= snakeGameView.getWidth() * 3 / 4) {
handler.sendEmptyMessage(MOVE_RIGHT);
} else if (motionEvent.getX() <= snakeGameView.getWidth() / 4) {
handler.sendEmptyMessage(MOVE_LEFT);
} else if (motionEvent.getY() <= snakeGameView.getHeight() / 4) {
handler.sendEmptyMessage(MOVE_UP);
} else if (motionEvent.getY() >= snakeGameView.getHeight() * 3 / 4) {
handler.sendEmptyMessage(MOVE_DOWN);
}
break;
}
return true;
}
@Override
public void onClick(View view) {
if (view.getId() == R.id.start_button) {
startButton.setVisibility(View.INVISIBLE);
snakeGameView.startGame();
}
}
}
```
这些代码实现了一个简单的安卓贪吃蛇游戏,并且可以通过触摸屏幕或者按钮控制贪吃蛇的移动方向。当贪吃蛇触碰到边界或自身时,游戏会重新开始,并记录最高分数。
阅读全文