Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Java to realize the Snake Game

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

这篇文章主要介绍如何使用Java实现贪吃蛇游戏,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

具体内容如下

这是一个比较简洁的小游戏,主要有三个类,一个主类,一个食物类,一个贪吃蛇类。

1、首先定义主类,主类中主要用来创建窗口

public class Main { public static final int WIDTH=600; public static final int HEIGHT=600; public static void main(String[] args) { JFrame win =new JFrame(); win.setVisible(true); win.setSize(WIDTH, HEIGHT); win.setDefaultCloseOperation(3); win.setLocationRelativeTo(null); SnakePanel panle =new SnakePanel(); win.add(panle); SnakePanel.Key l = panle.new Key(); win.addKeyListener(l); panle.addKeyListener(l); panle.run(); }}

2、其次是定义食物类,食物有长和宽,还有在窗口中的位置

import java.util.Random;public class Cell { protected int x; protected int y; protected int width; protected int height; Random ran=new Random(); public Cell(){ Random ran=new Random(); this.x=ran.nextInt(25)*15+60; this.y=ran.nextInt(25)*15+50; this.width=15; this.height=15; } public Cell(int x,int y){ this(); this.x=x; this.y=y; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; }}

3、最后是蛇类

import java.awt.Color;import java.awt.Font;import java.awt.Graphics;import java.awt.event.KeyAdapter;import java.awt.event.KeyEvent;import java.util.Arrays;import java.util.Timer;import java.util.TimerTask;import javax.swing.JPanel;public class SnakePanel extends JPanel { final int RIGHT=1; final int LEFT=2; final int UP=3; final int DOWN=4; int moved=1; Cell food; Cell[] snake; public SnakePanel(){ food=new Cell(); snake=new Cell[5]; for(int i=0;i=40){ speed=15; } timer.schedule(task, 1000, speed); } public void step(){ for(int i=1;i510|| snake[snake.length-1].getX()500|| snake[snake.length-1].getY()

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report