java se自己练手没看教程写的贪吃蛇还加点趣味玩法(算24点)

java se自己练手没看教程写的贪吃蛇还加点趣味玩法(算24点)

提示:这里可以添加系列文章的所有文章的目录,目录需要自己手动添加
例如:第一章 Python 机器学习入门之pandas的使用


提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档


一、准备工作:

准备工作
①素材准备
②JDK8.0
③IntelliJ IDEA

二、编程想法

1.把蛇的身体分成三个部分

首先蛇由圆形构成,新建一个数组存放该圆形的横纵坐标X和Y,再设置一个数组存放蛇身体也就该圆形的内部值。

代码如下(示例):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings('ignore')
import  ssl
ssl._create_default_https_context = ssl._create_unverified_context

2.地图随机生成四个圆形数字,生成的数字不能在蛇的身体内部;

代码如下(示例):

public class Foot {
    protected int X;
    protected int Y;

    public Foot() {
        GluttonousSnake gluttonousSnake = new GluttonousSnake();
        Random random = new Random();
        int randomOneX=0;
        int randomOneY=0;
        boolean flag =false;
        while(!flag){
            randomOneX = random.nextInt(26);
            randomOneY = random.nextInt(24);
            a:for (int i=0;i<24;i++){
                if (gluttonousSnake.snakeY[i]!=gluttonousSnake.LEFTTOLOW + gluttonousSnake.DEFAULTBIG *randomOneY){
                    for (int j =0;j<26;j++) {
                        if (gluttonousSnake.snakeX[j] != gluttonousSnake.UPTOLOW + gluttonousSnake.DEFAULTBIG *randomOneX) {
                            flag = true;
                            X = gluttonousSnake.LEFTTOLOW + gluttonousSnake.DEFAULTBIG* randomOneX;
                            Y = gluttonousSnake.UPTOLOW + gluttonousSnake.DEFAULTBIG* randomOneY;
                            break  a;
                        }
                    }
                }
            }
        }
    }
}

3.蛇移动

①:重新改变数组【0】的值来更换绘制四个方向头的图片
代码如下(示例):

public void moveLeft() {
        if (snakeBody[0].equals(bodys[16]) || snakeBody[0].equals(bodys[17])) {
            snakeBody[0] = bodys[14];
            turn();
        }
    }

②:每tab*100毫秒蛇的XY数组坐标移动一个默认值DEFAULTBIG
代码如下(示例):

public void turn() {
        if (snakeBody[0].equals(bodys[14])) {
            for (int i = length - 1; i >= 0; i--) {
                if (i == 0) {
                    snakeX[i] = snakeX[i] - DEFAULTBIG;
                } else {
                    snakeX[i] = snakeX[i - 1];
                    snakeY[i] = snakeY[i - 1];
                }
            }
        } else if (snakeBody[0].equals(bodys[15])) {
            for (int i = length - 1; i >= 0; i--) {
                if (i == 0) {
                    snakeX[i] = snakeX[i] + DEFAULTBIG;
                } else {
                    snakeX[i] = snakeX[i - 1];
                    snakeY[i] = snakeY[i - 1];
                }
            }
        } else if (snakeBody[0].equals(bodys[16])) {
            for (int i = length - 1; i >= 0; i--) {
                if (i == 0) {
                    snakeY[i] = snakeY[i] - DEFAULTBIG;
                } else {
                    snakeX[i] = snakeX[i - 1];
                    snakeY[i] = snakeY[i - 1];
                }
            }
        } else if (snakeBody[0].equals(bodys[17])) {
            for (int i = length - 1; i >= 0; i--) {
                if (i == 0) {
                    snakeY[i] = snakeY[i] + DEFAULTBIG;
                } else {
                    snakeX[i] = snakeX[i - 1];
                    snakeY[i] = snakeY[i - 1];
                }
            }
        }
    }

写两种游戏结束的可能1:出界 2:撞到一起
代码如下(示例):

    public boolean isBorder() {
        if (snakeX[0] <LEFTTOLOW || snakeX[0] > LEFTTOLOW+650+50 || snakeY[0] < UPTOLOW|| snakeY[0] > UPTOLOW +575+50) {
            return true;
        }
        return false;
    }

代码如下(示例):

    public boolean isGameOver(){
        for (int i=1;i<length;i++){
            if (snakeY[0]==snakeY[i]&&snakeX[0]==snakeX[i]){
                    return true;
            }
        }
        return false;
    }

代码如下(示例):
在start()方法中添加无限循环移动

