java贪吃蛇代码_java实现贪吃蛇游戏代码(附完整源码)

先给大家分享源码,喜欢的朋友点此处下载。

游戏界面

750833eb3dfe41d3d739326b8281766d.png

6c49897446fd3c9c7bcd9f2a899d3d92.png

GUI界面

java实现贪吃蛇游戏需要创建一个桌面窗口出来,此时就需要使用java中的swing控件

创建一个新窗口

JFrame frame = new JFrame("贪吃蛇游戏");

//设置大小

frame.setBounds(10, 10, 900, 720);

向窗口中添加控件

可以直接用add方法往窗口中添加控件

这里我创建GamePanel类继承自Panel,最后使用add方法添加GamePanel

加载图片

图片加载之后可以添加到窗口上

public static URL bodyUrl = GetImage.class.getResource("/picture/body.png");

public static ImageIcon body = new ImageIcon(bodyUrl);

逻辑实现

//每次刷新页面需要进行的操作

@Override

public void actionPerformed(ActionEvent e) {

//当游戏处于开始状态且游戏没有失败时

if(gameStart && !isFail) {

//蛇头所在的位置就是下一次蛇身体的位置

bodyX[++bodyIndexRight] = headX;

bodyY[bodyIndexRight] = headY;

//bodyIndexLeft++;

//长度到达数组的尾部

if(bodyIndexRight==480) {

for(int i=bodyIndexLeft, j=0; i<=bodyIndexRight; i++,j++) {

bodyX[j]=bodyX[i];

bodyY[j]=bodyY[i];

}

bodyIndexLeft=0;

bodyIndexRight=length-1;

}

//更新头部位置

if(fdirection==1) {

//头部方向为上,将蛇头向上移动一个单位

headY-=25;

}

else if(fdirection==2) {

//头部方向为下,将蛇头向下移动一个单位

headY+=25;

}

else if(fdirection==3) {

//头部方向为左,将蛇头向左移动一个单位

headX-=25;

}

else if(fdirection==4) {

//头部方向为右,将蛇头向右移动一个单位

headX+=25;

}

//当X坐标与Y坐标到达极限的时候,从另一端出来

if(headX<25)

headX = 850;

if(headX>850)

headX = 25;

if(headY<75)

headY = 650;

if(headY>650)

headY = 75;

//当头部坐标和食物坐标重合时

if(headX==foodX && headY==foodY){

length++;

score+=10;

//重新生成食物,判断食物坐标和蛇身坐标是否重合,效率较慢

while(true) {

foodX = 25 + 25* random.nextInt(34);

foodY = 75 + 25* random.nextInt(24);

//判断食物是否和头部身体重合

boolean isRepeat = false;

//和头部重合

if(foodX == headX && foodY == headY)

isRepeat = true;

//和身体重合

for(int i=bodyIndexLeft; i<=bodyIndexRight; i++) {

if(foodX == bodyX[i] && foodY == bodyY[i]){

isRepeat = true;

}

}

//当不重复的时候,食物生成成功,跳出循环

if(isRepeat==false)

break;

}

}

else bodyIndexLeft++;

//判断头部是否和身体重合

for(int i=bodyIndexLeft; i<=bodyIndexRight;i++) {

if(headX==bodyX[i] && headY==bodyY[i]){

//游戏失败

isFail = true;

break;

}

}

repaint();

}

timer.start();

}

键盘监听

实现KeyListener接口,重写KeyPressed方法,在其中写当键盘按下时所对应的操作。

//键盘监听事件

@Override

public void keyPressed(KeyEvent e) {

int keyCode = e.getKeyCode(); //获取按下的键盘

if (keyCode==KeyEvent.VK_SPACE){ //如果是空格

if (isFail){ //如果游戏失败,从头再来!

isFail = false;

init(); //重新初始化

}else { //否则,如果游戏中,暂停游戏,如果暂停游戏,开始游戏

gameStart = !gameStart;

}

repaint();

}

if (keyCode==KeyEvent.VK_LEFT){

//左

//不能掉头,当当前头的方向和要转的方向不相反时才能调转方向

if(fdirection!=4) {

fdirection = 3;

}

}else if (keyCode==KeyEvent.VK_RIGHT){

//左

if(fdirection!=3)

fdirection = 4;

}else if (keyCode==KeyEvent.VK_UP){

//上

if(fdirection!=2)

fdirection = 1;

}else if (keyCode==KeyEvent.VK_DOWN){

//下

if(fdirection!=1)

fdirection = 2;

}

}

