java贪吃蛇小游戏实验目的_基于Java的贪吃蛇小游戏

import java.awt.Color;

import java.awt.Graphics;

import java.awt.event.KeyEvent;

import java.awt.event.KeyListener;

import java.util.Random;

import javax.swing.JFrame;

import javax.swing.JOptionPane;

public class Snack extends JFrame {

int arr[][]=new int[20][20];

boolean isStart=true;

int headx=8;

int heady=8;

int tailx=6;

int taily=8;

int direction=0;//蛇头方向

int up=1,down=2,left=3,right=4;//移动方向

int foodx=0;

int foody=0;

int tail=0;//蛇尾方向

public Snack(){

setSize(500,500);

setTitle("贪吃蛇");

setVisible(true);//显示窗口

setLayout(null);

setResizable(false);//禁止改变窗体大小

setLocationRelativeTo(null);//居中显示

setDefaultCloseOperation(EXIT_ON_CLOSE);//设置默认关闭按钮

direction=right;//设置默认移动方向

for(int i=6;i<8;i++){

arr[i][heady]=right;

}

makeFood();//获取食物

addKeyListener(new KeyListener() {

public void keyTyped(KeyEvent e) {}

public void keyReleased(KeyEvent e) {}

public void keyPressed(KeyEvent e) {

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

if(isStart){

switch(keyCode){

case KeyEvent.VK_UP:

if(direction != down){

direction=up;

}

break;

case KeyEvent.VK_DOWN:

if(direction != up){

direction=down;

}

break;

case KeyEvent.VK_LEFT:

if(direction != right){

direction=left;

}

break;

case KeyEvent.VK_RIGHT:

if(direction != left){

direction=right;

}

break;

}

}

}

});

while(isStart){

arr[headx][heady]=direction;

switch(direction){

case 1:

heady--;

break;

case 2:

heady++;

break;

case 3:

headx--;

break;

case 4:

headx++;

break;

}

if(headx>19 || headx<0 || heady>19 || heady<0 || arr[headx][heady] != 0){

isStart=false;

break;

}

arr[headx][heady]=direction;

try{

Thread.sleep(500);

}catch(Exception e){

}

if(headx==foodx && heady==foody){

makeFood();

}else{

tail=arr[tailx][taily];

arr[tailx][taily]=0;

switch(tail){

case 1:

taily--;

break;

case 2:

taily++;

break;

case 3:

tailx--;

break;

case 4:

tailx++;

break;

}

}

repaint();

}

if(!isStart){

JOptionPane.showMessageDialog(null, "Game Over !");

}

}

public void makeFood(){

Random ran=new Random();

foodx=ran.nextInt(19)+1;

foody=ran.nextInt(19)+1;

if(arr[foodx][foody] != 0){

makeFood();

}

}

public void paint(Graphics g){//绘制图形

g.setColor(Color.LIGHT_GRAY);

g.fill3DRect(0, 0,500,500,true);

g.setColor(Color.BLUE);//设置颜色为蓝色

for(int i=0;i<20;i++){

for(int j=0;j<20;j++){

if(arr[i][j] != 0){

g.fillRect(i*25,j*25, 24, 24);

}

}

}

g.setColor(Color.RED);

g.fillRect(foodx*25, foody*25, 24,24);

}

public static void main(String[] args) {

Snack s=new Snack();

}

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的 Java 贪吃蛇小游戏的示例代码: ```java import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SnakeGame extends JFrame implements KeyListener { private static final long serialVersionUID = 1L; private final int WIDTH = 300; private final int 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 int x[] = new int[ALL_DOTS]; private 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; public SnakeGame() { addKeyListener(this); setTitle("Snake Game"); setBackground(Color.black); setResizable(false); setSize(WIDTH, HEIGHT); ImageIcon iid = new ImageIcon(getClass().getResource("dot.png")); ball = iid.getImage(); ImageIcon iia = new ImageIcon(getClass().getResource("apple.png")); apple = iia.getImage(); ImageIcon iih = new ImageIcon(getClass().getResource("head.png")); head = iih.getImage(); initGame(); } public void initGame() { 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(); } public void paint(Graphics g) { super.paint(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); } } public void gameOver(Graphics g) { String msg = "Game Over"; Font small = new Font("Helvetica", Font.BOLD, 14); FontMetrics metr = getFontMetrics(small); g.setColor(Color.white); g.setFont(small); g.drawString(msg, (WIDTH - metr.stringWidth(msg)) / 2, HEIGHT / 2); } public void checkApple() { if ((x[0] == apple_x) && (y[0] == apple_y)) { dots++; locateApple(); } } public 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; } } public 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] >= HEIGHT) { inGame = false; } if (y[0] < 0) { inGame = false; } if (x[0] >= WIDTH) { inGame = false; } if (x[0] < 0) { inGame = false; } if (!inGame) { timer.stop(); } } public 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)); } public void keyReleased(KeyEvent e) { } 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; } } public void keyTyped(KeyEvent e) { } class GameCycle implements ActionListener { public void actionPerformed(ActionEvent e) { if (inGame) { checkApple(); checkCollision(); move(); } repaint(); } } public static void main(String[] args) { new SnakeGame().setVisible(true); } } ``` 在代码中,`initGame()` 方法初始化游戏,`paint(Graphics g)` 方法绘制游戏界面,`checkApple()` 方法检查是否吃到了苹果,`move()` 方法移动贪吃蛇,`checkCollision()` 方法检查是否发生碰撞,`locateApple()` 方法随机生成苹果的位置,`keyPressed(KeyEvent e)` 方法处理键盘事件。运行代码后,即可开始玩贪吃蛇小游戏

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值