运行可以,但是并不能鼓吹是一个具有好的风格的代码,。
//文件一
package greedysnake_cx;
public class Node {
int x=0;
int y=0;
int nodewidth;
int nodeheight;
Node(int x,int y){
thisx=x;
thisy=y;
}
}
//文件二
package greedysnake_cx;
/
实现一个greedysnake的模型,具有功能:
1)移动,moveOn()----从director参数中获取方向信息,如果方向定义的下一个点的逻辑值是true,检查是不是food,是则将food添加到
列表的头部,snake继续移动,不是则停止移动(撞到蛇尾巴了)
2)加速,speedUp()----将现成的停滞时间间隔interval按照一定的比率 speedRate进行扩大
3)减速,speedDown()----
该类实现Runnable接口,
/
//定义snake的模型
import javautil;
import javaxswing;
public class SnakeModel implements Runnable {
private GreedSnake gs;
//给每一个矩阵点确立一个boolean值
boolean[][] matrix;
private int maxX;
private int maxY;
//设置一个节点的列表;
LinkedList nodeArray = new LinkedList();
Node food=null;
int direction=UP;
int score=0;
//定义方向
public final static int LEFT=1;
public final static int UP=2;
public final static int RIGHT=3;
public final static int DOWN=4;
private int interval=200; //停顿时间的间隔
boolean pause=false; //定义暂停
private double speedRate=05; //定义速度的变更幅度
//constructor
public SnakeModel(GreedSnake gs,int maxx,int maxy){
thisgs=gs;
thismaxX=maxx;
thismaxY=maxy;
//thismatrix=null;
////////////////////////////////////////////////////////////////////
//init matrix[][];
matrix=new boolean[maxX][]; //不初始化是不行滴
for(int i=0;i<maxX;i++){
matrix[i]=new boolean[maxY];//将矩阵的每一行定义成列的集合
Arraysfill(matrix[i], false);///使用javautilArrays的static方法fill,将matrix[]数组里面的元素全部定义成false
//至此,矩阵里面所有的点的boolean值都是flase
//for(int j=0;j<maxY;j++){
//matrix[i][j]=false;
//}
}
////////////////////////////////////////////////////////////////////
//init nodeArray
int initlength=10;
for(int i=0;i<initlength;i++){
//确保snake出现在屏幕的中央 assure that the greedy snake appears in the center of the model
//snake的长度由maxX来确定
int x=maxX/2+i;
int y=maxY/2;
nodeArrayaddFirst(new Node(x,y));
matrix[x][y]=true;
}
//////////////////////////////////////////////////////////////////////
//创建食物
food=createFood();
Systemoutprintln("some test!");
matrix[foodx][foody]=true;
}//end constructor
//snake动起
public boolean moveOn(){
Node head=(Node)nodeArraygetFirst();
int x=headx;
int y=heady;
switch(direction){
case LEFT:
x--;break;
case UP:
y--;break;
case RIGHT:
x++;break;
case DOWN:
y++;break;
default:
}
if((x >= 0 && x < maxX) && (y >= 0 && y < maxY)){
if(matrix[x][y]){//当蛇头转至一个bool值为true的点时
if(x==foodx&&y==foody){//该点是食物
nodeArrayaddFirst(food);
//吃掉补上
food=createFood();
matrix[foodx][foody]=true;
score+=10;
return true;
}
else //该点不是食物,(蛇尾巴)
return false;
}
else{
nodeArrayaddFirst(new Node(x,y));
matrix[x][y]=true;
Node nn=(Node)nodeArrayremoveLast();//移除并且返回列表中的最后一个元素
matrix[nnx][nny]=false;
return true;
}
}
return false;
}//end moveOn
public void run() {
boolean running=true;
while(running){
try{
Threadsleep(interval);
}
catch(InterruptedException e){
eprintStackTrace();
}
if(!pause){
if(moveOn()){
gsrepaint();
}
else{
JOptionPaneshowMessageDialog(null, "sorry myboy,GAME OVER!", "message", JOptionPaneINFORMATION_MESSAGE);
running=false;
}
}
}
/boolean running=true;
while(running){
try{
Threadsleep(interval);
}
catch (InterruptedException e){
eprintStackTrace();
}
if(!pause){
if(moveOn()){
gsrepaint();
}
else{
JOptionPaneshowMessageDialog(null,"i am sorry ,you failed!","message",JOptionPaneINFORMATION_MESSAGE);
break;
}
}
}//end while
running=false;//当且仅当失败退出的时候;
/
}
//获取当前游戏得分
public int getScore(){
return thisscore;
}
//加速
public void speedUp(){
interval=speedRate;
}
//减速
public void speedDown(){
interval/=speedRate;
}
//设置暂停
public void chagePause(){
pause=!pause;
}
//设置方向
public void chageDirection(int newdirection){
if(direction % 2 != newdirection % 2){
direction=newdirection;
}
}
//生成食物
private Node createFood() {
/
创建一个随机数的生成器,这个是javautilRandom类
与javalangMath类中的random()方法有不一样的地方,彼方法返回一个0-1之间的随机数
/
Random random=new Random();
int foodx=randomnextInt(maxX);
int foody=randomnextInt(maxY);
Node food=new Node(foodx,foody);
return food;
}
}
//文件三
package greedysnake_cx;
/
在repaint()方法中,绘画上下文对象是从canvas对象使用getContentPane()获取的!!
/
import javaxswing;
import javaawt;
import javaawtevent;
import javautil;
public class GreedSnake implements KeyListener{
Canvas canvas;
private JLabel jlabel;
private JPanel jpanel;
private JFrame jframe;
SnakeModel snakemodel;
private final static int canvaswidth=400;
private final static int canvasheight=300;
private final static int nodewidth=10;
private final static int nodeheight=10;
//construction
GreedSnake(){
jframe=new JFrame("The Greed Sanke!");
jframesetLayout(new BorderLayout());
Container cp=jframegetContentPane();
//在jframe面板中添加各种组件
jlabel=new JLabel("welcome");
jlabelsetText("Welcome my friend! Enjoy your self!");
cpadd(jlabel,BorderLayoutNORTH);
canvas=new Canvas();
canvassetSize(canvaswidth,canvasheight);
canvasaddKeyListener(this); //给空白面板添加键盘时间监听器!
cpadd(canvas,BorderLayoutCENTER);
jpanel=new JPanel();
jpanelsetLayout(new BorderLayout());
JLabel label=new JLabel("Pass enter or 'r' or 's' to start",JLabelCENTER);
jpaneladd(label,BorderLayoutNORTH);
JLabel label2=new JLabel("Pass space to pause this game!",JLabelCENTER);
jpaneladd(label2,BorderLayoutCENTER);
JLabel label3=new JLabel("Pass pageUp or pageDown to up or down the speed of the snake!",JLabelCENTER);
jpaneladd(label3,BorderLayoutSOUTH);
cpadd(jpanel,BorderLayoutSOUTH);
//给顶层容器设置时间监听、可视化、关闭按钮的设定
jframeaddKeyListener(this);
jframepack();
jframesetVisible(true);
jframesetResizable(false);
jframesetDefaultCloseOperation(JFrameEXIT_ON_CLOSE);
begin();
}//end construction
public void begin(){
//开启一个SnakeModel的进程,并且开始改进程
snakemodel=new SnakeModel(this,canvaswidth/nodewidth,canvasheight/nodeheight);
(new Thread(snakemodel))start();
}
void repaint(){
int score=snakemodelgetScore();
jlabelsetText("您的得分是:"+score);
Graphics g=canvasgetGraphics();///pay attention!
gsetColor(Colorwhite);
gfillRect(0, 0, canvaswidth, canvasheight);
gsetColor(Colorblue);
LinkedList list=snakemodelnodeArray;
for(int i=0;i<listsize();i++){
Node nn=(Node)listget(i);
paintingNode(g,nn);
}
//绘制food
gsetColor(Colorgreen);
Node foodnode=new Node(snakemodelfoodx,snakemodelfoody);
paintingNode(g,foodnode);
}
public void paintingNode(Graphics gg,Node n){
/
使用Graphics 的fillRect方法,填充一个矩形,
矩形的起点需要乘以一个NODE的长宽,以避免重叠
/
ggfillRect(nxnodewidth, nynodeheight,nodewidth-1,nodeheight-1);
}
public void keyPressed(KeyEvent e) {//按下某一个键时,调用此方法
int keycode=egetKeyCode();
/ if(keycode==KeyEventVK_ENTER||keycode==KeyEventVK_R){
begin();
}/
switch(keycode){
case KeyEventVK_LEFT:
snakemodelchageDirection(SnakeModelLEFT);
break;
case KeyEventVK_UP:
snakemodelchageDirection(SnakeModelUP);
break;
case KeyEventVK_RIGHT:
snakemodelchageDirection(SnakeModelRIGHT);
break;
case KeyEventVK_DOWN:
snakemodelchageDirection(SnakeModelDOWN);
break;
case KeyEventVK_PAGE_DOWN:
snakemodelspeedDown();
break;
case KeyEventVK_PAGE_UP:
snakemodelspeedUp();
break;
case KeyEventVK_ENTER:
case KeyEventVK_R:
begin();
break;
case KeyEventVK_SPACE:
case KeyEventVK_P:
snakemodelchagePause();
default:
}//end switch
}//end keyPressed
public void keyReleased(KeyEvent e) {//释放某一个键时,调用此方法
}
public void keyTyped(KeyEvent e) {//键入某一个键时,调用此方法!
}
//main
public static void main(String[] args){
GreedSnake gs=new GreedSnake();
}
}自己写着玩的,很简单,你试一试哦
主要用了javaxswingTimer这个类:
import javaawt;
import javaxswing;
@SuppressWarnings("serial")
public class MainClass extends JFrame {
ControlSnake control;
Toolkit kit;
Dimension dimen;
public static void main(String[] args) {
new MainClass("my snake");
}
public MainClass(String s) {
super(s);
control = new ControlSnake();
controlsetFocusable(true);
kit = ToolkitgetDefaultToolkit();
dimen = kitgetScreenSize();
add(control);
setLayout(new BorderLayout());
setLocation(dimenwidth / 3, dimenheight / 3);// dimenwidth/3,dimenheight/3
setSize(FWIDTH, FHEIGHT);
setDefaultCloseOperation(JFrameEXIT_ON_CLOSE);
setResizable(false);
setVisible(true);
}
public static final int FWIDTH = 315;
public static final int FHEIGHT = 380;
}
import javautil;
import javaawt;
import javaawtevent;
import javaxswing;
import javaxswingTimer;
import javautilRandom;
@SuppressWarnings("serial")
public class ControlSnake extends JPanel implements ActionListener {
Random rand;
ArrayList<Point> list, listBody;
String str, str1;
static boolean key;
int x, y, dx, dy, fx, fy, flag;
int snakeBody;
int speed;
public ControlSnake() {
snakeBody = 1;
str = "上下左右方向键控制 P键暂停";
str1 = "现在的长度为:" + snakeBody;
key = true;
flag = 1;
speed = 700;
rand = new Random();
list = new ArrayList<Point>();
listBody = new ArrayList<Point>();
x = 5;
y = 5;
listadd(new Point(x, y));
listBodyadd(listget(0));
dx = 10;
dy = 0;
fx = randnextInt(30) 10 + 5;// 2
fy = randnextInt(30) 10 + 5;// 2
setBackground(ColorWHITE);
setSize(new Dimension(318, 380));
final Timer time = new Timer(speed, this);
timestart();
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if (egetKeyCode() == 37) {
dx = -10;
dy = 0;
} else if (egetKeyCode() == 38) {
dx = 0;
dy = -10;
} else if (egetKeyCode() == 39) {
dx = 10;
dy = 0;
} else if (egetKeyCode() == 40) {
dx = 0;
dy = 10;
} else if (egetKeyCode() == 80) {
if (flag % 2 == 1) {
timestop();
}
if (flag % 2 == 0) {
timestart();
}
flag++;
}
}
});
}
public void paint(Graphics g) {
gsetColor(ColorWHITE);
gfillRect(0, 0, 400, 400);
gsetColor(ColorDARK_GRAY);
gdrawLine(3, 3, 305, 3);
gdrawLine(3, 3, 3, 305);
gdrawLine(305, 3, 305, 305);
gdrawLine(3, 305, 305, 305);
gsetColor(ColorPINK);
for (int i = 0; i < listBodysize(); i++) {
gfillRect(listBodyget(i)x, listBodyget(i)y, 9, 9);
}
gfillRect(x, y, 9, 9);
gsetColor(ColorORANGE);
gfillRect(fx, fy, 9, 9);
gsetColor(ColorDARK_GRAY);
str1 = "现在的长度为:" + snakeBody;
gdrawString(str, 10, 320);
gdrawString(str1, 10, 335);
}
public void actionPerformed(ActionEvent e) {
x += dx;
y += dy;
if (makeOut() == false) {
JOptionPaneshowMessageDialog(null, "重新开始");
speed = 700;
snakeBody = 1;
x = 5;
y = 5;
listclear();
listadd(new Point(x, y));
listBodyclear();
listBodyadd(listget(0));
dx = 10;
dy = 0;
}
addPoint(x, y);
if (x == fx && y == fy) {
speed = (int) (speed 08);//速度增加参数
if (speed < 200) {
speed = 100;
}
fx = randnextInt(30) 10 + 5;// 2
fy = randnextInt(30) 10 + 5;// 2
snakeBody++;// 2
} // 2
repaint();
}
public void addPoint(int xx, int yy) {
// 动态的记录最新发生的50步以内的移动过的坐标
// 并画出最新的snakeBody
if (listsize() < 100) {//蛇身长度最长为100
listadd(new Point(xx, yy));
} else {
listremove(0);
listadd(new Point(xx, yy));
}
if (snakeBody == 1) {
listBodyremove(0);
listBodyadd(0, listget(listsize() - 1));
} else {
listBodyclear();
if (listsize() < snakeBody) {
for (int i = listsize() - 1; i > 0; i--) {
listBodyadd(listget(i));
}
} else {
for (int i = listsize() - 1; listBodysize() < snakeBody; i--) {
listBodyadd(listget(i));
}
}
}
}
public boolean makeOut() {
if ((x < 3 || y < 3) || (x > 305 || y > 305)) {
return false;
}
for (int i = 0; i < listBodysize() - 1; i++) {
for (int j = i + 1; j < listBodysize(); j++) {
if (listBodyget(i)equals(listBodyget(j))) {
return false;
}
}
}
return true;
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)