java小游戏代码详细注释(java语言小游戏代码)
admin 发布:2022-12-19 22:51 146
今天给各位分享java小游戏代码详细注释的知识,其中也会对java语言小游戏代码进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!
本文目录一览:
- 1、JAVA小游戏程序代码
- 2、求java小游戏源代码
- 3、急求这个十分简单的JAVA小代码详细注释!!
- 4、求一个简单又有趣的JAVA小游戏代码
- 5、高分求高手补全一个java小游戏,内详
- 6、java贪吃蛇代码注释求解
JAVA小游戏程序代码
这个是比较有名的那个烟花,不知道你有没有用:
建个工程,以Fireworks为类即可
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import javax.swing.*;
public class Fireworks extends Applet implements MouseListener,Runnable
{
int x,y;
int top,point;
/**
*对小程序进行变量和颜色的初始化。
*/
public void init()
{
x = 0;
y = 0;
//设置背景色为黑色
setBackground(Color.black);
addMouseListener(this);
}
public void paint(Graphics g)
{
}
/**
*使该程序可以作为应用程序运行。
*/
public static void main(String args[]) {
Fireworks applet = new Fireworks();
JFrame frame = new JFrame("TextAreaNew");
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
System.exit(0);
}
});
frame.getContentPane().add(
applet, BorderLayout.CENTER);
frame.setSize(800,400);
applet.init();
applet.start();
frame.setVisible(true);
}
/**
*程序主线程,对一个烟花进行绘制。
*/
public void run()
{
//变量初始化
Graphics g1;
g1 = getGraphics();
int y_move,y_click,x_click;
int v;
x_click = x;
y_click = y;
y_move = 400;
v = 3;
int r,g,b;
while(y_move y_click)
{
g1.setColor(Color.black);
g1.fillOval(x_click,y_move,5,5);
y_move -= 5;
r = (((int)Math.round(Math.random()*4321))%200)+55;
g = (((int)Math.round(Math.random()*4321))%200)+55;
b = (((int)Math.round(Math.random()*4321))%200)+55;
g1.setColor(new Color(r,g,b));
g1.fillOval(x_click,y_move,5,5);
for(int j = 0 ;j=10;j++)
{
if(r55) r -= 20;
if(g55) g -= 20;
if(b55) b -=20;
g1.setColor(new Color(r,g,b));
g1.fillOval(x_click,y_move+j*5,5,5);
}
g1.setColor(Color.black);
g1.fillOval(x_click,y_move+5*10,5,5);
try
{
Thread.currentThread().sleep(v++);
} catch (InterruptedException e) {}
}
for(int j=12;j=0;j--)
{
g1.setColor(Color.black);
g1.fillOval(x_click,y_move+(j*5),5,5);
try
{
Thread.currentThread().sleep((v++)/3);
} catch (InterruptedException e) {}
}
y_move = 400;
g1.setColor(Color.black);
while(y_move y_click)
{
g1.fillOval(x_click-2,y_move,9,5);
y_move -= 5;
}
v = 15;
for(int i=0;i=25;i++)
{
r = (((int)Math.round(Math.random()*4321))%200)+55;
g = (((int)Math.round(Math.random()*4321))%200)+55;
b = (((int)Math.round(Math.random()*4321))%200)+55;
g1.setColor(new Color(r,g,b));
g1.drawOval(x_click-3*i,y_click-3*i,6*i,6*i);
if(i23)
{
g1.drawOval(x_click-3*(i+1),y_click-3*(i+1),6*(i+1),6*(i+1));
g1.drawOval(x_click-3*(i+2),y_click-3*(i+2),6*(i+2),6*(i+2));
}
try
{
Thread.currentThread().sleep(v++);
} catch (InterruptedException e) {}
g1.setColor(Color.black);
g1.drawOval(x_click-3*i,y_click-3*i,6*i,6*i);
}
}
/**
*对鼠标事件进行监听。
*临听其鼠标按下事件。
*当按下鼠标时,产生一个新线程。
*/
public void mousePressed(MouseEvent e)
{
x = e.getX();
y = e.getY();
Thread one;
one = new Thread(this);
one.start();
one = null;
}
/**
*实现MouseListener接中的方法。为一个空方法。
*/
public void mouseReleased(MouseEvent e)
{
}
/**
*实现MouseListener接中的方法。为一个空方法。
*/
public void mouseEntered(MouseEvent e)
{
}
/**
*实现MouseListener接中的方法。为一个空方法。
*/
public void mouseExited(MouseEvent e)
{
}
/**
*实现MouseListener接中的方法。为一个空方法。
*/
public void mouseClicked(MouseEvent e)
{
}
}
求java小游戏源代码
表1. CheckerDrag.java
// CheckerDrag.javaimport java.awt.*;import java.awt.event.*;public class CheckerDrag extends java.applet.Applet{ // Dimension of checkerboard square. // 棋盘上每个小方格的尺寸 final static int SQUAREDIM = 40; // Dimension of checkerboard -- includes black outline. // 棋盘的尺寸 – 包括黑色的轮廓线 final static int BOARDDIM = 8 * SQUAREDIM + 2; // Dimension of checker -- 3/4 the dimension of a square. // 棋子的尺寸 – 方格尺寸的3/4 final static int CHECKERDIM = 3 * SQUAREDIM / 4; // Square colors are dark green or white. // 方格的颜色为深绿色或者白色 final static Color darkGreen = new Color (0, 128, 0); // Dragging flag -- set to true when user presses mouse button over checker // and cleared to false when user releases mouse button. // 拖动标记 --当用户在棋子上按下鼠标按键时设为true, // 释放鼠标按键时设为false boolean inDrag = false; // Left coordinate of checkerboard's upper-left corner. // 棋盘左上角的左方向坐标 int boardx; // Top coordinate of checkerboard's upper-left corner. //棋盘左上角的上方向坐标 int boardy; // Left coordinate of checker rectangle origin (upper-left corner). // 棋子矩形原点(左上角)的左方向坐标 int ox; // Top coordinate of checker rectangle origin (upper-left corner). // 棋子矩形原点(左上角)的上方向坐标 int oy; // Left displacement between mouse coordinates at time of press and checker // rectangle origin. // 在按键时的鼠标坐标与棋子矩形原点之间的左方向位移 int relx; // Top displacement between mouse coordinates at time of press and checker // rectangle origin. // 在按键时的鼠标坐标与棋子矩形原点之间的上方向位移 int rely; // Width of applet drawing area. // applet绘图区域的宽度 int width; // Height of applet drawing area. // applet绘图区域的高度 int height; // Image buffer. // 图像缓冲 Image imBuffer; // Graphics context associated with image buffer. // 图像缓冲相关联的图形背景 Graphics imG; public void init () { // Obtain the size of the applet's drawing area. // 获取applet绘图区域的尺寸 width = getSize ().width; height = getSize ().height; // Create image buffer. // 创建图像缓冲 imBuffer = createImage (width, height); // Retrieve graphics context associated with image buffer. // 取出图像缓冲相关联的图形背景 imG = imBuffer.getGraphics (); // Initialize checkerboard's origin, so that board is centered. // 初始化棋盘的原点,使棋盘在屏幕上居中 boardx = (width - BOARDDIM) / 2 + 1; boardy = (height - BOARDDIM) / 2 + 1; // Initialize checker's rectangle's starting origin so that checker is // centered in the square located in the top row and second column from // the left. // 初始化棋子矩形的起始原点,使得棋子在第一行左数第二列的方格里居中 ox = boardx + SQUAREDIM + (SQUAREDIM - CHECKERDIM) / 2 + 1; oy = boardy + (SQUAREDIM - CHECKERDIM) / 2 + 1; // Attach a mouse listener to the applet. That listener listens for // mouse-button press and mouse-button release events. // 向applet添加一个用来监听鼠标按键的按下和释放事件的鼠标监听器 addMouseListener (new MouseAdapter () { public void mousePressed (MouseEvent e) { // Obtain mouse coordinates at time of press. // 获取按键时的鼠标坐标 int x = e.getX (); int y = e.getY (); // If mouse is over draggable checker at time // of press (i.e., contains (x, y) returns // true), save distance between current mouse // coordinates and draggable checker origin // (which will always be positive) and set drag // flag to true (to indicate drag in progress). // 在按键时如果鼠标位于可拖动的棋子上方 // (也就是contains (x, y)返回true),则保存当前 // 鼠标坐标与棋子的原点之间的距离(始终为正值)并且 // 将拖动标志设为true(用来表明正处在拖动过程中) if (contains (x, y)) { relx = x - ox; rely = y - oy; inDrag = true; } } boolean contains (int x, int y) { // Calculate center of draggable checker. // 计算棋子的中心位置 int cox = ox + CHECKERDIM / 2; int coy = oy + CHECKERDIM / 2; // Return true if (x, y) locates with bounds // of draggable checker. CHECKERDIM / 2 is the // radius. // 如果(x, y)仍处于棋子范围内则返回true // CHECKERDIM / 2为半径 return (cox - x) * (cox - x) + (coy - y) * (coy - y) CHECKERDIM / 2 * CHECKERDIM / 2; } public void mouseReleased (MouseEvent e) { // When mouse is released, clear inDrag (to // indicate no drag in progress) if inDrag is // already set. // 当鼠标按键被释放时,如果inDrag已经为true, // 则将其置为false(用来表明不在拖动过程中) if (inDrag) inDrag = false; } }); // Attach a mouse motion listener to the applet. That listener listens // for mouse drag events. //向applet添加一个用来监听鼠标拖动事件的鼠标运动监听器 addMouseMotionListener (new MouseMotionAdapter () { public void mouseDragged (MouseEvent e) { if (inDrag) { // Calculate draggable checker's new // origin (the upper-left corner of // the checker rectangle). // 计算棋子新的原点(棋子矩形的左上角) int tmpox = e.getX () - relx; int tmpoy = e.getY () - rely; // If the checker is not being moved // (at least partly) off board, // assign the previously calculated // origin (tmpox, tmpoy) as the // permanent origin (ox, oy), and // redraw the display area (with the // draggable checker at the new // coordinates). // 如果棋子(至少是棋子的一部分)没有被 // 移出棋盘,则将之前计算的原点 // (tmpox, tmpoy)赋值给永久性的原点(ox, oy), // 并且刷新显示区域(此时的棋子已经位于新坐标上) if (tmpox boardx tmpoy boardy tmpox + CHECKERDIM boardx + BOARDDIM tmpoy + CHECKERDIM boardy + BOARDDIM) { ox = tmpox; oy = tmpoy; repaint (); } } } }); } public void paint (Graphics g) { // Paint the checkerboard over which the checker will be dragged. // 在棋子将要被拖动的位置上绘制棋盘 paintCheckerBoard (imG, boardx, boardy); // Paint the checker that will be dragged. // 绘制即将被拖动的棋子 paintChecker (imG, ox, oy); // Draw contents of image buffer. // 绘制图像缓冲的内容 g.drawImage (imBuffer, 0, 0, this); } void paintChecker (Graphics g, int x, int y) { // Set checker shadow color. // 设置棋子阴影的颜色 g.setColor (Color.black); // Paint checker shadow. // 绘制棋子的阴影 g.fillOval (x, y, CHECKERDIM, CHECKERDIM); // Set checker color. // 设置棋子颜色 g.setColor (Color.red); // Paint checker. // 绘制棋子 g.fillOval (x, y, CHECKERDIM - CHECKERDIM / 13, CHECKERDIM - CHECKERDIM / 13); } void paintCheckerBoard (Graphics g, int x, int y) { // Paint checkerboard outline. // 绘制棋盘轮廓线 g.setColor (Color.black); g.drawRect (x, y, 8 * SQUAREDIM + 1, 8 * SQUAREDIM + 1); // Paint checkerboard. // 绘制棋盘 for (int row = 0; row 8; row++) { g.setColor (((row 1) != 0) ? darkGreen : Color.white); for (int col = 0; col 8; col++) { g.fillRect (x + 1 + col * SQUAREDIM, y + 1 + row * SQUAREDIM, SQUAREDIM, SQUAREDIM); g.setColor ((g.getColor () == darkGreen) ? Color.white : darkGreen); } } } // The AWT invokes the update() method in response to the repaint() method // calls that are made as a checker is dragged. The default implementation // of this method, which is inherited from the Container class, clears the // applet's drawing area to the background color prior to calling paint(). // This clearing followed by drawing causes flicker. CheckerDrag overrides // update() to prevent the background from being cleared, which eliminates // the flicker. // AWT调用了update()方法来响应拖动棋子时所调用的repaint()方法。该方法从 // Container类继承的默认实现会在调用paint()之前,将applet的绘图区域清除 // 为背景色,这种绘制之后的清除就导致了闪烁。CheckerDrag重写了update()来 // 防止背景被清除,从而消除了闪烁。 public void update (Graphics g) { paint (g); }}
急求这个十分简单的JAVA小代码详细注释!!
几年没有碰swing了,给你详细注释了。仔细看。希望对你有所帮助。
import java.awt.*;//java抽象窗口工具包
import java.awt.event.*;//java抽象窗口工具包组件所激发的各类事件的接口和类
public class Test5{//类名
Frame f;//定义一个Frame窗体
TextArea center;//文本域
Label la1,la2,la3;//三个标签
Panel east,south,north;//三块面板
Button b1,b2,b3,b4;//四个按钮
Choice l1;//下拉单选框
TextField t1;//文本域
// textfield只有一行可写
// textarea是一个区域,可以有很多行
public static void main(String[] args){//主函数,程序入口
Test mb = new Test();
mb.go();//调用go方法,初始化界面
}
private void go(){
f = new Frame("留言版程序");//标题
f.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent evt){
f.setVisible(false);
System.exit(0);
//System.exit(0) 0--正常结束程序 1--异常关闭程序
}
});
f.setBounds(0,0,600,400);//布局大小
f.setLayout(new BorderLayout());//显示方式
f.setResizable(false);
//下面都将控件按钮初始化,你懂得
north = new Panel();
south = new Panel();
east = new Panel();
center = new TextArea("留言内容:");
center.setEditable(false);
b1 = new Button("清屏");
b2 = new Button("至顶");
b3 = new Button("至尾");
la1 = new Label("留言版");
la2 = new Label("你");
la3 = new Label(" 地说:");
t1 = new TextField(20);
b4 = new Button("提交");
l1 =new Choice();
l1.add("微笑 ");
l1.add("生气 ");
l1.add("伤心 ");
f.add(BorderLayout.NORTH,north);//布局
f.add(BorderLayout.SOUTH,south);//布局
f.add(BorderLayout.EAST,east);//布局
f.add(BorderLayout.CENTER,center);//布局
north.add(BorderLayout.CENTER,la1);
south.add(la2);//把东西加到面板上
south.add(l1);
south.add(la3);
south.add(t1);//把东西加到面板上
south.add(b4);
east.setLayout(new GridLayout(9,0,1,10));
east.add(b1);
east.add(b2);
east.add(b3);
f.setVisible(true);//可视化
b4.addActionListener(new ActionListener(){//点击提交按钮产生事件
public void actionPerformed(ActionEvent e){
String text1,text2;
text1 = l1.getSelectedItem();
text2 = t1.getText();
t1.setText(null);
if(t1.getText() != ""){//将下拉单选框的内容和你输入在文本框的内容显示在中间面板上
center.append("\n");
center.append(text1);
center.append(text2);
}
}
});
b1.addActionListener(new ActionListener(){//清屏按钮事件,只留下中间面板显示:“留言内容:”,其余清楚
public void actionPerformed(ActionEvent e){
center.setText("留言内容:");
}
});
b2.addActionListener(new ActionListener(){//至顶按钮事件,光标焦点至顶
public void actionPerformed(ActionEvent e){
center.requestFocusInWindow();
center.setCaretPosition(8);
}
});
b3.addActionListener(new ActionListener(){//至尾按钮事件,光标焦点至尾
public void actionPerformed(ActionEvent e){
center.requestFocusInWindow();
center.setCaretPosition(center.getText().length());
}
});
}
}
求一个简单又有趣的JAVA小游戏代码
具体如下:
连连看的小源码
package Lianliankan;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class lianliankan implements ActionListener
{
JFrame mainFrame; //主面板
Container thisContainer;
JPanel centerPanel,southPanel,northPanel; //子面板
JButton diamondsButton[][] = new JButton[6][5];//游戏按钮数组
JButton exitButton,resetButton,newlyButton; //退出,重列,重新开始按钮
JLabel fractionLable=new JLabel("0"); //分数标签
JButton firstButton,secondButton; //
分别记录两次62616964757a686964616fe59b9ee7ad9431333335326239被选中的按钮
int grid[][] = new int[8][7];//储存游戏按钮位置
static boolean pressInformation=false; //判断是否有按钮被选中
int x0=0,y0=0,x=0,y=0,fristMsg=0,secondMsg=0,validateLV; //游戏按钮的位置坐标
int i,j,k,n;//消除方法控制
代码(code)是程序员用开发工具所支持的语言写出来的源文件,是一组由字符、符号或信号码元以离散形式表示信息的明确的规则体系。
对于字符和Unicode数据的位模式的定义,此模式代表特定字母、数字或符号(例如 0x20 代表一个空格,而 0x74 代表字符“t”)。一些数据类型每个字符使用一个字节;每个字节可以具有 256 个不同的位模式中的一个模式。
在计算机中,字符由不同的位模式(ON 或 OFF)表示。每个字节有 8 位,这 8 位可以有 256 种不同的 ON 和 OFF 组合模式。对于使用 1 个字节存储每个字符的程序,通过给每个位模式指派字符可表示最多 256 个不同的字符。2 个字节有 16 位,这 16 位可以有 65,536 种唯一的 ON 和 OFF 组合模式。使用 2 个字节表示每个字符的程序可表示最多 65,536 个字符。
单字节代码页是字符定义,这些字符映射到每个字节可能有的 256 种位模式中的每一种。代码页定义大小写字符、数字、符号以及 !、@、#、% 等特殊字符的位模式。每种欧洲语言(如德语和西班牙语)都有各自的单字节代码页。
虽然用于表示 A 到 Z 拉丁字母表字符的位模式在所有的代码页中都相同,但用于表示重音字符(如"é"和"á")的位模式在不同的代码页中却不同。如果在运行不同代码页的计算机间交换数据,必须将所有字符数据由发送计算机的代码页转换为接收计算机的代码页。如果源数据中的扩展字符在接收计算机的代码页中未定义,那么数据将丢失。
如果某个数据库为来自许多不同国家的客户端提供服务,则很难为该数据库选择这样一种代码页,使其包括所有客户端计算机所需的全部扩展字符。而且,在代码页间不停地转换需要花费大量的处理时间。
高分求高手补全一个java小游戏,内详
最不会加注释了,不知道行不行,一共149行,要求全部完成。
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.Timer;
public class Racer extends JFrame {
private MyPanel drawPanel;
public static final int LINE_LEN = 20; // 方格的边长
public static final int NUM = 20; // 方格的个数为NUM*NUM
private static final int EDGE_WIDTH = 25; // 边距
public static final int OBSTACLE_NUM = 10; //屏幕上同时出现的障碍物数量
Racer() {
getContentPane().setLayout(new BorderLayout());
drawPanel = new MyPanel(this);
getContentPane().add(drawPanel, "Center"); //把游戏面板放到屏幕中央
setSize((LINE_LEN + 1) * NUM + EDGE_WIDTH, (LINE_LEN + 1) * NUM
+ EDGE_WIDTH); //设置窗口大小
setVisible(true); //显示窗口
drawPanel.requestFocusInWindow(); //在窗口显示后要求接受键盘输入
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //关闭窗口时结束程序
}
public static void main(String[] args) {
Racer r = new Racer();
}
}
class MyPanel extends JPanel implements ActionListener, KeyListener {
private Racer owner;
private static boolean flag = false; // 画路时,交替地画出黑白方块
private int num = Racer.NUM;
private int len = Racer.LINE_LEN;
private int x = 0; //汽车的位置,一开始为0
private int[] obstacleX = new int[Racer.OBSTACLE_NUM]; //所有障碍物的X坐标
private int[] obstacleY = new int[Racer.OBSTACLE_NUM]; //所有障碍物的Y坐标
private int[] carX = {8, 7, 8, 9, 8, 7, 8, 9}; //汽车方格的X坐标
private int[] carY = {16, 17, 17, 17, 18, 19, 19, 19}; //汽车方格的Y坐标
Random rand = new Random(); //随机数生成器
Timer timer; //动画计时更新,用javax.swing.Timer和键盘的输入较为匹配,可以避免直接用线程出现的一些问题
int LEFT_KEY = KeyEvent.VK_W; //按w键为往左,如果要按左键往左的话LEFT_KEY = KeyEvent.VK_LEFT
int RIGHT_KEY = KeyEvent.VK_D; //按w键为往左,如果要按右键往右的话LEFT_KEY = KeyEvent.VK_RIGHT
MyPanel(Racer r) {
owner = r;
timer = new Timer(200, this); //时间间隔为200毫秒
timer.start(); //开始游戏更新
addKeyListener(this); //注册键盘输入
for(int i=0;iobstacleX.length;i++) { //给与每个障碍物随机的坐标
obstacleX[i] = rand.nextInt(Racer.NUM-2)+1; //X在路面的左面1和右面NUM-1之间
obstacleY[i] = rand.nextInt(Racer.NUM) - num; //y在路面上方-1到-1-NUM之间,游戏开始时看不到
}
}
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()==LEFT_KEY) x--; //按往左的键时减小x变量
else if(e.getKeyCode()==RIGHT_KEY) x++; //按往右的键时增加x变量
if(x-6) x=-6; //如果出了左边界的话把车放回边界内
if(x9) x=9; //如果出了右边界的话把车放回边界内
repaint(); //重新画一编移动后的车
}
public void paint(Graphics g) {
g.clearRect(0, 0, getSize().width, getSize().height);
drawBkgnd(g); // 画背景
drawRoad(g); // 画路
drawCar(g); // 画车
drawObstacles(g); //画障碍物
}
private void drawBkgnd(Graphics g) {
for (int i = 0; i = num; i++) {
g.drawLine(0, i * len, len * num, i * len); //画横线
g.drawLine(i * len, 0, i * len, len * num); //画竖线
}
}
private void drawRoad(Graphics g) {
if (flag) {
for (int i = 0; i num; i += 2) { //交替涂路边的格子
g.fillRect(0, i * len, len, len);
g.fillRect((num - 1) * len, i * len, len, len);
}
} else {
for (int i = 1; i num; i += 2) {
g.fillRect(0, i * len, len, len);
g.fillRect((num - 1) * len, i * len, len, len);
}
}
}
private void drawCar(Graphics g) {
for(int i=0;icarX.length;i++) {
g.fillRect((carX[i] + x)*len, carY[i]*len, len, len); //把汽车所占有的格子涂黑
}
}
private void drawObstacles(Graphics g) {
for(int i=0;iobstacleX.length;i++) {
g.fillRect(obstacleX[i]*len, obstacleY[i]*len, len, len); //把障碍物占有的格子涂黑
}
}
private boolean collision() {
for(int i=0;iobstacleX.length;i++) { //对于每个障碍物的格子
for(int j=0;jcarX.length;j++) { //对于每个汽车的格子
if(obstacleX[i] == carX[j]+x obstacleY[i] == carY[j]) //如果障碍物的坐标和汽车的坐标一样的话
return true; //相撞发生了
}
}
return false;
}
public void actionPerformed(ActionEvent e) {
if(collision()) { //检测有没有撞到障碍物
timer.stop(); //暂停游戏
JOptionPane.showMessageDialog(this, "你输了,按OK重新开始。"); //显示结束信息
//这里用户按下了ok
for(int i=0;iobstacleX.length;i++) { //重新设置障碍物的位置
obstacleX[i] = rand.nextInt(Racer.NUM-2)+1;
obstacleY[i] = rand.nextInt(Racer.NUM) - num;
}
x=0; //重置汽车的位置
timer.start(); //恢复游戏
}
for(int i=0;iobstacleY.length;i++) { //对于每个障碍物
obstacleY[i]++; //让障碍物往下移动一格
if(obstacleY[i]=num) { //如果障碍物移动到网格的下面去了
obstacleX[i]=rand.nextInt(num-2)+1; //随机给一个新的X坐标
obstacleY[i]=0; //恢复到屏幕上放
}
}
flag=!flag; //更新路边的斑马格
repaint(); //重画屏幕
}
public void keyReleased(KeyEvent e) {} //没有用到的方法,继承KeyListener必须声明
public void keyTyped(KeyEvent e) {} //同上
}
java贪吃蛇代码注释求解
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
public class InterFace extends JFrame {
/**
* WIDTH:宽
* HEIGHT:高
* SLEEPTIME:可以看作蛇运动的速度
* L = 1,R = 2, U = 3, D = 4 左右上下代码
*/
public static final int WIDTH = 800, HEIGHT = 600, SLEEPTIME = 200, L = 1,R = 2, U = 3, D = 4;
BufferedImage offersetImage= new BufferedImage(WIDTH, HEIGHT,BufferedImage.TYPE_3BYTE_BGR);;
Rectangle rect = new Rectangle(20, 40, 15 * 50, 15 * 35);
Snake snake;
Node node;
public InterFace() {
//创建"蛇"对象
snake = new Snake(this);
//创建"食物"对象
createNode();
this.setBounds(100, 100, WIDTH, HEIGHT);
//添加键盘监听器
this.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent arg0) {
System.out.println(arg0.getKeyCode());
switch (arg0.getKeyCode()) {
//映射上下左右4个键位
case KeyEvent.VK_LEFT:
snake.dir = L;
break;
case KeyEvent.VK_RIGHT:
snake.dir = R;
break;
case KeyEvent.VK_UP:
snake.dir = U;
break;
case KeyEvent.VK_DOWN:
snake.dir = D;
}
}
});
this.setTitle("贪吃蛇 0.1 By : Easy");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setVisible(true);
//启动线程,开始执行
new Thread(new ThreadUpadte()).start();
}
public void paint(Graphics g) {
Graphics2D g2d = (Graphics2D) offersetImage.getGraphics();
g2d.setColor(Color.white);
g2d.fillRect(0, 0, WIDTH, HEIGHT);
g2d.setColor(Color.black);
g2d.drawRect(rect.x, rect.y, rect.width, rect.height);
//如果蛇碰撞(吃)到食物,则创建新食物
if (snake.hit(node)) {
createNode();
}
snake.draw(g2d);
node.draw(g2d);
g.drawImage(offersetImage, 0, 0, null);
}
class ThreadUpadte implements Runnable {
public void run() {
//无限重绘画面
while (true) {
try {
Thread.sleep(SLEEPTIME);
repaint(); //
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
/**
* 创建食物
*/
public void createNode() {
//随机食物的出现位置
int x = (int) (Math.random() * 650) + 50,y = (int) (Math.random() * 500) + 50;
Color color = Color.blue;
node = new Node(x, y, color);
}
public static void main(String args[]) {
new InterFace();
}
}
/**
* 节点类(包括食物和蛇的身躯组成节点)
*/
class Node {
int x, y, width = 15, height = 15;
Color color;
public Node(int x, int y, Color color) {
this(x, y);
this.color = color;
}
public Node(int x, int y) {
this.x = x;
this.y = y;
this.color = color.black;
}
public void draw(Graphics2D g2d) {
g2d.setColor(color);
g2d.drawRect(x, y, width, height);
}
public Rectangle getRect() {
return new Rectangle(x, y, width, height);
}
}
/**
* 蛇
*/
class Snake {
public ListNode nodes = new ArrayListNode();
InterFace interFace;
int dir=InterFace.R;
public Snake(InterFace interFace) {
this.interFace = interFace;
nodes.add(new Node(20 + 150, 40 + 150));
addNode();
}
/**
* 是否碰撞到食物
* @return true 是 false 否
*/
public boolean hit(Node node) {
//遍历整个蛇体是否与食物碰撞
for (int i = 0; i nodes.size(); i++) {
if (nodes.get(i).getRect().intersects(node.getRect())) {
addNode();
return true;
}
}
return false;
}
public void draw(Graphics2D g2d) {
for (int i = 0; i nodes.size(); i++) {
nodes.get(i).draw(g2d);
}
move();
}
public void move() {
nodes.remove((nodes.size() - 1));
addNode();
}
public synchronized void addNode() {
Node nodeTempNode = nodes.get(0);
//如果方向
switch (dir) {
case InterFace.L:
//判断是否会撞墙
if (nodeTempNode.x = 20) {
nodeTempNode = new Node(20 + 15 * 50, nodeTempNode.y);
}
nodes.add(0, new Node(nodeTempNode.x - nodeTempNode.width,
nodeTempNode.y));
break;
case InterFace.R:
//判断是否会撞墙
if (nodeTempNode.x = 20 + 15 * 50 - nodeTempNode.width) {
nodeTempNode = new Node(20 - nodeTempNode.width, nodeTempNode.y);
}
nodes.add(0, new Node(nodeTempNode.x + nodeTempNode.width,
nodeTempNode.y));
break;
case InterFace.U:
//判断是否会撞墙
if (nodeTempNode.y = 40) {
nodeTempNode = new Node(nodeTempNode.x, 40 + 15 * 35);
}
nodes.add(0, new Node(nodeTempNode.x, nodeTempNode.y - nodeTempNode.height));
break;
case InterFace.D:
//判断是否会撞墙
if (nodeTempNode.y = 40 + 15 * 35 - nodeTempNode.height) {
nodeTempNode = new Node(nodeTempNode.x,40 - nodeTempNode.height);
}
nodes.add(0, new Node(nodeTempNode.x, nodeTempNode.y + nodeTempNode.height));
break;
}
}
}
关于java小游戏代码详细注释和java语言小游戏代码的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。
版权说明:如非注明,本站文章均为 AH站长 原创,转载请注明出处和附带本文链接;
相关推荐
- 05-12网页设计需要学什么,网页设计学什么语言
- 05-10自己建网页,自己建网页详细流程
- 05-09网页代码,网页代码快捷键
- 05-06单页网站的代码(完整的网页代码)[20240506更新]
- 05-06个人主页图片代码(个人主页图片代码怎么弄)[20240506更新]
- 05-06提取微信名片代码(微信名片信息提取)[20240506更新]
- 05-06php后台权限管理代码(php管理员权限)[20240506更新]
- 05-06付费观看代码php(付费观看代码)[20240506更新]
- 05-06在线html执行代码(html怎么运行)[20240506更新]
- 05-06源代码管理资源管理器(资源管理器运行代码)[20240506更新]
取消回复欢迎 你 发表评论:
- 标签列表
- 最近发表
- 友情链接