求java小程序源代码 在线等 急急急!!!
发布网友
发布时间:2022-04-27 01:41
我来回答
共5个回答
热心网友
时间:2022-06-22 03:01
下面是俄罗斯方块游戏源代码
还没完,这代码太长了,我用我另一个号再粘上
import javax.swing.*;
import javax.swing.JOptionPane;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import java.awt.*;
import java.awt.event.*;
/**
* 游戏主类,继承自JFrame类,负责游戏的全局控制。
* 内含
* 1, 一个GameCanvas画布类的实例引用,
* 2, 一个保存当前活动块(ErsBlock)实例的引用,
* 3, 一个保存当前控制面板(ControlPanel)实例的引用;*/
public class ErsBlocksGame extends JFrame {
/**
* 每填满一行计多少分*/
public final static int PER_LINE_SCORE = 100;
/**
* 积多少分以后能升级*/
public final static int PER_LEVEL_SCORE = PER_LINE_SCORE * 20;
/**
* 最大级数是10级*/
public final static int MAX_LEVEL = 10;
/**
* 默认级数是5*/
public final static int DEFAULT_LEVEL = 5;
private GameCanvas canvas;
private ErsBlock block;
private boolean playing = false;
private ControlPanel ctrlPanel;
private JMenuBar bar = new JMenuBar();
private JMenu
mGame = new JMenu("游戏设置"),
mControl = new JMenu("游戏控制"),
mWindowStyle = new JMenu("窗口风格");
private JMenuItem
miNewGame = new JMenuItem("新游戏"),
miSetBlockColor = new JMenuItem("设置颜色 ..."),
miSetBackColor = new JMenuItem("设置底色 ..."),
miTurnHarder = new JMenuItem("提升等级"),
miTurnEasier = new JMenuItem("调底等级"),
miExit = new JMenuItem("退出"),
miPlay = new JMenuItem("开始游戏"),
miPause = new JMenuItem("暂停"),
miResume = new JMenuItem("继续");
private JCheckBoxMenuItem
miAsWindows = new JCheckBoxMenuItem("风格1"),
miAsMotif = new JCheckBoxMenuItem("风格2"),
miAsMetal = new JCheckBoxMenuItem("风格3", true);
/**
* 主游戏类的构造函数
* @param title String,窗口标题*/
public ErsBlocksGame(String title) {
super(title);
//this.setTitle("lskdf");
setSize(315, 392);
Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();
//获得屏幕的大小
setLocation((scrSize.width - getSize().width) / 2,
(scrSize.height - getSize().height) / 2);
createMenu();
Container container = getContentPane();
container.setLayout(new BorderLayout(6, 0));
canvas = new GameCanvas(20, 12);
ctrlPanel = new ControlPanel(this);
container.add(canvas, BorderLayout.CENTER);
container.add(ctrlPanel, BorderLayout.EAST);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
JOptionPane about=new JOptionPane();
stopGame();
System.exit(0);
}
});
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent ce) {
canvas.fanning();
}
});
show();
canvas.fanning();
}
// 游戏“复位”
public void reset() {
ctrlPanel.reset();
canvas.reset();
}
/**
* 判断游戏是否还在进行
* @return boolean, true-还在运行,false-已经停止*/
public boolean isPlaying() {
return playing;
}
/**
* 得到当前活动的块
* @return ErsBlock, 当前活动块的引用*/
public ErsBlock getCurBlock() {
return block;
}
/**
* 得到当前画布
* @return GameCanvas, 当前画布的引用 */
public GameCanvas getCanvas() {
return canvas;
}
/**
* 开始游戏*/
public void playGame() {
play();
ctrlPanel.setPlayButtonEnable(false);
miPlay.setEnabled(false);
ctrlPanel.requestFocus();
}
/**
* 游戏暂停*/
public void pauseGame() {
if (block != null) block.pauseMove();
ctrlPanel.setPauseButtonLabel(false);
miPause.setEnabled(false);
miResume.setEnabled(true);
}
/**
* 让暂停中的游戏继续*/
public void resumeGame() {
if (block != null) block.resumeMove();
ctrlPanel.setPauseButtonLabel(true);
miPause.setEnabled(true);
miResume.setEnabled(false);
ctrlPanel.requestFocus();
}
/**
* 用户停止游戏 */
public void stopGame() {
playing = false;
if (block != null) block.stopMove();
miPlay.setEnabled(true);
miPause.setEnabled(true);
miResume.setEnabled(false);
ctrlPanel.setPlayButtonEnable(true);
ctrlPanel.setPauseButtonLabel(true);
}
/**
* 得到当前游戏者设置的游戏难度
* @return int, 游戏难度1-MAX_LEVEL*/
public int getLevel() {
return ctrlPanel.getLevel();
}
/**
* 让用户设置游戏难度
* @param level int, 游戏难度1-MAX_LEVEL*/
public void setLevel(int level) {
if (level < 11 && level > 0) ctrlPanel.setLevel(level);
}
/**
* 得到游戏积分
* @return int, 积分。*/
public int getScore() {
if (canvas != null) return canvas.getScore();
return 0;
}
/**
* 得到自上次升级以来的游戏积分,升级以后,此积分清零
* @return int, 积分。*/
public int getScoreForLevelUpdate() {
if (canvas != null) return canvas.getScoreForLevelUpdate();
return 0;
}
/**
* 当分数累计到一定的数量时,升一次级
* @return boolean, ture-update successufl, false-update fail
*/
public boolean levelUpdate() {
int curLevel = getLevel();
if (curLevel < MAX_LEVEL) {
setLevel(curLevel + 1);
canvas.resetScoreForLevelUpdate();
return true;
}
return false;
}
/**
* 游戏开始*/
private void play() {
reset();
playing = true;
Thread thread = new Thread(new Game());
thread.start();
}
/**
* 报告游戏结束了*/
private void reportGameOver() {
JOptionPane.showMessageDialog(this, "游戏结束!");
}
/**
* 建立并设置窗口菜单 */
private void createMenu() {
bar.add(mGame);
bar.add(mControl);
bar.add(mWindowStyle);
mGame.add(miNewGame);
mGame.addSeparator();
mGame.add(miSetBlockColor);
mGame.add(miSetBackColor);
mGame.addSeparator();
mGame.add(miTurnHarder);
mGame.add(miTurnEasier);
mGame.addSeparator();
mGame.add(miExit);
mControl.add(miPlay);
mControl.add(miPause);
mControl.add(miResume);
mWindowStyle.add(miAsWindows);
mWindowStyle.add(miAsMotif);
mWindowStyle.add(miAsMetal);
setJMenuBar(bar);
miPause.setAccelerator(
KeyStroke.getKeyStroke(KeyEvent.VK_P, KeyEvent.CTRL_MASK));
miResume.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0));
miNewGame.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
stopGame();
reset();
setLevel(DEFAULT_LEVEL);
}
});
miSetBlockColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Color newFrontColor =
JColorChooser.showDialog(ErsBlocksGame.this,
"设置积木颜色", canvas.getBlockColor());
if (newFrontColor != null)
canvas.setBlockColor(newFrontColor);
}
});
miSetBackColor.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
Color newBackColor =
JColorChooser.showDialog(ErsBlocksGame.this,
"设置底版颜色", canvas.getBackgroundColor());
if (newBackColor != null)
canvas.setBackgroundColor(newBackColor);
}
});
miTurnHarder.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int curLevel = getLevel();
if (curLevel < MAX_LEVEL) setLevel(curLevel + 1);
}
});
miTurnEasier.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int curLevel = getLevel();
if (curLevel > 1) setLevel(curLevel - 1);
}
});
miExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
System.exit(0);
}
});
miPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
playGame();
}
});
miPause.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
pauseGame();
}
});
miResume.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
resumeGame();
}
});
miAsWindows.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String plaf = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel";
setWindowStyle(plaf);
canvas.fanning();
ctrlPanel.fanning();
miAsWindows.setState(true);
miAsMetal.setState(false);
miAsMotif.setState(false);
}
});
miAsMotif.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String plaf = "com.sun.java.swing.plaf.motif.MotifLookAndFeel";
setWindowStyle(plaf);
canvas.fanning();
ctrlPanel.fanning();
miAsWindows.setState(false);
miAsMetal.setState(false);
miAsMotif.setState(true);
}
});
miAsMetal.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String plaf = "javax.swing.plaf.metal.MetalLookAndFeel";
setWindowStyle(plaf);
canvas.fanning();
ctrlPanel.fanning();
miAsWindows.setState(false);
miAsMetal.setState(true);
miAsMotif.setState(false);
}
});
}
/**
* 根据字串设置窗口外观
* @param plaf String, 窗口外观的描述
*/
private void setWindowStyle(String plaf) {
try {
UIManager.setLookAndFeel(plaf);
SwingUtilities.updateComponentTreeUI(this);
} catch (Exception e) {
}
}
/**
* 一轮游戏过程,实现了Runnable接口
* 一轮游戏是一个大循环,在这个循环中,每隔100毫秒,
* 检查游戏中的当前块是否已经到底了,如果没有,
* 就继续等待。如果到底了,就看有没有全填满的行,
* 如果有就删除它,并为游戏者加分,同时随机产生一个
* 新的当前块,让它自动下落。
* 当新产生一个块时,先检查画布最顶上的一行是否已经
* 被占了,如果是,可以判断Game Over了。*/
private class Game implements Runnable {
public void run() {
//产生新方快
int col = (int) (Math.random() * (canvas.getCols() - 3)),
style = ErsBlock.STYLES[(int) (Math.random() * 7)][(int) (Math.random() * 4)];
while (playing) {
if (block != null) { //第一次循环时,block为空
if (block.isAlive()) {
try {
Thread.currentThread().sleep(100);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
continue;
}
}
checkFullLine(); //检查是否有全填满的行
if (isGameOver()) { //检查游戏是否应该结束了
miPlay.setEnabled(true);
miPause.setEnabled(true);
miResume.setEnabled(false);
ctrlPanel.setPlayButtonEnable(true);
ctrlPanel.setPauseButtonLabel(true);
reportGameOver();
return;
}
block = new ErsBlock(style, -1, col, getLevel(), canvas);
block.start();
col = (int) (Math.random() * (canvas.getCols() - 3));
style = ErsBlock.STYLES[(int) (Math.random() * 7)][(int) (Math.random() * 4)];
ctrlPanel.setTipStyle(style);
}
}
/**
* 检查画布中是否有全填满的行,如果有就删除之*/
public void checkFullLine() {
for (int i = 0; i < canvas.getRows(); i++) {
int row = -1;
boolean fullLineColorBox = true;
for (int j = 0; j < canvas.getCols(); j++) {
if (!canvas.getBox(i, j).isColorBox()) {
fullLineColorBox = false;
break;
}
}
if (fullLineColorBox) {
row = i--;
canvas.removeLine(row);
}
}
}
/**
* 根据最顶行是否被占,判断游戏是否已经结束了。
* @return boolean, true-游戏结束了,false-游戏未结束*/
private boolean isGameOver() {
for (int i = 0; i < canvas.getCols(); i++) {
ErsBox box = canvas.getBox(0, i);
if (box.isColorBox()) return true;
}
return false;
}
}
热心网友
时间:2022-06-22 03:02
//接住上面的 ,还没完,看来我还得换个号
public static void main(String[] args) {
new ErsBlocksGame("俄罗斯方块 v1.0");
}
public ErsBlocksGame() {
try {
jbInit();
}
catch(Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
this.addWindowListener(new ErsBlocksGame_this_windowAdapter(this));
}
}
/////////////////////////////////////////////////////////////////////////
class GameCanvas extends JPanel {
private Color backColor = Color.black, frontColor = Color.orange;
private int rows, cols, score = 0, scoreForLevelUpdate = 0;
private ErsBox[][] boxes;
private int boxWidth, boxHeight;
public GameCanvas(int rows, int cols) {
this.rows = rows;
this.cols = cols;
boxes = new ErsBox[rows][cols];
for (int i = 0; i < boxes.length; i++) {
for (int j = 0; j < boxes[i].length; j++) {
boxes[i][j] = new ErsBox(false);
}
}
setBorder(new EtchedBorder(
EtchedBorder.RAISED, Color.white, new Color(148, 145, 140)));
}
public GameCanvas(int rows, int cols,
Color backColor, Color frontColor) {
this(rows, cols);
this.backColor = backColor;
this.frontColor = frontColor;
}
/**
* 设置游戏背景色彩
* @param backColor Color, 背景色彩*/
public void setBackgroundColor(Color backColor) {
this.backColor = backColor;
}
/**
* 取得游戏背景色彩
* @return Color, 背景色彩*/
public Color getBackgroundColor() {
return backColor;
}
public void setBlockColor(Color frontColor) {
this.frontColor = frontColor;
}
/**
* 取得游戏方块色彩
* @return Color, 方块色彩*/
public Color getBlockColor() {
return frontColor;
}
/**
* 取得画布中方格的行数
* @return int, 方格的行数*/
public int getRows() {
return rows;
}
public int getCols() {
return cols;
}
public int getScore() {
return score;
}
public int getScoreForLevelUpdate() {
return scoreForLevelUpdate;
}
public void resetScoreForLevelUpdate() {
scoreForLevelUpdate -= ErsBlocksGame.PER_LEVEL_SCORE;
}
public ErsBox getBox(int row, int col) {
if (row < 0 || row > boxes.length - 1
|| col < 0 || col > boxes[0].length - 1)
return null;
return (boxes[row][col]);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(frontColor);
for (int i = 0; i < boxes.length; i++) {
for (int j = 0; j < boxes[i].length; j++) {
g.setColor(boxes[i][j].isColorBox() ? frontColor : backColor);
g.fill3DRect(j * boxWidth, i * boxHeight,
boxWidth, boxHeight, true);
}
}
}
public void fanning() {
boxWidth = getSize().width / cols;
boxHeight = getSize().height / rows;
}
public synchronized void removeLine(int row) {
for (int i = row; i > 0; i--) {
for (int j = 0; j < cols; j++)
boxes[i][j] = (ErsBox) boxes[i - 1][j].clone();
}
score += ErsBlocksGame.PER_LINE_SCORE;
scoreForLevelUpdate += ErsBlocksGame.PER_LINE_SCORE;
repaint();
}
public void reset() {
score = 0;
scoreForLevelUpdate = 0;
for (int i = 0; i < boxes.length; i++) {
for (int j = 0; j < boxes[i].length; j++)
boxes[i][j].setColor(false);
}
repaint();
}
}
class ErsBlocksGame_this_windowAdapter extends java.awt.event.WindowAdapter {
ErsBlocksGame adaptee;
ErsBlocksGame_this_windowAdapter(ErsBlocksGame adaptee) {
this.adaptee = adaptee;
}
}
class ErsBlock extends Thread {
/**
* 一个块占的行数是4行 */
public final static int BOXES_ROWS = 4;
/**
* 一个块占的列数是4列*/
public final static int BOXES_COLS = 4;
/**
* 让升级变化平滑的因子,避免最后几级之间的速度相差近一倍*/
public final static int LEVEL_FLATNESS_GENE = 3;
/**
* 相近的两级之间,块每下落一行的时间差别为多少(毫秒)*/
public final static int BETWEEN_LEVELS_DEGRESS_TIME = 50;
/**
* 方块的样式数目为7*/
private final static int BLOCK_KIND_NUMBER = 7;
/**
* 每一个样式的方块的反转状态种类为4*/
private final static int BLOCK_STATUS_NUMBER = 4;
/**
* 分别对应对7种模型的28种状态*/
public final static int[][] STYLES = {// 共28种状态
{0x0f00, 0x4444, 0x0f00, 0x4444}, // 长条型的四种状态
{0x04e0, 0x0464, 0x00e4, 0x04c4}, // 'T'型的四种状态
{0x4620, 0x6c00, 0x4620, 0x6c00}, // 反'Z'型的四种状态
{0x2640, 0xc600, 0x2640, 0xc600}, // 'Z'型的四种状态
{0x6220, 0x1700, 0x2230, 0x0740}, // '7'型的四种状态
{0x6440, 0x0e20, 0x44c0, 0x8e00}, // 反'7'型的四种状态
{0x0660, 0x0660, 0x0660, 0x0660}, // 方块的四种状态
};
private GameCanvas canvas;
private ErsBox[][] boxes = new ErsBox[BOXES_ROWS][BOXES_COLS];
private int style, y, x, level;
private boolean pausing = false, moving = true;
public ErsBlock(int style, int y, int x, int level, GameCanvas canvas) {
this.style = style;
this.y = y;
this.x = x;
this.level = level;
this.canvas = canvas;
int key = 0x8000;
for (int i = 0; i < boxes.length; i++) {
for (int j = 0; j < boxes[i].length; j++) {
boolean isColor = ((style & key) != 0);
boxes[i][j] = new ErsBox(isColor);
key >>= 1;
}
}
display();
}
/**
* 线程类的run()函数覆盖,下落块,直到块不能再下落*/
public void run() {
while (moving) {
try {
sleep(BETWEEN_LEVELS_DEGRESS_TIME
* (ErsBlocksGame.MAX_LEVEL - level + LEVEL_FLATNESS_GENE));
} catch (InterruptedException ie) {
ie.printStackTrace();
}
//后边的moving是表示在等待的100毫秒间,moving没被改变
if (!pausing) moving = (moveTo(y + 1, x) && moving);
}
}
/**
* 块向左移动一格*/
public void moveLeft() {
moveTo(y, x - 1);
}
/**
* 块向右移动一格*/
public void moveRight() {
moveTo(y, x + 1);
}
/**
* 块向下落一格*/
public void moveDown() {
moveTo(y + 1, x);
}
public void moveDownest(){
while(isMoveAble(y+1,x) )
moveTo(y + 1, x);
}
/**
* 块变型*/
public void turnNext() {
for (int i = 0; i < BLOCK_KIND_NUMBER; i++) {
for (int j = 0; j < BLOCK_STATUS_NUMBER; j++) {
if (STYLES[i][j] == style) {
int newStyle = STYLES[i][(j + 1) % BLOCK_STATUS_NUMBER];
turnTo(newStyle);
return;
}
}
}
}
/**
* 暂停块的下落,对应游戏暂停*/
public void pauseMove() {
pausing = true;
}
/**
* 继续块的下落,对应游戏继续*/
public void resumeMove() {
pausing = false;
}
/**
* 停止块的下落,对应游戏停止*/
public void stopMove() {
moving = false;
}
private void earse() {
for (int i = 0; i < boxes.length; i++) {
for (int j = 0; j < boxes[i].length; j++) {
if (boxes[i][j].isColorBox()) {
ErsBox box = canvas.getBox(i + y, j + x);
if (box == null) continue;
box.setColor(false);
}
}
}
}
private void display() {
for (int i = 0; i < boxes.length; i++) {
for (int j = 0; j < boxes[i].length; j++) {
if (boxes[i][j].isColorBox()) {
ErsBox box = canvas.getBox(y + i, x + j);
if (box == null) continue;
box.setColor(true);
}
}
}
}
private boolean isMoveAble(int newRow, int newCol) {
earse();
for (int i = 0; i < boxes.length; i++) {
for (int j = 0; j < boxes[i].length; j++) {
if (boxes[i][j].isColorBox()) {
ErsBox box = canvas.getBox(newRow + i, newCol + j);
if (box == null || (box.isColorBox())) {
display();
return false;
}
}
}
}
display();
return true;
}
private synchronized boolean moveTo(int newRow, int newCol) {
if (!isMoveAble(newRow, newCol) || !moving) return false;
earse();
y = newRow;
x = newCol;
display();
canvas.repaint();
return true;
}
private boolean isTurnAble(int newStyle) {
int key = 0x8000;
earse();
for (int i = 0; i < boxes.length; i++) {
for (int j = 0; j < boxes[i].length; j++) {
if ((newStyle & key) != 0) {
ErsBox box = canvas.getBox(y + i, x + j);
if (box == null || box.isColorBox()) {
display();
return false;
}
}
key >>= 1;
}
}
display();
return true;
}
private boolean turnTo(int newStyle) {
if (!isTurnAble(newStyle) || !moving) return false;
earse();
int key = 0x8000;
for (int i = 0; i < boxes.length; i++) {
for (int j = 0; j < boxes[i].length; j++) {
boolean isColor = ((newStyle & key) != 0);
boxes[i][j].setColor(isColor);
key >>= 1;
}
}
style = newStyle;
display();
canvas.repaint();
return true;
}
}
热心网友
时间:2022-06-22 03:02
/*
*12.24日,完成了蛇撞到自己的检测.修改方法是在蛇的初始化的时候,用双循环来置FALSE;
* 在重写代码的时候,我借鉴了别人的思路:将整个游戏的界面定义为一个布尔型的二维数组.
* 用一个LinkedList来储存蛇.当蛇移动的时候,在蛇的头部增加一个节点,然后删除最后一个节点.
* 因为只是做练习,所以没做游戏界面,比如菜单栏,计分栏什么的.另外还有一个问题,就是当两次点击回车时,蛇的移动速度会变快
*/
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
public class Game {
public static void main(String args[]) {
GameFrame frame = new GameFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setResizable(false);
frame.show();
JOptionPane.showMessageDialog(null, "上,下左,右控制蛇的方向\n回车开始,S暂停");
}
}
class GameFrame extends JFrame {
public GameFrame() {
setSize(294, 482);
setTitle("贪吃蛇DEMO");
this.setLocation(360, 100);
Container c = getContentPane();
GamePanel panel = new GamePanel();
c.add(panel, BorderLayout.CENTER);
}
}
class GamePanel extends JPanel implements KeyListener {
static int panelWidth = 294;
static int panelHeight = 450;
int rectX = 15;
int rectY = 15;
Snake snake;
Node n;
public GamePanel() {
snake = new Snake(this, panelWidth / rectX, panelHeight / rectY);
setBackground(Color.WHITE);
setSize(panelWidth, panelHeight);
setFocusable(true);
addKeyListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
LinkedList list = snake.snakeList;
Iterator it = list.iterator();
g2.setColor(Color.black);
while (it.hasNext()) {
n = (Node) it.next();
drawNode(g2, n);
}
g2.setColor(Color.ORANGE);
Node f = snake.food;
drawNode(g2, f);
snake.drawMap(g2);// 绘制地图
}
public void keyPressed(KeyEvent e) {
int keycode = e.getKeyCode();
if (keycode == KeyEvent.VK_ENTER) {
begin();
} else if (keycode == KeyEvent.VK_UP) {
snake.changeDirection(Snake.up);
} else if (keycode == KeyEvent.VK_DOWN) {
snake.changeDirection(Snake.down);
} else if (keycode == KeyEvent.VK_LEFT) {
snake.changeDirection(Snake.left);
} else if (keycode == KeyEvent.VK_RIGHT) {
snake.changeDirection(Snake.right);
} else if (keycode == KeyEvent.VK_S) {
Snake.run = false;
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
public void drawNode(Graphics2D g, Node n) {
g.fillRect(n.x * rectX, n.y * rectY, rectX - 2, rectY - 2);
}
public void begin() {
Snake.run = true;
SnakeThread thread = new SnakeThread(snake);
thread.start();
}
}
class Node {
int x;
int y;
public Node(int x, int y) {
this.x = x;
this.y = y;
}
}
class SnakeThread extends Thread {
Snake snake;
public SnakeThread(Snake s) {
snake = s;
}
public void run() {
Snake.run = true;
while (Snake.run) {
try {
snake.move();
sleep(200);
} catch (InterruptedException e) {
}
}
Snake.run = false;
}
}
class Snake {
GamePanel panel;
Node food;
boolean[][] all;
public static boolean run;
int maxX;
int maxY;
public static int left = 1;
public static int up = 2;
public static int right = 3;
public static int down = 4;
int direction = 4;
LinkedList snakeList = new LinkedList();
public Snake(GamePanel p, int maxX, int maxY) {
panel = p;
this.maxX = maxX;
this.maxY = maxY;
all = new boolean[maxX][maxY];
for (int i = 0; i < maxX; i++) {
for (int j = 0; j < maxY; j++) {
all[i][j] = false;
}
}
int arrayLength = maxX > 20 ? 10 : maxX / 2;
for (int i = 0; i < arrayLength; i++) {
int x = maxX / 10 + i;
int y = maxY / 10;
snakeList.addFirst(new Node(x, y));
all[x][y] = true;
}
food = createFood();
all[food.x][food.y] = true;
}
// 蛇移动的方法
public void move() {
Node n = (Node) snakeList.getFirst();
int x = n.x;
int y = n.y;
if (direction == 3) {
x++;
} else if (direction == 4) {
y++;
} else if (direction == 1) {
x--;
} else if (direction == 2) {
y--;
}
// 实现对蛇撞到自身的检测
if ((0 <= x && x <= GamePanel.panelWidth / 15 - 1)
&& (0 <= y && y <= GamePanel.panelHeight / 15 - 1)) {
if (all[x][y]) {
if (x == food.x && y == food.y) {
snakeList.addFirst(food);
food = createFood();
all[food.x][food.y] = true;
} else {
JOptionPane.showMessageDialog(null, "你撞到自己了");
System.exit(0);
}
} else {
snakeList.addFirst(new Node(x, y));
all[x][y] = true;
Node l = (Node) snakeList.getLast();
snakeList.removeLast();
all[l.x][l.y] = false;
}
} else {
JOptionPane.showMessageDialog(null, "越界了,游戏结束");
System.exit(0);
}
panel.repaint();
}
public Node createFood() {
int x = 0;
int y = 0;
do {
Random r = new Random();
x = r.nextInt(maxX - 10);
y = r.nextInt(maxY - 10);
} while (all[x][y]);
return new Node(x, y);
}
//设置蛇不能回头
public void changeDirection(int newDirection) {
if (direction % 2 != newDirection % 2) {
direction = newDirection;
}
}
public void drawMap(Graphics2D g) {
for (int i = 0; i < maxX; i++) {
for (int j = 0; j < maxY; j++) {
if (all[i][j] == true) {
g.setColor(Color.red);
g.fillRect(i, j, 4, 4);
}
}
}
}
}
热心网友
时间:2022-06-22 03:03
//接住上面的 这下完了
class ControlPanel extends JPanel {
private JTextField
tfLevel = new JTextField("" + ErsBlocksGame.DEFAULT_LEVEL),
tfScore = new JTextField("0");
private JButton
btPlay = new JButton("开始游戏"),
btPause = new JButton("暂停"),
btStop = new JButton("结束"),
btTurnLevelUp = new JButton("升级"),
btTurnLevelDown = new JButton("降级");
private JPanel plTip = new JPanel(new BorderLayout());
private TipPanel plTipBlock = new TipPanel();
private JPanel plInfo = new JPanel(new GridLayout(4, 1));
private JPanel plButton = new JPanel(new GridLayout(5, 1));
private Timer timer;
private ErsBlocksGame game;
private Border border = new EtchedBorder(
EtchedBorder.RAISED, Color.white, new Color(148, 145, 140));
public ControlPanel(final ErsBlocksGame game) {
setLayout(new GridLayout(3, 1, 0, 4));
this.game = game;
plTip.add(new JLabel("下一个方块"), BorderLayout.NORTH);
plTip.add(plTipBlock);
plTip.setBorder(border);
plInfo.add(new JLabel("等级"));
plInfo.add(tfLevel);
plInfo.add(new JLabel("分数"));
plInfo.add(tfScore);
plInfo.setBorder(border);
tfLevel.setEditable(false);
tfScore.setEditable(false);
plButton.add(btPlay);
plButton.add(btPause);
plButton.add(btStop);
plButton.add(btTurnLevelUp);
plButton.add(btTurnLevelDown);
plButton.setBorder(border);
add(plTip);
add(plInfo);
add(plButton);
addKeyListener(new ControlKeyListener());
btPlay.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
game.playGame();
}
});
btPause.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (btPause.getText().equals(new String("暂停"))) {
game.pauseGame();
} else {
game.resumeGame();
}
}
});
btStop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
game.stopGame();
}
});
btTurnLevelUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
int level = Integer.parseInt(tfLevel.getText());
if (level < ErsBlocksGame.MAX_LEVEL)
tfLevel.setText("" + (level + 1));
} catch (NumberFormatException e) {
}
requestFocus();
}
});
btTurnLevelDown.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
int level = Integer.parseInt(tfLevel.getText());
if (level > 1)
tfLevel.setText("" + (level - 1));
} catch (NumberFormatException e) {
}
requestFocus();
}
});
addComponentListener(new ComponentAdapter() {
public void componentResized(ComponentEvent ce) {
plTipBlock.fanning();
}
});
timer = new Timer(500, new ActionListener() {
public void actionPerformed(ActionEvent ae) {
tfScore.setText("" + game.getScore());
int scoreForLevelUpdate =
game.getScoreForLevelUpdate();
if (scoreForLevelUpdate >= ErsBlocksGame.PER_LEVEL_SCORE
&& scoreForLevelUpdate > 0)
game.levelUpdate();
}
});
timer.start();
}
public void setTipStyle(int style) {
plTipBlock.setStyle(style);
}
public int getLevel() {
int level = 0;
try {
level = Integer.parseInt(tfLevel.getText());
} catch (NumberFormatException e) {
}
return level;
}
public void setLevel(int level) {
if (level > 0 && level < 11) tfLevel.setText("" + level);
}
public void setPlayButtonEnable(boolean enable) {
btPlay.setEnabled(enable);
}
public void setPauseButtonLabel(boolean pause) {
btPause.setText(pause ? "暂停" : "继续");
}
public void reset() {
tfScore.setText("0");
plTipBlock.setStyle(0);
}
public void fanning() {
plTipBlock.fanning();
}
private class TipPanel extends JPanel {
private Color backColor = Color.darkGray, frontColor = Color.lightGray;
private ErsBox[][] boxes =
new ErsBox[ErsBlock.BOXES_ROWS][ErsBlock.BOXES_COLS];
private int style, boxWidth, boxHeight;
private boolean isTiled = false;
public TipPanel() {
for (int i = 0; i < boxes.length; i++) {
for (int j = 0; j < boxes[i].length; j++)
boxes[i][j] = new ErsBox(false);
}
}
public TipPanel(Color backColor, Color frontColor) {
this();
this.backColor = backColor;
this.frontColor = frontColor;
}
public void setStyle(int style) {
this.style = style;
repaint();
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (!isTiled) fanning();
int key = 0x8000;
for (int i = 0; i < boxes.length; i++) {
for (int j = 0; j < boxes[i].length; j++) {
Color color = (((key & style) != 0) ? frontColor : backColor);
g.setColor(color);
g.fill3DRect(j * boxWidth, i * boxHeight,
boxWidth, boxHeight, true);
key >>= 1;
}
}
}
/**
* 根据窗口的大小,自动调整方格的尺寸*/
public void fanning() {
boxWidth = getSize().width / ErsBlock.BOXES_COLS;
boxHeight = getSize().height / ErsBlock.BOXES_ROWS;
isTiled = true;
}
}
private class ControlKeyListener extends KeyAdapter {
public void keyPressed(KeyEvent ke) {
if (!game.isPlaying()) return;
ErsBlock block = game.getCurBlock();
switch (ke.getKeyCode()) {
case KeyEvent.VK_DOWN:
block.moveDown();
break;
case KeyEvent.VK_LEFT:
block.moveLeft();
break;
case KeyEvent.VK_RIGHT:
block.moveRight();
break;
case KeyEvent.VK_UP:
block.turnNext();
break;
case KeyEvent.VK_SPACE:
block.moveDownest();
default:
break;
}
}
}
}
class ErsBox implements Cloneable {
private boolean isColor;
private Dimension size = new Dimension();
public ErsBox(boolean isColor) {
this.isColor = isColor;
}
public boolean isColorBox() {
return isColor;
}
public void setColor(boolean isColor) {
this.isColor = isColor;
}
/**
* 得到此方格的尺寸
* @return Dimension,方格的尺寸*/
public Dimension getSize() {
return size;
}
/**
* 设置方格的尺寸
* @param size Dimension,方格的尺寸*/
public void setSize(Dimension size) {
this.size = size;
}
public Object clone() {
Object cloned = null;
try {
cloned = super.clone();
} catch (Exception ex) {
ex.printStackTrace();
}
return cloned;
}
}
//把分给我第一个号哈 谢谢了
热心网友
时间:2022-06-22 03:04
代码怎么能随便公布,都是公司或者个人的财产。
楼主提这个问题,本身就不值得回答。