while (true) {
            if (game_state == PLAYING) {
                int tab = speedDiffcuty[game_diffcuty];
                try {
                    Thread.sleep(100 * tab);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (!isBorder()&&!isGameOver()) {
                    eat();
                    turn();
                }else{
                    game_state =GAMEOVER;
                    if (max<totalScore){
                        max=totalScore;
                        writeMax();
                    }
                }
            }
            repaint();
        }

4.蛇吃食物,计算24点

蛇吃食物就是当蛇头XY坐标和食物一致时将食物值归零,获取食物的值后添加的蛇身体最后;
再设置每次计算最后六个白色圆形数字的值,如果和为24即可消除。

public void eat() {
        for (int x = 0; x < 4; x++) {
            if (xs[x] == snakeX[0] && ys[x] == snakeY[0]) {
                length++;
                snakeX[length - 1] = xs[x];
                snakeY[length - 1] = ys[x];
                sums[length - 1] = randoms[x]+1;
                snakeBody[length - 1] = bodys[randoms[x]];
                xs[x] = 0;
                ys[x] = 0;
                totalScore++;
            }
        }
        System.out.println(length);
        int sum = 0;
        if (length > 7) {
            for (int i = length-1; i > length - 7; i--) {
                if (i>0){
                    if (sums[i]==0){
                        return;
                    }
                    sum += sums[i];
                    if (sum == 24) {
                        length=i+1;
                        for (int j = i; j < length; j++){
                            snakeX[j]=0;
                            snakeY[j]=0;
                            sums[j]=0;
                            snakeBody[j]=null;
                            sum=0;
                            System.out.println("2"+length);
                            snakeX[length - 1] = 0;
                            snakeY[length - 1] = 0;
                            sums[length - 1] = 0;
                            snakeBody[length - 1] = bodys[9];
                            totalScore+=24;
                        }
                    }
                }
            }
        }else{
            for (int i = length-1; i > 1; i--) {
                if (sums[i]==0){
                    return;
                }
                sum += sums[i];
                if (sum == 24) {
                    length=i+1;
                    for (int j = i; j < length; j++){
                        snakeX[j]=0;
                        snakeY[j]=0;
                        snakeBody[j]=null;
                        sum=0;
                        System.out.println("2"+length);
                        snakeX[length - 1] = 0;
                        snakeY[length - 1] = 0;
                        sums[length - 1] = 0;
                        snakeBody[length - 1] = bodys[9];
                        totalScore+=24;
                    }
                }
            }
        }
    }

5.记录就是DataInputStream和 DataOutputStream的读写

    public void writeMax(){
       DataOutputStream dos= null;
        try {
            dos = new DataOutputStream(new FileOutputStream(Thread.currentThread().getContextClassLoader().getResource("Max").getPath()));
            dos.writeInt(max);
            dos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                dos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void readMax(){
        DataInputStream dis = null;
        try {
            dis = new DataInputStream(new FileInputStream(Thread.currentThread().getContextClassLoader().getResource("Max").getPath()));
            max=dis.readInt();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                dis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

效果如图

在这里插入图片描述
吃一个24:
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个简单的贪吃蛇游戏JAVA代码,可以在控制台中玩: ```java import java.util.Random; import java.util.Scanner; public class SnakeGame { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Random random = new Random(); int width = 20; // 游戏界面宽度 int height = 20; // 游戏界面高度 int[][] map = new int[width][height]; // 地图,0表示空格,1表示食物,2表示蛇身 int score = 0; // 得分 int direction = 0; // 方向:0表示往上,1表示往右,2表示往下,3表示往左 int[] head = {width / 2, height / 2}; // 蛇头初始位置 int[][] body = {head}; // 蛇身初始位置 map[head[0]][head[1]] = 2; // 在地图上标记蛇头 while (true) { // 游戏循环 // 在地图上随机生成食物 while (true) { int x = random.nextInt(width); int y = random.nextInt(height); if (map[x][y] == 0) { map[x][y] = 1; break; } } // 打印地图和得分 System.out.print("Score: " + score + "\n"); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (i == head[0] && j == head[1]) { System.out.print("O"); } else if (map[i][j] == 1) { System.out.print("*"); } else if (map[i][j] == 2) { System.out.print("#"); } else { System.out.print(" "); } } System.out.print("\n"); } // 获取用户输入的方向 System.out.print("Enter direction (w/a/s/d): "); String input = scanner.nextLine(); if (input.equals("w")) { direction = 0; } else if (input.equals("d")) { direction = 1; } else if (input.equals("s")) { direction = 2; } else if (input.equals("a")) { direction = 3; } // 移动蛇头 switch (direction) { case 0: head[0]--; break; case 1: head[1]++; break; case 2: head[0]++; break; case 3: head[1]--; break; } // 如果蛇头撞到边界或自己的身体,游戏结束 if (head[0] < 0 || head[0] >= width || head[1] < 0 || head[1] >= height || map[head[0]][head[1]] == 2) { System.out.print("Game over!\n"); break; } // 如果蛇头吃到食物,得分1,并将食物从地图上移除 if (map[head[0]][head[1]] == 1) { score++; map[head[0]][head[1]] = 2; } // 将蛇头入蛇身数组最前面 body = addToArray(body, head); // 如果蛇身长度超过得分,删除蛇身数组最后面的元素 if (body.length > score) { body = removeFromArray(body, body.length - 1); } // 根据蛇身数组更新地图 map = new int[width][height]; for (int i = 0; i < body.length; i++) { map[body[i][0]][body[i][1]] = 2; } } } // 将元素添到数组最前面 public static int[][] addToArray(int[][] array, int[] element) { int[][] newArray = new int[array.length + 1][2]; newArray[0] = element; for (int i = 0; i < array.length; i++) { newArray[i + 1] = array[i]; } return newArray; } // 删除数组中指定位置的元素 public static int[][] removeFromArray(int[][] array, int index) { int[][] newArray = new int[array.length - 1][2]; for (int i = 0; i < index; i++) { newArray[i] = array[i]; } for (int i = index + 1; i < array.length; i++) { newArray[i - 1] = array[i]; } return newArray; } } ``` 使用方法: 1. 将以上代码复制到Java编译器中。 2. 编译并运行代码,控制台会出现游戏界面和提示。 3. 根据提示输入方向,使蛇头移动。 4. 如果蛇头吃到食物,得分1,并在地图上随机生成新的食物。 5. 如果蛇头撞到边界或自己的身体,游戏结束。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值