到此这篇关于java实现贪吃蛇游戏代码的文章就介绍到这了,更多相关java实现贪吃蛇游戏内容请搜索云海天教程以前的文章或继续浏览下面的相关文章希望大家以后多多支持云海天教程!

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的Java双人贪吃蛇游戏代码示例: ```java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SnakeGame extends JFrame { private final int B_WIDTH = 300; private final int B_HEIGHT = 300; private final int DOT_SIZE = 10; private final int ALL_DOTS = 900; private final int RAND_POS = 29; private int DELAY = 140; private final int x[] = new int[ALL_DOTS]; private final int y[] = new int[ALL_DOTS]; private int dots; private int apple_x; private int apple_y; private boolean leftDirection = false; private boolean rightDirection = true; private boolean upDirection = false; private boolean downDirection = false; private boolean inGame = true; private Timer timer; private Image ball; private Image apple; private Image head; private int player1Score = 0; private int player2Score = 0; private boolean player1Turn = true; public SnakeGame() { initGame(); } private void initGame() { addKeyListener(new TAdapter()); setBackground(Color.black); setFocusable(true); setPreferredSize(new Dimension(B_WIDTH, B_HEIGHT)); loadImages(); initGameBoard(); } private void loadImages() { ImageIcon iid = new ImageIcon("dot.png"); ball = iid.getImage(); ImageIcon iia = new ImageIcon("apple.png"); apple = iia.getImage(); ImageIcon iih = new ImageIcon("head.png"); head = iih.getImage(); } private void initGameBoard() { dots = 3; for (int z = 0; z < dots; z++) { x[z] = 50 - z * 10; y[z] = 50; } locateApple(); timer = new Timer(DELAY, new GameCycle()); timer.start(); } @Override public void paintComponent(Graphics g) { super.paintComponent(g); doDrawing(g); } private void doDrawing(Graphics g) { if (inGame) { g.drawImage(apple, apple_x, apple_y, this); for (int z = 0; z < dots; z++) { if (z == 0) { g.drawImage(head, x[z], y[z], this); } else { g.drawImage(ball, x[z], y[z], this); } } Toolkit.getDefaultToolkit().sync(); } else { gameOver(g); } } private void gameOver(Graphics g) { String msg = "Game Over!"; String msg2 = "Player 1 Score: " + player1Score + " Player 2 Score: " + player2Score; Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = getFontMetrics(small); g.setColor(Color.white); g.setFont(small); g.drawString(msg, (B_WIDTH - metr.stringWidth(msg)) / 2, B_HEIGHT / 2); g.drawString(msg2, (B_WIDTH - metr.stringWidth(msg2)) / 2, (B_HEIGHT / 2) + 20); } private void checkApple() { if ((x[0] == apple_x) && (y[0] == apple_y)) { dots++; locateApple(); if (player1Turn) { player1Score++; } else { player2Score++; } } } private void move() { for (int z = dots; z > 0; z--) { x[z] = x[(z - 1)]; y[z] = y[(z - 1)]; } if (leftDirection) { x[0] -= DOT_SIZE; } if (rightDirection) { x[0] += DOT_SIZE; } if (upDirection) { y[0] -= DOT_SIZE; } if (downDirection) { y[0] += DOT_SIZE; } } private void checkCollision() { for (int z = dots; z > 0; z--) { if ((z > 4) && (x[0] == x[z]) && (y[0] == y[z])) { inGame = false; } } if (y[0] >= B_HEIGHT) { inGame = false; } if (y[0] < 0) { inGame = false; } if (x[0] >= B_WIDTH) { inGame = false; } if (x[0] < 0) { inGame = false; } if(!inGame) { timer.stop(); } } private void locateApple() { int r = (int) (Math.random() * RAND_POS); apple_x = ((r * DOT_SIZE)); r = (int) (Math.random() * RAND_POS); apple_y = ((r * DOT_SIZE)); } private class TAdapter extends KeyAdapter { @Override public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_LEFT && !rightDirection) { leftDirection = true; upDirection = false; downDirection = false; } if (key == KeyEvent.VK_RIGHT && !leftDirection) { rightDirection = true; upDirection = false; downDirection = false; } if (key == KeyEvent.VK_UP && !downDirection) { upDirection = true; rightDirection = false; leftDirection = false; } if (key == KeyEvent.VK_DOWN && !upDirection) { downDirection = true; rightDirection = false; leftDirection = false; } } } private class GameCycle implements ActionListener { @Override public void actionPerformed(ActionEvent e) { if (inGame) { checkApple(); checkCollision(); move(); if (player1Turn) { player1Turn = false; } else { player1Turn = true; } } repaint(); } } public static void main(String[] args) { EventQueue.invokeLater(() -> { JFrame ex = new SnakeGame(); ex.setVisible(true); }); } } ``` 这个示例代码使用了Java Swing库来创建游戏窗口和图形界面,同时实现了基本的游戏逻辑和双人模式。你可以根据自己的需求对代码进行修改和扩展。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值