微信小游戏贪吃蛇源码(微信小程序贪吃蛇怎么玩)
本文目录一览:
- 1、求"贪吃蛇"小游戏JAVA源代码一份
- 2、用mfc设计贪吃蛇游戏源代码,最好有解析
- 3、贪吃蛇游戏的源代码
- 4、求贪吃蛇的程序代码(c语言)
- 5、求一个C++的贪吃蛇游戏源代码,要标注解释的。
- 6、求一段JAVA编写的贪吃蛇小程序源代码
求"贪吃蛇"小游戏JAVA源代码一份
贪吃蛇
import java.awt.*;
import java.awt.event.*;
public class GreedSnake //主类
{
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new MyWindow();
}
}
class MyPanel extends Panel implements KeyListener,Runnable//自定义面板类,继承了键盘和线程接口
{
Button snake[]; //定义蛇按钮
int shu=0; //蛇的节数
int food[]; //食物数组
boolean result=true; //判定结果是输 还是赢
Thread thread; //定义线程
static int weix,weiy; //食物位置
boolean t=true; //判定游戏是否结束
int fangxiang=0; //蛇移动方向
int x=0,y=0; //蛇头位置
MyPanel()
{
setLayout(null);
snake=new Button[20];
food=new int [20];
thread=new Thread(this);
for(int j=0;j20;j++)
{
food[j]=(int)(Math.random()*99);//定义20个随机食物
}
weix=(int)(food[0]*0.1)*60; //十位*60为横坐标
weiy=(int)(food[0]%10)*40; //个位*40为纵坐标
for(int i=0;i20;i++)
{
snake[i]=new Button();
}
add(snake[0]);
snake[0].setBackground(Color.black);
snake[0].addKeyListener(this); //为蛇头添加键盘监视器
snake[0].setBounds(0,0,10,10);
setBackground(Color.cyan);
}
public void run() //接收线程
{
while(t)
{
if(fangxiang==0)//向右
{
try
{
x+=10;
snake[0].setLocation(x, y);//设置蛇头位置
if(x==weixy==weiy) //吃到食物
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint(); //重绘下一个食物
add(snake[shu]); //增加蛇节数和位置
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100); //睡眠100ms
}
catch(Exception e){}
}
else if(fangxiang==1)//向左
{
try
{
x-=10;
snake[0].setLocation(x, y);
if(x==weixy==weiy)
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint();
add(snake[shu]);
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100);
}
catch(Exception e){}
}
else if(fangxiang==2)//向上
{
try
{
y-=10;
snake[0].setLocation(x, y);
if(x==weixy==weiy)
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint();
add(snake[shu]);
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100);
}
catch(Exception e){}
}
else if(fangxiang==3)//向下
{
try
{
y+=10;
snake[0].setLocation(x, y);
if(x==weixy==weiy)
{
shu++;
weix=(int)(food[shu]*0.1)*60;
weiy=(int)(food[shu]%10)*40;
repaint();
add(snake[shu]);
snake[shu].setBounds(snake[shu-1].getBounds());
}
thread.sleep(100);
}
catch(Exception e){}
}
int num1=shu;
while(num11)//判断是否咬自己的尾巴
{
if(snake[num1].getBounds().x==snake[0].getBounds().xsnake[num1].getBounds().y==snake[0].getBounds().y)
{
t=false;
result=false;
repaint();
}
num1--;
}
if(x0||x=this.getWidth()||y0||y=this.getHeight())//判断是否撞墙
{
t=false;
result=false;
repaint();
}
int num=shu;
while(num0) //设置蛇节位置
{
snake[num].setBounds(snake[num-1].getBounds());
num--;
}
if(shu==15) //如果蛇节数等于15则胜利
{
t=false;
result=true;
repaint();
}
}
}
public void keyPressed(KeyEvent e) //按下键盘方向键
{
if(e.getKeyCode()==KeyEvent.VK_RIGHT)//右键
{
if(fangxiang!=1)//如果先前方向不为左
fangxiang=0;
}
else if(e.getKeyCode()==KeyEvent.VK_LEFT)
{ if(fangxiang!=0)
fangxiang=1;
}
else if(e.getKeyCode()==KeyEvent.VK_UP)
{ if(fangxiang!=3)
fangxiang=2;
}
else if(e.getKeyCode()==KeyEvent.VK_DOWN)
{ if(fangxiang!=2)
fangxiang=3;
}
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
public void paint(Graphics g) //在面板上绘图
{
int x1=this.getWidth()-1;
int y1=this.getHeight()-1;
g.setColor(Color.red);
g.fillOval(weix, weiy, 10, 10);//食物
g.drawRect(0, 0, x1, y1); //墙
if(t==falseresult==false)
g.drawString("GAME OVER!", 250, 200);//输出游戏失败
else if(t==falseresult==true)
g.drawString("YOU WIN!", 250, 200);//输出游戏成功
}
}
class MyWindow extends Frame implements ActionListener//自定义窗口类
{
MyPanel my;
Button btn;
Panel panel;
MyWindow()
{
super("GreedSnake");
my=new MyPanel();
btn=new Button("begin");
panel=new Panel();
btn.addActionListener(this);
panel.add(new Label("begin后请按Tab键选定蛇"));
panel.add(btn);
panel.add(new Label("按上下左右键控制蛇行动"));
add(panel,BorderLayout.NORTH);
add(my,BorderLayout.CENTER);
setBounds(100,100,610,500);
setVisible(true);
validate();
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
public void actionPerformed(ActionEvent e)//按下begin按钮
{
if(e.getSource()==btn)
{
try
{
my.thread.start(); //开始线程
my.validate();
}
catch(Exception ee){}
}
}
}
用mfc设计贪吃蛇游戏源代码,最好有解析
1.算法
1. 首先,用一个结构体数组来标记蛇的X位置和Y位置,还有每一节的方向。用一变量标识蛇的长度。
2. 在蛇非转弯的移动时用定时器来自动移动,不管蛇是哪种形状,都只需在每次移动时先将各节向后移动(蛇尾舍弃,新的蛇尾由蛇尾的上一节代替):如蛇本身为snake[0]到snake[3],就是将snake[0]到snake[2]一起移动到snake[1]到snake[3]: 将 snake[2]的XY坐标赋值snake[3]的XY坐标 ,snake[1]的XY坐标 赋值给snake[2]的XY坐标 ,snake[0]的XY坐标 赋值给snake[1]的XY坐标 。再判断蛇头的方向,然后将蛇头顺着这个方向向前移动一格就是蛇头snake[0]的XY坐标 。而蛇除蛇头外各节的方向由函数SetDirection()来确定(明显此种情况,蛇头的方向不变),SetDirection()的思想是根据蛇的每一节的前一节的相对位置来确定本节的方向。(其实这个函数是多余的,真正用到的只有蛇头的方向)。
3. 蛇在转弯时,也是各节一次向后移,蛇头的位置顺着转弯的方向移动,方向由转弯方向确定。
4. 蛇在吃到食物时,长度加一,蛇头的位置变成食物的位置,方向不变。蛇的本身每节的XY位置都向后移。如蛇本身为snake[0]到snake[3], 就是将snake[0]到snake[3]一起移动到snake[1]到snake[4]。
5. 基于对话框的应用程序,响应按键消息需在PreTranslateMessage里,而不是像文档视图模式那样在OnKeyDown里响应。
6. 每次蛇在转弯时只能有一种方向按键能响应,即要么左右转,要么上下转。蛇头方向向左或向右时,只能上下转微信小游戏贪吃蛇源码;蛇头方向向上或向下时,只能左右转。
7. 食物的位置由rand函数随机产生。
2.添加如下函数和变量
1 void HuaFangGe(int bianChang, int gridShumu); //如在400*400的方格里绘制20*20个格子,则bianChang = 400;gridShumu = 20;
2 void InitSnackSite(); //初始化蛇的位置
3
4 int snakeLength; //表示蛇的长度
5 int foodX; //食物的X位置
6 int foodY; //食物的Y位置
7 bool start; //标志是否开始
8 bool reStart; //标志是否重新开始
9
10 struct SNAKE
11 {
12 int x;
13 int y;
14 char direction; //某位置的方向为前一个位置相对于该位置的方向,由SetDirection()确定
15 }snake[200];
16
17 void DrawRed(int x, int y); //指定点0*0到20*20,画相应颜色,下同(红头绿身蓝尾)
18 void DrawGreen(int x, int y);
19 void DrawBlue(int x, int y);
20 void DrawBlack(int x, int y); //根据SetFoodXY()所确定的foodX和foodY来画食物。
21
22 void DrawSnakeFood(); //根据数组snakeSite数组的标识信息类绘制蛇的形状位置颜色。
23 void SetFoodXY(); //随机绘制食物的XY位置
24
25 bool leftRight; //确定是否能上下走(蛇本身在上下走,再按上下就无用微信小游戏贪吃蛇源码了)
26 bool upDown; //确定是否能左右走(蛇本身在左右走,再按左右就无用了)
27
28 void MoveSite(); //蛇移动过程中,设置“除蛇头”外各节的x和y的位置,顺序前移。
29 void SetDirection(); //蛇移动过程中,设置“除蛇头”外各节的方向
30
31 void TurnLeft(); //当蛇左转时
32 void TurnRight(); //当蛇右转时
33 void GoUp(); //当蛇向上时
34 void GoDown(); //当蛇向下时
可以参考这里:
【原创】基于MFC的 贪吃蛇 小游戏的实现,附源码下载
贪吃蛇游戏的源代码
?
贪吃蛇源码:
!doctype html
html
body style='overflow:hidden'
canvas id="can" width="400" height="400" style="background:Black;display: block;margin:20px auto;"/canvas
script
var sn = [ 42, 41 ], dz = 43, fx = 1, n, ctx = document.getElementById("can").getContext("2d");
function draw(t, c) {
ctx.fillStyle = c;
ctx.fillRect(t % 20 * 20 + 1, ~~(t / 20) * 20 + 1, 18, 18);
}
document.onkeydown = function(e) {
fx = sn[1] - sn[0] == (n = [ -1, -20, 1, 20 ][(e || event).keyCode - 37] || fx) ? fx : n
};
!function() {
sn.unshift(n = sn[0] + fx);
if (sn.indexOf(n, 1) 0 || n0||n399 || fx == 1 n % 20 == 0 || fx == -1 n % 20 == 19)
return alert("GAME OVER");
draw(n, "Lime");
if (n == dz) {
while (sn.indexOf(dz = ~~(Math.random() * 400)) = 0);
draw(dz, "Yellow");
} else
draw(sn.pop(), "Black");
setTimeout(arguments.callee, 130);
}();
/script
/body
/html
求贪吃蛇的程序代码(c语言)
贪吃蛇游戏的代码
#define N 200
#include graphics.h
#include stdlib.h
#include dos.h
#define LEFT 0x4b00
#define RIGHT 0x4d00
#define DOWN 0x5000
#define UP 0x4800
#define ESC 0x011b
int i,key;
int score=0;/*得分*/
int gamespeed=50000;/*游戏速度自己调整*/
struct Food
{
int x;/*食物的横坐标*/
int y;/*食物的纵坐标*/
int yes;/*判断是否要出现食物的变量*/
}food;/*食物的结构体*/
struct Snake
{
int x[N];
int y[N];
int node;/*蛇的节数*/
int direction;/*蛇移动方向*/
int life;/* 蛇的生命,0活着,1死亡*/
}snake;
void Init(void);/*图形驱动*/
void Close(void);/*图形结束*/
void DrawK(void);/*开始画面*/
void GameOver(void);/*结束游戏*/
void GamePlay(void);/*玩游戏具体过程*/
void PrScore(void);/*输出成绩*/
/*主函数*/
void main(void)
{
Init();/*图形驱动*/
DrawK();/*开始画面*/
GamePlay();/*玩游戏具体过程*/
Close();/*图形结束*/
}
/*图形驱动*/
void Init(void)
{
int gd=DETECT,gm;
initgraph(gd,gm,"c:\\tc");
cleardevice();
}
/*开始画面,左上角坐标为(50,40),右下角坐标为(610,460)的围墙*/
void DrawK(void)
{
/*setbkcolor(LIGHTGREEN);*/
setcolor(11);
setlinestyle(SOLID_LINE,0,THICK_WIDTH);/*设置线型*/
for(i=50;i=600;i+=10)/*画围墙*/
{
rectangle(i,40,i+10,49); /*上边*/
rectangle(i,451,i+10,460);/*下边*/
}
for(i=40;i=450;i+=10)
{
rectangle(50,i,59,i+10); /*左边*/
rectangle(601,i,610,i+10);/*右边*/
}
}
/*玩游戏具体过程*/
void GamePlay(void)
{
randomize();/*随机数发生器*/
food.yes=1;/*1表示需要出现新食物,0表示已经存在食物*/
snake.life=0;/*活着*/
snake.direction=1;/*方向往右*/
snake.x[0]=100;snake.y[0]=100;/*蛇头*/
snake.x[1]=110;snake.y[1]=100;
snake.node=2;/*节数*/
PrScore();/*输出得分*/
while(1)/*可以重复玩游戏,压ESC键结束*/
{
while(!kbhit())/*在没有按键的情况下,蛇自己移动身体*/
{
if(food.yes==1)/*需要出现新食物*/
{
food.x=rand()%400+60;
food.y=rand()%350+60;
while(food.x%10!=0)/*食物随机出现后必须让食物能够在整格内,这样才可以让蛇吃到*/
food.x++;
while(food.y%10!=0)
food.y++;
food.yes=0;/*画面上有食物了*/
}
if(food.yes==0)/*画面上有食物了就要显示*/
{
setcolor(GREEN);
rectangle(food.x,food.y,food.x+10,food.y-10);
}
for(i=snake.node-1;i0;i--)/*蛇的每个环节往前移动,也就是贪吃蛇的关键算法*/
{
snake.x[i]=snake.x[i-1];
snake.y[i]=snake.y[i-1];
}
/*1,2,3,4表示右,左,上,下四个方向,通过这个判断来移动蛇头*/
switch(snake.direction)
{
case 1:snake.x[0]+=10;break;
case 2: snake.x[0]-=10;break;
case 3: snake.y[0]-=10;break;
case 4: snake.y[0]+=10;break;
}
for(i=3;isnake.node;i++)/*从蛇的第四节开始判断是否撞到自己了,因为蛇头为两节,第三节不可能拐过来*/
{
if(snake.x[i]==snake.x[0]snake.y[i]==snake.y[0])
{
GameOver();/*显示失败*/
snake.life=1;
break;
}
}
if(snake.x[0]55||snake.x[0]595||snake.y[0]55||
snake.y[0]455)/*蛇是否撞到墙壁*/
{
GameOver();/*本次游戏结束*/
snake.life=1; /*蛇死*/
}
if(snake.life==1)/*以上两种判断以后,如果蛇死就跳出内循环,重新开始*/
break;
if(snake.x[0]==food.xsnake.y[0]==food.y)/*吃到食物以后*/
{
setcolor(0);/*把画面上的食物东西去掉*/
rectangle(food.x,food.y,food.x+10,food.y-10);
snake.x[snake.node]=-20;snake.y[snake.node]=-20;
/*新的一节先放在看不见的位置,下次循环就取前一节的位置*/
snake.node++;/*蛇的身体长一节*/
food.yes=1;/*画面上需要出现新的食物*/
score+=10;
PrScore();/*输出新得分*/
}
setcolor(4);/*画出蛇*/
for(i=0;isnake.node;i++)
rectangle(snake.x[i],snake.y[i],snake.x[i]+10,
snake.y[i]-10);
delay(gamespeed);
setcolor(0);/*用黑色去除蛇的的最后一节*/
rectangle(snake.x[snake.node-1],snake.y[snake.node-1],
snake.x[snake.node-1]+10,snake.y[snake.node-1]-10);
} /*endwhile(!kbhit)*/
if(snake.life==1)/*如果蛇死就跳出循环*/
break;
key=bioskey(0);/*接收按键*/
if(key==ESC)/*按ESC键退出*/
break;
else
if(key==UPsnake.direction!=4)
/*判断是否往相反的方向移动*/
snake.direction=3;
else
if(key==RIGHTsnake.direction!=2)
snake.direction=1;
else
if(key==LEFTsnake.direction!=1)
snake.direction=2;
else
if(key==DOWNsnake.direction!=3)
snake.direction=4;
}/*endwhile(1)*/
}
/*游戏结束*/
void GameOver(void)
{
cleardevice();
PrScore();
setcolor(RED);
settextstyle(0,0,4);
outtextxy(200,200,"GAME OVER");
getch();
}
/*输出成绩*/
void PrScore(void)
{
char str[10];
setfillstyle(SOLID_FILL,YELLOW);
bar(50,15,220,35);
setcolor(6);
settextstyle(0,0,2);
sprintf(str,"score:%d",score);
outtextxy(55,20,str);
}
/*图形结束*/
void Close(void)
{
getch();
closegraph();
}
程序结束,请采纳
求一个C++的贪吃蛇游戏源代码,要标注解释的。
/*因为当时只考虑到微信小游戏贪吃蛇源码了代码可通过微信小游戏贪吃蛇源码,没有考虑代码的质量微信小游戏贪吃蛇源码,所以重复利用率差微信小游戏贪吃蛇源码,不要随意改动哦
运行是完全通过的但是会一闪一闪的*/
#includeiostream
#includeconio.h
#includetime.h
#includewindows.h
#define X 15
#define Y 15
int score=0;
char ch[X][Y];
char lch = 's';
char nch = 's';
class Snake
{
public:
Snake() { nx = 8;ny = 8;lx = 9;ly = 9;next = NULL; }
Snake(Snaker);//建立蛇身
void input();//把数据输入到图像
void control();//控制贪吃蛇
void show();//显示图像
void check();//检测食物是否被吃掉
bool gameover();//检测游戏是否结束
int nx;
int ny;
int lx;
int ly;
Snake*next;
};
Snake *head;
namespace Food
{
int x;
int y;
void NEW()
{
Snake*p=head;
x = rand() % X;
y = rand() % Y;
while(p!=NULL)
{
if(p-nx==xp-ny==y)
{
x = rand() % X;
y = rand() % Y;
p = head;
}
else
p=p-next;
}
ch[x][y]='$';
}
};
Snake::Snake(Snaker)
{
this-nx = r.lx;
this-ny = r.ly;
r.next = this;
this-next = NULL;
}
void Snake::show()//显示图像
{
system("cls");
//std::cout " ------------------------------ \n";
for (int y = 0; yY; ++y)
{
//std::cout "|";
for (int x = 0; x X; ++x)
std::cerr ch[x][y] " " ;
std::cerr "|" std::endl;
}
std::cout " ------------------------------ \n";
printf("x = %d,y = %d\n",nx,ny);
printf("x = %0X,y = %0X\n",nx,ny);
printf("score = %d\n",score);
}
void Snake::control()//键盘控制
{
if (_kbhit() == 1)
{
nch = _getch();
lx = nx;
ly = ny;
if (nch == 'w' || nch == 's' || nch == 'a' || nch == 'd')
{
lch = nch;
switch (nch)
{
case 'w':if (ny == 0) ny = Y - 1; else --ny; break;
case 's':if (ny == Y - 1) ny = 0; else ++ny; break;
case 'a':if (nx == 0) nx = X - 1; else --nx; break;
case 'd':if (nx == X - 1) nx = 0; else ++nx; break;
}
}
else
{
switch (lch)
{
case 'w':if (ny == 0) ny = Y - 1; else --ny; break;
case 's':if (ny == Y - 1) ny = 0; else ++ny; break;
case 'a':if (nx == 0) nx = X - 1; else --nx; break;
case 'd':if (nx == X - 1) nx = 0; else ++nx; break;
}
}
}
else
{
lx = nx;
ly = ny;
if (nch == 'w' || nch == 's' || nch == 'a' || nch == 'd')
{
lch = nch;
switch (nch)
{
case 'w':if (ny == 0) ny = Y - 1; else --ny; break;
case 's':if (ny == Y - 1) ny = 0; else ++ny; break;
case 'a':if (nx == 0) nx = X - 1; else --nx; break;
case 'd':if (nx == X - 1) nx = 0; else ++nx; break;
}
}
else
{
switch (lch)
{
case 'w':if (ny == 0) ny = Y - 1; else --ny; break;
case 's':if (ny == Y - 1) ny = 0; else ++ny; break;
case 'a':if (nx == 0) nx = X - 1; else --nx; break;
case 'd':if (nx == X - 1) nx = 0; else ++nx; break;
}
}
}
}
void Snake::input()//把对象输入到图像
{
Snake*p = head;
ch[p-lx][p-ly] = ' ';
ch[p-nx][p-ny] = '*';
while (p-next != NULL)
{
p-next-lx = p-next-nx;
p-next-ly = p-next-ny;
p-next-nx = p-lx;
p-next-ny = p-ly;
p = p-next;
ch[p-lx][p-ly] = ' ';
ch[p-nx][p-ny] = '*';
}
}
void Snake::check()//检测食物是否被吃掉
{
Snake*p=head;
if (p-nx == Food::xp-ny == Food::y)
{
Snake*p = head;
while (p-next != NULL)
{
p = p-next;
}
p-next = new Snake(*p);
Food::NEW();
++score;
}
}
bool Snake::gameover()//检测游戏是否结束
{
Snake*p = head;
Snake*pn = head-next;
while (p != NULL)
{
while (pn != NULL)
{
if (p-nx == pn-nxp-ny == pn-ny)
{
std::cout "Game Over\n";
return true;
}
pn = pn-next;
}
p = p-next;
}
return 0;
}
int main()
{
//初始化
srand(time(NULL));
for (int y = 0; yY; ++y)
for (int x = 0; xX; ++x)
ch[x][y] = ' ';
head = new Snake;
Food::NEW();
std::cout"游戏规则:\n1.wsad(小写)控制蛇\n2.若蛇节数超过2,那么无法反方向运动,\n若反方向运动则GameOver\n3.'*'为蛇,'$'为食物\n";
system("pause");
//开始游戏
while (1)
{
head-control();
head-input();
head-check();
if(head-gameover())
break;
head-show();
Sleep(100);
}
Sleep(1000);
system("pause");
return 0;
}
/*------------------------------------------------------------------------------------
当然你也可以用下面这个,经过一些奇怪的算法,当然可读性极差,不闪,但是有时有些莫名其妙的bug的,这是把输出图像变成了一个一维数组,用一维数组来模拟直角坐标系
------------------------------------------------------------------------------------*/
#includeiostream
#includewindows.h
#includeconio.h
#includetime.h
#define X 32
#define Y 17
char ch[544];
char nch = 's';
char lch = 's';
int score = 0;
class Snake
{
public:
Snake();//创建蛇头
void Add();//添加蛇身
void Show();//显示图像
bool GameOver();//检测游戏是否结束
void Input();//输入数据
void Check();//检测食物是否被吃
void Control();//输入控制
void INIT();
int GetX(){return nx;}
int GetY(){return ny;}
Snake *next;
private:
int lx;
int ly;
int nx;
int ny;
};
Snake*head;
Snake*finally;
namespace Food
{
int x;
int y;
void GetXY()
{
std::cout"Food x = "x"Food y = "y"\n";
}
void NEW()
{
Snake*p=head;
x = (rand()%15)+1;
y = (rand()%15)+1;
while(p!=NULL)
{
if(p-GetX()==xp-GetY()==y)
{
x = (rand()%15)+1;
y = (rand()%15)+1;
p=head;
}
p=p-next;
}
ch[y*32+x*2-1]='$';
}
};
void Snake :: INIT()//初始化
{
for(int n=0;n=543;++n)
ch[n]=' ';
for(int n=1;n30;++n)
ch[n]='-';
for(int n=1;n30;++n)
ch[n+512]='-';
for(int n=0;n=16;++n)
ch[n*32+31]='\n';
for(int n=1;n=16;++n)
ch[n*32+30]='|';
for(int n=1;n=16;++n)
ch[n*32]='|';
ch[543]='\0';
next=NULL;
Food::NEW();
lx = 4;
ly = 4;
nx = 4;
ny = 5;
ch[ly*32+lx*2-1]='*';
}
Snake :: Snake()//创建蛇头head
{
}
void Snake :: Add()//添加蛇身
{
finally-next = new Snake;
finally-next-nx=finally-lx;
finally-next-ny=finally-ly;
finally-next-next=NULL;
finally=finally-next;
}
void Snake :: Control()//控制输入
{
if(kbhit()==1){
nch=getch();
if(nch=='w'||nch=='s'||nch=='a'||nch=='d'){
lch=nch;
switch(nch)
{
case 'w':if(ny==1) ny=15;else ny--;break;
case 's':if(ny==15) ny=1;else ny++;break;
case 'a':if(nx==1) nx=15;else nx--;break;
case 'd':if(nx==15) nx=1;else nx++;break;
}
}else{
switch(lch)
{
case 'w':if(ny==1) ny=15;else ny--;break;
case 's':if(ny==15) ny=1;else ny++;break;
case 'a':if(nx==1) nx=15;else nx--;break;
case 'd':if(nx==15) nx=1;else nx++;break;
}
}
}else{
switch(lch)
{
case 'w':if(ny==1) ny=15;else ny--;break;
case 's':if(ny==15) ny=1;else ny++;break;
case 'a':if(nx==1) nx=15;else nx--;break;
case 'd':if(nx==15) nx=1;else nx++;break;
}
}
}
void Snake :: Show()//显示图像
{
std::cerrch"\nscore = "score"\t";
}
void Snake :: Input()//输入数据
{
Snake*p = head;
ch[(p-lx)*2+(p-ly)*32-1] = ' ';
ch[(p-nx)*2+(p-ny)*32-1] = '*';
while (p-next != NULL)
{
p-next-lx = p-next-nx;
p-next-ly = p-next-ny;
p-next-nx = p-lx;
p-next-ny = p-ly;
p = p-next;
ch[(p-lx)*2+(p-ly)*32-1] = ' ';
ch[(p-nx)*2+(p-ny)*32-1] = '*';
}
head-lx=head-nx;
head-ly=head-ny;
}
bool Snake :: GameOver()//检测游戏是否结束
{
Snake *p = head;
Snake *pl ;
while(p!=NULL)
{
pl=p-next;
while(pl!=NULL)
{
if(p-nx==pl-nxp-ny==pl-ny){
std::cout"\nGameOver\n";
return true;
}
pl=pl-next;
}
p=p-next;
}
return false;
}
void Snake :: Check()//检测食物是否被吃掉
{
if(head-nx==Food::xhead-ny==Food::y)
{
Food::NEW();
head-Add();
score++;
}
}
int main(int argc,char *argv[])
{
srand(time(NULL));
head=new Snake;
head-INIT();
finally = head;
while(1)
{
head-Control();//控制输出
head-Input();//输入数据
system("cls");
head-Show();//显示图像
Sleep(150);
if(head-GameOver())//检测游戏是否结束
break;
head-Check();//检测食物是否被吃
}
Sleep(1000);
printf("请按任意键退出\n");
_getch();
return 0;
}
求一段JAVA编写的贪吃蛇小程序源代码
用MVC方式实现的贪吃蛇游戏,共有4个类。运行GreedSnake运行即可。主要是观察者模式的使用,我已经添加了很多注释了。
1、
/*
* 程序名称:贪食蛇
* 原作者:BigF
* 修改者:algo
* 说明:我以前也用C写过这个程序,现在看到BigF用Java写的这个,发现虽然作者自称是Java的初学者,
* 但是明显编写程序的素养不错,程序结构写得很清晰,有些细微得地方也写得很简洁,一时兴起之
* 下,我认真解读了这个程序,发现数据和表现分开得很好,而我近日正在学习MVC设计模式,
* 因此尝试把程序得结构改了一下,用MVC模式来实现,对源程序得改动不多。
* 我同时也为程序增加了一些自己理解得注释,希望对大家阅读有帮助。
*/
package mvcTest;
/**
* @author WangYu
* @version 1.0
* Description:
* /pre
* Create on :Date :2005-6-13 Time:15:57:16
* LastModified:
* History:
*/
public class GreedSnake {
public static void main(String[] args) {
SnakeModel model = new SnakeModel(20,30);
SnakeControl control = new SnakeControl(model);
SnakeView view = new SnakeView(model,control);
//添加一个观察者,让view成为model的观察者
model.addObserver(view);
(new Thread(model)).start();
}
}
-------------------------------------------------------------
2、
package mvcTest;
//SnakeControl.java
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
/**
* MVC中的Controler,负责接收用户的操作,并把用户操作通知Model
*/
public class SnakeControl implements KeyListener{
SnakeModel model;
public SnakeControl(SnakeModel model){
this.model = model;
}
public void keyPressed(KeyEvent e) {
int keyCode = e.getKeyCode();
if (model.running){ // 运行状态下,处理的按键
switch (keyCode) {
case KeyEvent.VK_UP:
model.changeDirection(SnakeModel.UP);
break;
case KeyEvent.VK_DOWN:
model.changeDirection(SnakeModel.DOWN);
break;
case KeyEvent.VK_LEFT:
model.changeDirection(SnakeModel.LEFT);
break;
case KeyEvent.VK_RIGHT:
model.changeDirection(SnakeModel.RIGHT);
break;
case KeyEvent.VK_ADD:
case KeyEvent.VK_PAGE_UP:
model.speedUp();
break;
case KeyEvent.VK_SUBTRACT:
case KeyEvent.VK_PAGE_DOWN:
model.speedDown();
break;
case KeyEvent.VK_SPACE:
case KeyEvent.VK_P:
model.changePauseState();
break;
default:
}
}
// 任何情况下处理的按键,按键导致重新启动游戏
if (keyCode == KeyEvent.VK_R ||
keyCode == KeyEvent.VK_S ||
keyCode == KeyEvent.VK_ENTER) {
model.reset();
}
}
public void keyReleased(KeyEvent e) {
}
public void keyTyped(KeyEvent e) {
}
}
-------------------------------------------------------------
3、
/*
*
*/
package mvcTest;
/**
* 游戏的Model类,负责所有游戏相关数据及运行
* @author WangYu
* @version 1.0
* Description:
* /pre
* Create on :Date :2005-6-13 Time:15:58:33
* LastModified:
* History:
*/
//SnakeModel.java
import javax.swing.*;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Random;
/**
* 游戏的Model类,负责所有游戏相关数据及运行
*/
class SnakeModel extends Observable implements Runnable {
boolean[][] matrix; // 指示位置上有没蛇体或食物
LinkedList nodeArray = new LinkedList(); // 蛇体
Node food;
int maxX;
int maxY;
int direction = 2; // 蛇运行的方向
boolean running = false; // 运行状态
int timeInterval = 200; // 时间间隔,毫秒
double speedChangeRate = 0.75; // 每次得速度变化率
boolean paused = false; // 暂停标志
int score = 0; // 得分
int countMove = 0; // 吃到食物前移动的次数
// UP and DOWN should be even
// RIGHT and LEFT should be odd
public static final int UP = 2;
public static final int DOWN = 4;
public static final int LEFT = 1;
public static final int RIGHT = 3;
public SnakeModel( int maxX, int maxY) {
this.maxX = maxX;
this.maxY = maxY;
reset();
}
public void reset(){
direction = SnakeModel.UP; // 蛇运行的方向
timeInterval = 200; // 时间间隔,毫秒
paused = false; // 暂停标志
score = 0; // 得分
countMove = 0; // 吃到食物前移动的次数
// initial matirx, 全部清0
matrix = new boolean[maxX][];
for (int i = 0; i maxX; ++i) {
matrix[i] = new boolean[maxY];
Arrays.fill(matrix[i], false);
}
// initial the snake
// 初始化蛇体,如果横向位置超过20个,长度为10,否则为横向位置的一半
int initArrayLength = maxX 20 ? 10 : maxX / 2;
nodeArray.clear();
for (int i = 0; i initArrayLength; ++i) {
int x = maxX / 2 + i;//maxX被初始化为20
int y = maxY / 2; //maxY被初始化为30
//nodeArray[x,y]: [10,15]-[11,15]-[12,15]~~[20,15]
//默认的运行方向向上,所以游戏一开始nodeArray就变为:
// [10,14]-[10,15]-[11,15]-[12,15]~~[19,15]
nodeArray.addLast(new Node(x, y));
matrix[x][y] = true;
}
// 创建食物
food = createFood();
matrix[food.x][food.y] = true;
}
public void changeDirection(int newDirection) {
// 改变的方向不能与原来方向同向或反向
if (direction % 2 != newDirection % 2) {
direction = newDirection;
}
}
/**
* 运行一次
* @return
*/
public boolean moveOn() {
Node n = (Node) nodeArray.getFirst();
int x = n.x;
int y = n.y;
// 根据方向增减坐标值
switch (direction) {
case UP:
y--;
break;
case DOWN:
y++;
break;
case LEFT:
x--;
break;
case RIGHT:
x++;
break;
}
// 如果新坐标落在有效范围内,则进行处理
if ((0 = x x maxX) (0 = y y maxY)) {
if (matrix[x][y]) { // 如果新坐标的点上有东西(蛇体或者食物)
if (x == food.x y == food.y) { // 吃到食物,成功
nodeArray.addFirst(food); // 从蛇头赠长
// 分数规则,与移动改变方向的次数和速度两个元素有关
int scoreGet = (10000 - 200 * countMove) / timeInterval;
score += scoreGet 0 ? scoreGet : 10;
countMove = 0;
food = createFood(); // 创建新的食物
matrix[food.x][food.y] = true; // 设置食物所在位置
return true;
} else // 吃到蛇体自身,失败
return false;
} else { // 如果新坐标的点上没有东西(蛇体),移动蛇体
nodeArray.addFirst(new Node(x, y));
matrix[x][y] = true;
n = (Node) nodeArray.removeLast();
matrix[n.x][n.y] = false;
countMove++;
return true;
}
}
return false; // 触到边线,失败
}
public void run() {
running = true;
while (running) {
try {
Thread.sleep(timeInterval);
} catch (Exception e) {
break;
}
if (!paused) {
if (moveOn()) {
setChanged(); // Model通知View数据已经更新
notifyObservers();
} else {
JOptionPane.showMessageDialog(null,
"you failed",
"Game Over",
JOptionPane.INFORMATION_MESSAGE);
break;
}
}
}
running = false;
}
private Node createFood() {
int x = 0;
int y = 0;
// 随机获取一个有效区域内的与蛇体和食物不重叠的位置
do {
Random r = new Random();
x = r.nextInt(maxX);
y = r.nextInt(maxY);
} while (matrix[x][y]);
return new Node(x, y);
}
public void speedUp() {
timeInterval *= speedChangeRate;
}
public void speedDown() {
timeInterval /= speedChangeRate;
}
public void changePauseState() {
paused = !paused;
}
public String toString() {
String result = "";
for (int i = 0; i nodeArray.size(); ++i) {
Node n = (Node) nodeArray.get(i);
result += "[" + n.x + "," + n.y + "]";
}
return result;
}
}
class Node {
int x;
int y;
Node(int x, int y) {
this.x = x;
this.y = y;
}
}
------------------------------------------------------------
4、
package mvcTest;
//SnakeView.java
import javax.swing.*;
import java.awt.*;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Observable;
import java.util.Observer;
/**
* MVC模式中得Viewer,只负责对数据的显示,而不用理会游戏的控制逻辑
*/
public class SnakeView implements Observer {
SnakeControl control = null;
SnakeModel model = null;
JFrame mainFrame;
Canvas paintCanvas;
JLabel labelScore;
public static final int canvasWidth = 200;
public static final int canvasHeight = 300;
public static final int nodeWidth = 10;
public static final int nodeHeight = 10;
public SnakeView(SnakeModel model, SnakeControl control) {
this.model = model;
this.control = control;
mainFrame = new JFrame("GreedSnake");
Container cp = mainFrame.getContentPane();
// 创建顶部的分数显示
labelScore = new JLabel("Score:");
cp.add(labelScore, BorderLayout.NORTH);
// 创建中间的游戏显示区域
paintCanvas = new Canvas();
paintCanvas.setSize(canvasWidth + 1, canvasHeight + 1);
paintCanvas.addKeyListener(control);
cp.add(paintCanvas, BorderLayout.CENTER);
// 创建底下的帮助栏
JPanel panelButtom = new JPanel();
panelButtom.setLayout(new BorderLayout());
JLabel labelHelp;
labelHelp = new JLabel("PageUp, PageDown for speed;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.NORTH);
labelHelp = new JLabel("ENTER or R or S for start;", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.CENTER);
labelHelp = new JLabel("SPACE or P for pause", JLabel.CENTER);
panelButtom.add(labelHelp, BorderLayout.SOUTH);
cp.add(panelButtom, BorderLayout.SOUTH);
mainFrame.addKeyListener(control);
mainFrame.pack();
mainFrame.setResizable(false);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setVisible(true);
}
void repaint() {
Graphics g = paintCanvas.getGraphics();
//draw background
g.setColor(Color.WHITE);
g.fillRect(0, 0, canvasWidth, canvasHeight);
// draw the snake
g.setColor(Color.BLACK);
LinkedList na = model.nodeArray;
Iterator it = na.iterator();
while (it.hasNext()) {
Node n = (Node) it.next();
drawNode(g, n);
}
// draw the food
g.setColor(Color.RED);
Node n = model.food;
drawNode(g, n);
updateScore();
}
private void drawNode(Graphics g, Node n) {
g.fillRect(n.x * nodeWidth,
n.y * nodeHeight,
nodeWidth - 1,
nodeHeight - 1);
}
public void updateScore() {
String s = "Score: " + model.score;
labelScore.setText(s);
}
public void update(Observable o, Object arg) {
repaint();
}
}
希望采纳