求C语言小游戏源程序

求C语言小游戏源程序,第1张

我的楼主可以自己玩一下

试试吧

#define N 200

#include <graphicsh>

#include <stdlibh>

#include <dosh>

#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();/随机数发生器/

foodyes=1;/1表示需要出现新食物,0表示已经存在食物/

snakelife=0;/活着/

snakedirection=1;/方向往右/

snakex[0]=100;snakey[0]=100;/蛇头/

snakex[1]=110;snakey[1]=100;

snakenode=2;/节数/

PrScore();/输出得分/

while(1)/可以重复玩游戏,压ESC键结束/

{

while(!kbhit())/在没有按键的情况下,蛇自己移动身体/

{

if(foodyes==1)/需要出现新食物/

{

foodx=rand()%400+60;

foody=rand()%350+60;

while(foodx%10!=0)/食物随机出现后必须让食物能够在整格内,这样才可以让蛇吃到/

foodx++;

while(foody%10!=0)

foody++;

foodyes=0;/画面上有食物了/

}

if(foodyes==0)/画面上有食物了就要显示/

{

setcolor(GREEN);

rectangle(foodx,foody,foodx+10,foody-10);

}

for(i=snakenode-1;i>0;i--)/蛇的每个环节往前移动,也就是贪吃蛇的关键算法/

{

snakex[i]=snakex[i-1];

snakey[i]=snakey[i-1];

}

/1,2,3,4表示右,左,上,下四个方向,通过这个判断来移动蛇头/

switch(snakedirection)

{

case 1:snakex[0]+=10;break;

case 2: snakex[0]-=10;break;

case 3: snakey[0]-=10;break;

case 4: snakey[0]+=10;break;

}

for(i=3;i<snakenode;i++)/从蛇的第四节开始判断是否撞到自己了,因为蛇头为两节,第三节不可能拐过来/

{

if(snakex[i]==snakex[0]&&snakey[i]==snakey[0])

{

GameOver();/显示失败/

snakelife=1;

break;

}

}

if(snakex[0]<55||snakex[0]>595||snakey[0]<55||

snakey[0]>455)/蛇是否撞到墙壁/

{

GameOver();/本次游戏结束/

snakelife=1; /蛇死/

}

if(snakelife==1)/以上两种判断以后,如果蛇死就跳出内循环,重新开始/

break;

if(snakex[0]==foodx&&snakey[0]==foody)/吃到食物以后/

{

setcolor(0);/把画面上的食物东西去掉/

rectangle(foodx,foody,foodx+10,foody-10);

snakex[snakenode]=-20;snakey[snakenode]=-20;

/新的一节先放在看不见的位置,下次循环就取前一节的位置/

snakenode++;/蛇的身体长一节/

foodyes=1;/画面上需要出现新的食物/

score+=10;

PrScore();/输出新得分/

}

setcolor(4);/画出蛇/

for(i=0;i<snakenode;i++)

rectangle(snakex[i],snakey[i],snakex[i]+10,

snakey[i]-10);

delay(gamespeed);

setcolor(0);/用黑色去除蛇的的最后一节/

rectangle(snakex[snakenode-1],snakey[snakenode-1],

snakex[snakenode-1]+10,snakey[snakenode-1]-10);

} /endwhile(!kbhit)/

if(snakelife==1)/如果蛇死就跳出循环/

break;

key=bioskey(0);/接收按键/

if(key==ESC)/按ESC键退出/

break;

else

if(key==UP&&snakedirection!=4)

/判断是否往相反的方向移动/

snakedirection=3;

else

if(key==RIGHT&&snakedirection!=2)

snakedirection=1;

else

if(key==LEFT&&snakedirection!=1)

snakedirection=2;

else

if(key==DOWN&&snakedirection!=3)

snakedirection=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();

}

#include<graphicsh>

#include<stdlibh>

#include<dosh>

#define LEFT 0x4b00

#define RIGHT 0x4d00

#define DOWN 0x5000

#define UP 0x4800

#define ESC 0x011b

int i,key;

int score=0;

int gamespeed=32000;

struct Food /食物的结构体/

{

int x; /食物的横坐标/

int y; /食物的纵坐标/

int yes; /食物是否出现的变量/

}food;

struct Snack /蛇的结构体/

{

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 PrScore(void); /分数输出函数/

DELAY(char ch)/调节游戏速度/

{

if(ch=='3')

{

delay(gamespeed); /delay是延迟函数/

delay(gamespeed);

}

else if(ch=='2')

{

delay(gamespeed);

}

}

Menu()/游戏开始菜单/

{

char ch;

printf("Please choose the gamespeed:\n");

printf("1-Fast 2-Normal 3-Slow\n");

printf("\nPlease Press The numbers\n");

do

{ch=getch();}

while(ch!='1'&&ch!='2'&&ch!='3');

clrscr();

return(ch);

}

/主函数/

void main(void)

{

int ch;

ch=Menu();

Init();

DrawK();

GamePlay(ch);

Close();

}

void Init(void)

{

int gd=DETECT,gm;

initgraph(&gd,&gm,"c:\\tc");

cleardevice();

}

void DrawK(void)

{

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(char ch)

{

randomize(); /随机数发生器/

foodyes=1; /1代表要出现食物,0表示以存在食物/

snakelife=0;

snakedirection=1;

snakex[0]=100;snakey[0]=100;

snakex[1]=110;snakey[1]=100;

snakenode=2;

PrScore();

while(1) /可以重复游戏/

{

while(!kbhit()) /在没有按键的情况下蛇自己移动/

{

if(foodyes==1) /需要食物/

{

foodx=rand()%400+60;

foody=rand()%350+60; /使用rand函数随机产生食物坐标/

while(foodx%10!=0)

foodx++;

while(foody%10!=0)

foody++; /判断食物是否出现在整格里/

foodyes=0; /现在有食物了/

}

if(foodyes==0) /有食物了就要显示出来/

{

setcolor(GREEN);

rectangle(foodx,foody,foodx+10,foody-10);

}

for(i=snakenode-1;i>0;i--) /贪吃蛇的移动算法/

{

snakex[i]=snakex[i-1];

snakey[i]=snakey[i-1]; /贪吃蛇的身体移动算法/

}

switch(snakedirection) /贪吃蛇的头部移动算法,以此来控制移动/

{

case 1:snakex[0]+=10;break;

case 2:snakex[0]-=10;break;

case 3:snakey[0]-=10;break;

case 4:snakey[0]+=10;break;

}

for(i=3;i<snakenode;i++) /判断是否头部与身体相撞/

{

if(snakex[i]==snakex[0]&&snakey[i]==snakey[0])

{

GameOver();

snakelife=1;

break;

}

}

/下面是判断是否撞到墙壁/

if(snakex[0]<55||snakex[0]>595||snakey[0]<55||snakey[0]>455)

{

GameOver();

snakelife=1;

}

if(snakelife==1) /如果死亡就退出循环/

break;

if(snakex[0]==foodx&&snakey[0]==foody) /判断蛇是否吃到食物/

{

setcolor(0);

rectangle(foodx,foody,foodx+10,foody-10); /吃的食物后用黑色将食物擦去/

snakex[snakenode]=-20;snakey[snakenode]=-20; /现把增加的一节放到看不到的地方去/

snakenode++;

foodyes=1;

score+=10;

PrScore();

}

setcolor(4); /每次移动后将后面的身体擦去/

for(i=0;i<snakenode;i++)

rectangle(snakex[i],snakey[i],snakex[i]+10,snakey[i]-10);

delay(gamespeed);

DELAY(ch);

setcolor(0);

rectangle(snakex[snakenode-1],snakey[snakenode-1],snakex[snakenode-1]+10,snakey[snakenode-1]-10);

}

if(snakelife==1)

break;

key=bioskey(0); /接受按键/

if(key==ESC)

break;

else

if(key==UP&&snakedirection!=4)/判断是否改变方向/

snakedirection=3;

else

if(key==RIGHT&&snakedirection!=2)

snakedirection=1;

else

if(key==LEFT&&snakedirection!=1)

snakedirection=2;

else

if(key==DOWN&&snakedirection!=3)

snakedirection=4;

}

}

void GameOver(void)

{

cleardevice();

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,"scord:%d",score);

outtextxy(55,20,str);

}

void Close(void)

{

getch();

closegraph();

}

贪吃蛇

贪吃蛇

using System;

using SystemCollectionsGeneric;

using SystemComponentModel;

using SystemData;

using SystemDrawing;

using SystemText;

using SystemWindowsForms;

using SystemCollections;

namespace WindowsApplication1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

private bool i;//开关

snake a_snake = new snake(5);//实例化个长度为5的蛇

food afood = new food();//实例化一个食物

private void pictureBox1_Paint(object sender, PaintEventArgs e)

{

Graphics g = eGraphics;

if (i)//点击了开始button

{

a_snakedrawsnake(g);//画出蛇

afooddrawfood(g);//画出来食物

}

if (a_snakedeadsnake())//如果蛇死亡事件为真

{

timer1Enabled = false;//timer控件停止

if (DialogResultYes ==

MessageBoxShow("GAME OVER", "是否重新开始", MessageBoxButtonsYesNo))

//messagebox消息

{

//点击确定后重新开始游戏

button1Enabled = true;

a_snake = new snake(5);//初始化蛇

afood = new food();//初始化食物

i = false;//开关为假

gClear(pictureBox1BackColor);//清理picturebox

}

else

ApplicationExit();//关闭程序

}

}

private void button1_Click(object sender, EventArgs e)

{

i = true; //开关为真

afoodF_point = afoodgetpoint();//产生一个食物的随机坐标

pictureBox1Refresh();//刷新picturebox

timer1Enabled = true;//开启timer控件

timer1Interval = 100; //时间间隔为01秒

button1Enabled = false;

}

private void timer1_Tick(object sender, EventArgs e)

{

pictureBox1Refresh();//刷新picturebox

a_snakeextendsnake();//蛇伸长一节

if (a_snakeheadpoint == afoodF_point)

afoodF_point = afoodgetpoint();//蛇头坐标与食物相同

//就只伸长

else

a_snakecontractsnake();//没吃到食物就缩短一节

}

private void Form1_KeyDown(object sender, KeyEventArgs e)

{

if (eKeyCode == KeysW && a_snakeWay != 2)

{

a_snakeWay = 0;

}

if (eKeyCode == KeysD && a_snakeWay != 3)

{

a_snakeWay = 1;

}

if (eKeyCode == KeysS && a_snakeWay != 0)

{

a_snakeWay = 2;

}

if (eKeyCode == KeysA && a_snakeWay != 1)

{

a_snakeWay = 3;

}

//设置KeyDown事件,用按件控制方向

}

}

public class segment//[一节蛇]类

{

private int number;//私有成员

public int Number//[一节蛇]的编号

{

get

{

return number;

}

set

{

number = value;

}

}

private Point orign;

public Point Orign//[一节蛇]的坐标

{

get

{

return orign;

}

set

{

orign = value;

}

}

public void drawpart(Graphics g)//画[一节蛇]

{

Pen p = new Pen(ColorRed);

gDrawEllipse(p, orignX, orignY, 10, 10);

//画红色圆圈代表一节蛇

}

}

public class snake//蛇类

{

ArrayList alist;//定义一个先进先出的数据表

public Point headpoint;//蛇头坐标

private int way = 1;//初始方向为右

public int Way

{

get

{

return way;

}

set

{

way = value;

}

}

public snake(int count)//蛇的构造函数

{

segment apart;

Point apoint = new Point(30, 30);//初始位置

alist = new ArrayList(count);//初始化数据表

for (int i = 1; i <= count; i++)

{

apointX = apointX + 10;

apart = new segment();

apartNumber = i;

apartOrign = apoint;

alistAdd(apart);//将没节蛇存在表里面

if (i == count)//将最后的一节蛇定为蛇头

headpoint = apoint;

}

}

public void drawsnake(Graphics g)//画蛇

{

for (int i = 0; i < alistCount; i++)

{

segment seg = (segment)alist[i];

segdrawpart(g);

}

}

public void extendsnake()//伸长一节蛇

{

segment seg = new segment();

segNumber = alistCount + 1;

Point p;

if (way == 0)

p = new Point(headpointX, headpointY - 10);

else if (way == 2)

p = new Point(headpointX, headpointY + 10);

else if (way == 3)

p = new Point(headpointX - 10, headpointY);

else

p = new Point(headpointX + 10, headpointY);

segOrign = p;

alistAdd(seg);//将新的一节蛇添加到表尾

headpoint = segOrign;//重新设蛇头

}

public void contractsnake()//蛇缩短一节

{

alistRemove(alist[0]);//删除表的第一个元素

}

public bool deadsnake()//射死亡事件

{

if (headpointX < 0 || headpointY < 0 || headpointX > 350 || headpointY > 270)

//判断是否撞墙了

return true;

for (int i = 0; i < alistCount - 1; i++)

{

segment seg = (segment)alist[i];

if (segOrign == headpoint)//判断是否咬到自己

return true;

}

return false;

}

}

public class food//食物类

{

private Point f_point;

public Point F_point//食物的坐标

{

get

{

return f_point;

}

set

{

f_point = value;

}

}

public void drawfood(Graphics g)//画食物

{

SolidBrush b = new SolidBrush(ColorBlue);

Rectangle rtg = new Rectangle(f_pointX, f_pointY, 10, 10);

gFillRectangle(b, rtg);

//实心的蓝色方块

}

public Point getpoint()//获得食物坐标[随机数point]

{

int i = 10;

Random rdm = new Random(SystemDateTimeNowMillisecond + i);

i = rdmNext(0, 27);

int j = rdmNext(0, 27);

Point newp = new Point(i 10, j 10);

return newp;

}

}

}

下一百层

using System;

using SystemCollectionsGeneric;

using SystemComponentModel;

using SystemData;

using SystemDrawing;

using SystemText;

using SystemWindowsForms;

using SystemCollections;

namespace WindowsApplication1

{

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

}

lift alift = new lift();//梯子实例化

people man = new people();//人物实例化

bool i;//开关

int j =1;//人物移动方向

private void pictureBox1_Paint(object sender, PaintEventArgs e)

{

Graphics g = eGraphics;

if (i)

{

aliftdrawlift(g);//画梯子

mandrawpeople(g);//画人物

}

if (manmandead())//人物死亡为真

{

timer1Enabled = false;

timer2Enabled = false;

timer3Enabled = false;

timer4Enabled = false;

if (DialogResultYes ==

MessageBoxShow("Game Over", "重新开始游戏?", MessageBoxButtonsYesNo))

{ //重新开始游戏

button1Enabled = true;

manFootpoint = new Point(aliftdownmostX + 50, aliftdownmostY - 20);

}

else

ApplicationExit();//退出游戏

}

}

private void button1_Click(object sender, EventArgs e)

{

i = true;//打开开关

pictureBox1Refresh();//刷新

timer1Interval = 2;

timer1Enabled = true;

timer3Interval = 1;

timer3Enabled = true;

manFootpoint = new Point(aliftdownmostX + 50, aliftdownmostY -20);

//初始化任务的坐标

button1Enabled = false;//Button1被锁

}

private void timer1_Tick(object sender, EventArgs e)

{

aliftliftrise();//伸梯子

if (aliftdownmostY <= 260)

aliftaddstep();//加梯子

pictureBox1Refresh();

}

private void Form1_KeyDown(object sender, KeyEventArgs e)

{

//用A控制向左,S控制向右

if (eKeyCode == KeysA)

{

timer2Interval = 1;

timer2Enabled = true;

j = 2;

}

if (eKeyCode == KeysS)

{

timer2Interval = 1;

timer2Enabled = true;

j = 3;

}

}

private void Form1_KeyUp(object sender, KeyEventArgs e)

{

//KeyUp事件控制人物左右移动的停止

if (eKeyCode == KeysA)

{

timer2Enabled = false ;

j = 1;

}

if (eKeyCode == KeysS)

{

timer2Enabled = false ;

j = 1;

}

}

private void timer2_Tick(object sender, EventArgs e)

{

if (j == 2)

manmoveleft();//人物向左移动

else if (j == 3)

manmoveright();//人物向右移动

}

private void timer3_Tick(object sender, EventArgs e)

{

manmovedown();//人物下落

if (aliftmanland(man))

{

timer3Enabled = false;

timer4Interval = 2;

timer4Enabled = true;

}

}

private void timer4_Tick(object sender, EventArgs e)

{

manmoverise();//人物随梯子上升

if (aliftmanout(man))

{

timer3Enabled = true;

timer4Enabled = false;

}

}

}

public class step//台阶类是梯子的一个单位

{

private Point safep;//台阶的坐标

public Point Safep

{

get

{

return safep;

}

set

{

safep = value;

}

}

public void drawstep(Graphics g)//画台阶[实心长方形]

{

SolidBrush b = new SolidBrush(ColorDarkSlateBlue);

Rectangle rect = new Rectangle(safepX, safepY, 100, 10);

gFillRectangle(b, rect);

}

public int getpointx(int i)//台阶的随机X坐标

{

Random rdm = new Random(SystemDateTimeNowMillisecond+i);

return rdmNext(0,240);

}

public Point risepoint()//新伸起来的台阶坐标

{

Random rdm = new Random(SystemDateTimeNowMillisecond123456 );

int x= rdmNext(0, 240);

Point p = new Point(x, 340);

return p;

}

}

public class lift//梯子类

{

public ArrayList alist = new ArrayList(5);//先进先出表

public Point downmost;//最下面台阶的坐标

public lift()//构造函数

{

step astep;

int x=1,y=10;

for (int i = 0; i < 5; i++)

{

astep = new step();

x = astepgetpointx(x);

astep = new step();

astepSafep =new Point(x, y);

alistAdd(astep);

y = y + 80;

if (i == 4)

downmost = astepSafep;

}

}

public void drawlift(Graphics g)//画梯子

{

for (int i=0;i<5;i++)

{

step astep=(step) alist[i];

astepdrawstep (g);

}

}

public void liftrise()//梯子上升

{

//表中的每个Y坐标加1

//并把新的台阶存在表的尾部

for (int i = 0; i < 5; i++)

{

step astep = (step)alist[i];

Point p = new Point(astepSafepX, astepSafepY - 1);

astepSafep = p;

alistAdd(astep);

if (i == 4)

downmost = astepSafep;

}

for (int i = 0; i < 5; i++)//删除表的前5个数据

{

alistRemove(alist[i]);

}

}

public void addstep()//伸起来的一节梯子

{

step astep=new step ();

astepSafep=asteprisepoint();

alistAdd(astep);

alistRemove(alist[0]);

downmost = astepSafep; //始终保证最下面的一节为downmost

}

public bool manland(people man)//人物登陆事件

{

step s;

for (int a = 0; a < 5; a++)

{

s = (step)alist[a];

if (MathAbs( sSafepY -(manFootpointY+10))<2&&

sSafepX <= manFootpointX+10 &&

manFootpointX <= sSafepX + 100)

return true;

}

return false;

}

public bool manout(people man)//人物冲出事件

{

step s;

for (int a = 0; a < 5; a++)

{

s = (step)alist[a];

if (MathAbs(sSafepY - (manFootpointY + 10)) < 3)

{

if (sSafepX-10 > manFootpointX ||

manFootpointX > sSafepX + 100)

return true;

}

}

return false;

}

}

public class people//人物类

{

private Point footpoint;//人物的坐标

public Point Footpoint

{

get

{

return footpoint;

}

set

{

footpoint = value;

}

}

public void drawpeople(Graphics g)//画个实心圆代表人物

{

SolidBrush b = new SolidBrush(ColorIndianRed);

Rectangle rect = new Rectangle(footpointX, footpointY, 10, 10);

gFillEllipse(b, rect);

}

public void moveleft()//人物向左移动

{

Point p = new Point(footpointX - 2, footpointY);

footpoint = p;

}

public void moveright()//人物向右移动

{

Point p = new Point(footpointX + 2, footpointY);

footpoint = p;

}

public void moverise()//人物随梯子上升

{

Point p = new Point(footpointX, footpointY-1);

footpoint = p;

}

public void movedown()//人物下落

{

Point p = new Point(footpointX, footpointY + 1);

footpoint = p;

}

public bool mandead()//人物死亡

{

if ( footpointY<0 ||footpointY>340)

return true ;

return false ;

}

}

}

发两个玩玩吧。 都测试过可行的

我这儿有c语言的自写俄罗斯方块,请指教:#include

#include

#include

#include

#include

#include

#include

#define ESC 0x011b

#define UP 0x4800

#define DOWN 0x5000

#define LEFT 0x4b00

#define RIGHT 0x4d00

#define SPACE 0x3920

#define Y 0x1579

#define N 0x316e

#define clearkbd(); while(bioskey(1)) bioskey(0); /清空键盘缓冲队列/

void update();

void messagebox();

void process();

void initremove();

void initinfo();

void initbox();

void initposition();

void next_shape();

typedef struct shape /形状单一状态的记录/

{ int attr;

int co[8];

}shape;

typedef struct RE_AB /相对,绝对坐标记录/

{ int Rx,Ry;

int x1,x2,y1,y2;

}RE_AB;

RE_AB RA;

shape p[19]={ { RED,0,1,1,0,1,1,2,1 }, /数组中保证y最大的在最后,以便initposition使用/

{ RED,0,1,1,0,1,1,1,2 },

{ RED,0,0,1,0,2,0,1,1 },

{ RED,0,0,0,1,1,1,0,2 },

{ GREEN,0,0,1,0,2,0,3,0 },

{ GREEN,0,0,0,1,0,2,0,3 },

{ CYAN,0,0,0,1,1,0,1,1 },

{ BROWN,0,0,1,0,1,1,2,1 },

{ BROWN,1,0,0,1,1,1,0,2 },

{ BLUE,1,0,2,0,1,1,0,1 },

{ BLUE,0,0,0,1,1,1,1,2 },

{ MAGENTA,0,0,0,1,0,2,1,2 },

{ MAGENTA,2,0,0,1,1,1,2,1},

{ MAGENTA,0,0,1,0,1,1,1,2 },

{ MAGENTA,0,0,0,1,1,0,2,0 },

{ YELLOW,0,2,1,0,1,1,1,2 },

{ YELLOW,0,0,1,0,2,0,2,1 },

{ YELLOW,1,0,0,0,0,1,0,2},

{ YELLOW,0,0,0,1,1,1,2,1 },

};

int nback,nleft,nright,r_f[12][22],rs1,rs2,xcors,xcorb,ycors,ycorb;

/检查方快有没有左,右,下接触,游戏区内所有格子有无颜色记录数组,rs1形状记录,rs2为提示框用,记录小格子在游戏区中的位置,按键存储/

void interrupt (oldint)(); /系统定时中断/

int count_down=0,count_other=0; /中断记时/

void interrupt newint() /设置新的中断程序/

{ count_down++;

count_other++;

oldint();

}

void intenable() /设置中断向量表,启动新的中断程序/

{ oldint=getvect(0x1c);

disable();

setvect(0x1c,newint);

enable();

}

void intrestore() /恢复中断向量/

{ disable();

setvect(0x1c,oldint);

enable();

}

void HZ12(int x0,int y0,int w,int color,char s) /根据字模,在dos下显示汉字/

/横坐标,纵坐标,字间隔,汉字颜色,汉字字符串/

{ FILE fp;

register char buffer[24];

register char str[2];

unsigned long fpos;/fpos为最终偏移动量/

register int i,j,k;

fp=fopen(hzk12,r);/打开1212汉字苦/

while(s)/一直到字符串结束为止/

{

if(s<0)/汉字输出/

{ str[0]=(s)-0xa0;

str[1]=(s+1)-0xa0;

fpos=((str[0]-1)94+(str[1]-1))24L;/计算汉字在hzk12的偏移量/

fseek(fp,fpos,SEEK_SET);/指针移动到当前位置/

fread(buffer,24,1,fp);/读取一个汉字到数组中/

for(i=0;i<12;i++)/12行/

for(j=0;j<2;j++)/两个字节/

for(k=0;k<8;k++)/8位/

if (((buffer[i2+j]>>(7-k))&0x1)!=NULL)/是一就画点/

putpixel(x0+8j+k,y0+i,color);

s+=2;/一个汉字占两个字节,现在将指针移动两个字节/

x0+=w;/显示坐标也按照间隔移动/

}

else/显示非汉字字符/

{ settextstyle(0,0,1);

setcolor(color);

str[0]=s;str[1]=0;

outtextxy(x0,y0+3,str);/显示单个字符/

x0+=w-7;/显示单个字符后的x坐标变化/

s++;/指针移动到下一个字节/

}

}

fclose(fp);

}

void translation() /把相对坐标解释为绝对坐标/

{ if(RARx==1)

{ RAx1=1; RAx2=16; }

else

{ RAx1=16(RARx-1); RAx2=16RARx; }

if(RARy==1)

{ RAy1=1; RAy2=16; }

else

{ RAy1=16(RARy-1); RAy2=16RARy; }

}

int check_b() /检查是否到达低部/

{ int x,y,i,zf=0; /zf为是否有颜色填充记录/

for(i=0;i<7;i++,i++)

{ x=RARx+p[rs1]co[i];

y=RARy+p[rs1]co[i+1];

if(y>=6)

zf+=r_f[x-15][y-6+1];

}

if(zf==0)

return 1;

else

return 0;

}

int finish()

{ int tfull=0,i; /判断顶层空间是否有填充/

for(i=1;i<11;i++)

tfull+=r_f[i][1];

if(tfull!=0)

return 1; /告诉judge()可以结束了/

}

int check_l() /检查形状是否与左接触/

{ int x,y,i,zf=0;

for(i=0;i<7;i++,i++)

{ x=RARx+p[rs1]co[i];

y=RARy+p[rs1]co[i+1];

if(y>6)

zf+=r_f[x-15-1][y-6];

if(y<=6&&x==16)

zf+=1;

}

if(zf==0)

return 1;

else

return 0;

}

int check_r() /检查形状是否与右接触/

{ /zf为是否有颜色填充记录/

int x,y,i,zf=0; /zf为是否有颜色填充记录/

for(i=0;i<7;i++,i++)

{

x=RARx+p[rs1]co[i];

y=RARy+p[rs1]co[i+1];

if(y>6)

zf+=r_f[x-15+1][y-6];

if(y<=6&&x==25)

zf+=1;

}

if(zf==0)

return 1;

else

return 0;

}

void check_touch()

{ nback=check_b();

nleft=check_l();

nright=check_r();

}

void draw(int cb) /画形状,cb=1以填充色画形状,cb=2以背景色画形状,cb=3以白色画形状/

{ int i,recordx=RARx,recordy=RARy;

for(i=0;i<7;i++,i++)

{ RARx+=p[rs1]co[i];

RARy+=p[rs1]co[i+1];

if(RARy<=6)

{ RARx=recordx;

RARy=recordy;

continue;

}

translation();

if(cb==1)

setfillstyle(1,p[rs1]attr);

else

if(cb==2)

setfillstyle(1,BLACK);

else

if(cb==3)

{ setfillstyle(1,WHITE);

r_f[RARx-15][RARy-6]=1; /置对应数组标记元素/

}

bar(RAx1+1,RAy1+1,RAx2-1,RAy2-1);

RARx=recordx;

RARy=recordy;

}

}

void mov(int key) /向下,左,右移动方块/

{ draw(2);

if(key==LEFT&&nleft)

RARx--;

else

if(key==RIGHT&&nright)

RARx++;

else

RARy++;

nback=check_b();

if(nback) /判断形状有没有到达底部,有就将其颜色变为白色/

draw(1);

else

draw(3);

}

void change() /变换形状/

{ int status=rs1,buffer,i,x,y,zf=0;

if(p[rs1]attr==p[rs1+1]attr)

rs1++;

else

while(p[rs1]attr==p[rs1-1]attr)

rs1--;

for(i=0;i<7;i++,i++) /检查变化形状后是否与已存形状发生冲突/

{ x=RARx+p[rs1]co[i];

y=RARy+p[rs1]co[i+1];

if(y>6)

zf+=r_f[x-15][y-6];

}

if(zf!=0)

rs1=status;

buffer=rs1;

rs1=status;

status=buffer;

draw(2);

buffer=rs1;

rs1=status;

status=buffer;

nback=check_b(); /判断变化后的形状是不是到达了低部,这个检查是十分必要的/

if(nback)

draw(1);

else

draw(3);

}

void accelerate()

{ if(count_down>=1)

{ check_touch(); /消除上一步动作对方块状态的影响/

count_down=0;

if(nback) /0表示到达底部,1表示没有到达/

mov(DOWN);

}

}

void drawbox() /画方块所在方框/

{ int xcor,ycor;

for(xcor=xcors;xcor<=xcorb;xcor++)

for(ycor=ycors;ycor<=ycorb;ycor++)

{ if(xcor==xcors||xcor==xcorb||ycor==ycors||ycor==ycorb)

{ RARx=xcor;

RARy=ycor;

translation();

setfillstyle(1,DARKGRAY);

bar(RAx1+1,RAy1+1,RAx2-1,RAy2-1);

}

}

}

void erasure(int k)

{ int i,j,recordx=RARx,recordy=RARy;

{ j=k-1;

for(;j>0;j--)

{ for(i=1;i<11;i++)

{ r_f[i][j+1]=r_f[i][j];

RARx=i+15;

RARy=j+1+6;

translation();

if(r_f[i][j+1]==1)

setfillstyle(1,WHITE);

else

setfillstyle(1,BLACK);

bar(RAx1+1,RAy1+1,RAx2-1,RAy2-1);

RARx=recordx;

RARy=recordy;

}

}

}

}

void pause()

{ HZ12(450,400,15,BLACK,正常);

HZ12(450,400,15,GREEN,暂停);

for(;;)

if(bioskey(1)&&bioskey(0)==SPACE)

{ clearkbd();

HZ12(450,400,15,BLACK,暂停);

HZ12(450,400,15,RED,正常);

return;

}

}

void judge()

{ int i,j,full=0; /full等于10说明某一行满,该消除了/

if(finish()) /判断游戏是否该结束了/

messagebox(); /win编程里有这个函数/

for(j=1;j<21;j++) /判断某一行是否满了/

{ for(i=1;i<11;i++)

full+=r_f[i][j];

if(full==10)

erasure(j); /消除这行/

full=0;

}

}

void update() /使程序可以重新运行/

{ cleardevice();

setbkcolor(BLACK);

initinfo(); /提示信息初始化/

initbox(); /游戏框架初始化/

srand((unsigned)time(NULL)); /随机器函数的初始化/

rs1=random(19);

rs2=random(19);

next_shape();

initposition(); /方块最开始的出现位置/

initremove(); /记录每个方格有无颜色填充数组初始化/

HZ12(450,400,15,RED,正常);

process();

}

void EXIT()

{ closegraph();

intrestore(); /恢复中断向量/

exit(0);

}

void initremove()

{ int i,j;

for(i=0;i<12;i++)

for(j=0;j<22;j++)

if(i==0||i==11||j==0||j==21)

r_f[i][j]=1;

else

r_f[i][j]=0;

}

void initinfo()

{ char aStr[2];

setcolor(RED);

outtextxy(450,100,This game's writer is:);

HZ12(450,140,15,RED,该程序作者:NULL);

outtextxy(525,110,NULL);

outtextxy(450,180,FUNCTION FOR KEYS:);

outtextxy(450,200,UP:change the shape);

outtextxy(450,210,DOWN:accelerate);

outtextxy(450,220,LEFT:move left);

outtextxy(450,230,RIGHT:move right);

outtextxy(450,240,ESC:exit this game);

outtextxy(450,250,SPACE:pause);

HZ12(450,260,20,RED,上:);

HZ12(450,280,20,RED,下:);

HZ12(450,300,20,RED,左:);

HZ12(450,320,20,RED,右:);

HZ12(450,340,20,RED,ESC:退出);

HZ12(450,360,15,RED,空格: 暂停/开始);

HZ12(450,380,15,RED,目前状态:);

HZ12(20,200,15,RED,下一个形状);

aStr[0]=24;

aStr[1]=0;

aStr[6]=0;

HZ12(480,260,12,GREEN,aStr);

HZ12(500,260,12,GREEN,( 变形 ));

aStr[0]=25;

aStr[1]=0;

HZ12(480,280,12,GREEN,aStr);

HZ12(500,280,12,GREEN,( 加速 ));

aStr[0]=27;

aStr[1]=0;

HZ12(480,300,12,GREEN,aStr);

HZ12(500,300,12,GREEN,向左);

aStr[0]=26;

aStr[1]=0;

HZ12(480,320,12,GREEN,aStr);

HZ12(500,320,12,GREEN,向右);

}

void messagebox()

{ int key;

setcolor(GREEN);

setfillstyle(1,DARKGRAY);

rectangle(220,200,420,300);

bar(221,201,419,299);

HZ12(280,210,15,GREEN,GAME OVER);

HZ12(275,230,15,GREEN,重新游戏: Y);

HZ12(275,270,15,GREEN,退出游戏: N);

HZ12(450,400,15,BLACK,正常);

HZ12(450,400,15,GREEN,GAME OVER);

for(;;)

if(bioskey(1))

{ key=bioskey(0);

if(key==Y)

{ clearkbd();

update();

}

else

if(key==N)

{ clearkbd();

EXIT();

}

else

clearkbd();

}

}

void initbox()

{ xcors=15; /画游戏框/

xcorb=26;

ycors=6;

ycorb=27;

drawbox();

xcors=2; /画提示框/

xcorb=7;

ycors=6;

ycorb=11;

drawbox();

}

void initposition()

{ RARx=18;

RARy=6-p[rs1]co[7];;

RAx1=0;

RAx2=0;

RAy1=0;

RAy2=0;

}

void next_shape() /画下一形状提示框/

{ int recordx=RARx,recordy=RARy,buffer;

RARx=3;

RARy=7;

draw(2);

buffer=rs1;

rs1=rs2;

rs2=buffer;

draw(1);

RARx=recordx;

RARy=recordy;

buffer=rs1;

rs1=rs2;

rs2=buffer;

}

void process() /游戏过程/

{ for(;;)

{ check_touch();

if(!nback)

{ rs1=rs2;

rs2=random(19); /产生另一种方块的码数/

initposition();

judge(); /判断某一行是否满了和这个游戏是否可以结束了/

draw(1);

next_shape();

}

if(count_other>=1)

{ count_other=0;

if(bioskey(1)) /对按键的处理/

{ int key=bioskey(0);

clearkbd(); /清除键盘缓冲队列/

if(key==ESC)

EXIT();

if(key==LEFT&&nleft&&nback)

mov(LEFT);

if(key==RIGHT&&nright&&nback)

mov(RIGHT);

if(key==UP&&nback)

change();

if(key==SPACE)

pause();

if(key==DOWN)

accelerate();

}

}

if(count_down>=4)

{ check_touch(); /消除上一步动作对方块状态的影响/

count_down=0;

if(nback) /0表示到达底部,1表示没有到达/

mov(DOWN);

}

}/for/

}

main()

{ int gdriver=DETECT,gmode=0;

initgraph(&gdriver,&gmode,d:turboc); /启动图形与中断部分/

intenable();

update();

}

// Calcu24cpp : Defines the entry point for the console application

//

/

6-6

24点游戏

/

#include "conioh"

#include "stdlibh"

#include "timeh"

#include "mathh"

#include "stringh"/

从一副扑克牌中,任取4张。

2-10 按其点数计算(为了表示方便10用T表示),J,Q,K,A 统一按 1 计算

要求通过加减乘除四则运算得到数字 24。

本程序可以随机抽取纸牌,并用试探法求解。

/void GivePuzzle(char buf)

{

char card[] = {'A','2','3','4','5','6','7','8','9','T','J','Q','K'}; for(int i=0; i<4; i++){

buf[i] = card[rand() % 13];

}

}

void shuffle(char buf)

{

for(int i=0; i<5; i++){

int k = rand() % 4;

char t = buf[k];

buf[k] = buf[0];

buf[0] = t;

}

}

int GetCardValue(int c)

{

if(c=='T') return 10;

if(c>='0' && c<='9') return c - '0';

return 1;

}

char GetOper(int n)

{

switch(n)

{

case 0:

return '+';

case 1:

return '-';

case 2:

return '';

case 3:

return '/';

} return ' ';

}double MyCalcu(double op1, double op2, int oper)

{

switch(oper)

{

case 0:

return op1 + op2;

case 1:

return op1 - op2;

case 2:

return op1 op2;

case 3:

if(fabs(op2)>00001)

return op1 / op2;

else

return 100000;

} return 0;

}

void MakeAnswer(char answer, int type, char question, int oper)

{

char p[4][3];

for(int i=0; i<4; i++)

{

if( question[i] == 'T' )

strcpy(p[i], "10");

else

sprintf(p[i], "%c", question[i]);

}

switch(type)

{

case 0:

sprintf(answer, "%s %c (%s %c (%s %c %s))",

p[0], GetOper(oper[0]), p[1], GetOper(oper[1]), p[2], GetOper(oper[2]), p[3]);

break;

case 1:

sprintf(answer, "%s %c ((%s %c %s) %c %s)",

p[0], GetOper(oper[0]), p[1], GetOper(oper[1]), p[2], GetOper(oper[2]), p[3]);

break;

case 2:

sprintf(answer, "(%s %c %s) %c (%s %c %s)",

p[0], GetOper(oper[0]), p[1], GetOper(oper[1]), p[2], GetOper(oper[2]), p[3]);

break;

case 3:

sprintf(answer, "((%s %c %s) %c %s) %c %s",

p[0], GetOper(oper[0]), p[1], GetOper(oper[1]), p[2], GetOper(oper[2]), p[3]);

break;

case 4:

sprintf(answer, "(%s %c (%s %c %s)) %c %s",

p[0], GetOper(oper[0]), p[1], GetOper(oper[1]), p[2], GetOper(oper[2]), p[3]);

break;

}

}

bool TestResolve(char question, int oper, char answer)

{

// 等待考生完成

int type[5]={0,1,2,3,4};//计算类型

double p[4];

double sum=0;

//

for(int i=0; i<4; i++) //循环取得点数

{

p[i]=GetCardValue(int(question[i]));

} for(i=0;i<5;i++)

{

MakeAnswer(answer,type[i],question,oper); //获取可能的答案

switch(type[i])

{

case 0:

sum=MyCalcu(p[0],MyCalcu( p[1],MyCalcu(p[2], p[3], oper[2]),oper[1]),oper[0]); //A(B(cD))

break;

case 1:

sum=MyCalcu(p[0],MyCalcu(MyCalcu(p[1], p[2], oper[1]),p[3],oper[2]),oper[0]); //A((BC)D)

break;

case 2:

sum=MyCalcu(MyCalcu(p[0], p[1], oper[0]),MyCalcu(p[2], p[3], oper[2]),oper[1]); // (AB)(CD)

break;

case 3:

sum=MyCalcu(MyCalcu(MyCalcu(p[0], p[1], oper[0]),p[2],oper[1]),p[3],oper[2]); //((AB)C)D

break;

case 4:

sum=MyCalcu(MyCalcu(p[0],MyCalcu(p[1], p[2], oper[1]),oper[0]),p[3],oper[2]); //(A(BC))D

break;

}

if(sum==24) return true;

}

return false;

}

/

采用随机试探法:就是通过随机数字产生 加减乘除的 组合,通过大量的测试来命中的解法

提示:

1 需要考虑用括号控制计算次序的问题 比如:( 10 - 4 ) ( 3 + A ), 实际上计算次序的数目是有限的:

A(B(cD))

A((BC)D)

(AB)(CD)

((AB)C)D

(A(BC))D

2 需要考虑计算结果为分数的情况:( 3 + (3 / 7) ) 7

3 题目中牌的位置可以任意交换

/

bool TryResolve(char question, char answer)

{

int oper[3]; // 存储运算符,0:加法 1:减法 2:乘法 3:除法

for(int i=0; i<1000 1000; i++)

{

// 打乱纸牌顺序

shuffle(question);

// 随机产生运算符

for(int j=0; j<3; j++)

oper[j] = rand() % 4; if( TestResolve(question, oper, answer) ) return true;

} return false;

}

int main(int argc, char argv[])

{

// 初始化随机种子

srand( (unsigned)time( NULL ) ); char buf1[4]; // 题目

char buf2[30]; // 解答

printf("\n");

printf("计算24\n");

printf("A J Q K 均按1计算,其它按牌点计算\n");

printf("目标是:通过四则运算组合出结果:24\n");

printf("\n\n");

for(;;)

{

GivePuzzle(buf1); // 出题

printf("题目:");

for(int j=0; j<4; j++){

if( buf1[j] == 'T' )

printf("10 ");

else

printf("%c ", buf1[j]);

} printf("\n按任意键参考答案\n");

getch(); if( TryResolve(buf1, buf2) ) // 解题

printf("参考:%s\n", buf2);

else

printf("可能是无解\n"); printf("按任意键出下一题目,x 键退出\n");

if( getch() == 'x' ) break;

} return 0;

}

以下是贪吃蛇源代码:

#include<iostreamh>

#include<windowsh>

#include<timeh>

#include<stdlibh>

#include<conioh>

#define N 21

void gotoxy(int x,int y)//位置函数

{

COORD pos;

posX=2x;

posY=y;

SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),pos);

}

void color(int a)//颜色函数

{

SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),a);

}

void init(int apple[2])//初始化函数(初始化围墙、显示信息、苹果)

{

int i,j;//初始化围墙

int wall[N+2][N+2]={{0}};

for(i=1;i<=N;i++)

{

for(j=1;j<=N;j++)

wall[i][j]=1;

}

color(11);

for(i=0;i<N+2;i++)

{

for(j=0;j<N+2;j++)

{

if(wall[i][j])

cout<<"■";

else cout<<"□" ;

}

cout<<endl;

}

gotoxy(N+3,1);//显示信息

color(20);

cout<<"按 W S A D 移动方向"<<endl;

gotoxy(N+3,2);

color(20);

cout<<"按任意键暂停"<<endl;

gotoxy(N+3,3);

color(20);

cout<<"得分:"<<endl;

apple[0]=rand()%N+1;//苹果

apple[1]=rand()%N+1;

gotoxy(apple[0],apple[1]);

color(12);

cout<<"●"<<endl;

}

int main()

{

int i,j;

int snake=NULL;

int apple[2];

int score=0;

int tail[2];

int len=3;

char ch='p';

srand((unsigned)time(NULL));

init(apple);

snake=(int)realloc(snake,sizeof(int)len);

for(i=0;i<len;i++)

snake[i]=(int)malloc(sizeof(int)2);

for(i=0;i<len;i++)

{

snake[i][0]=N/2;

snake[i][1]=N/2+i;

gotoxy(snake[i][0],snake[i][1]);

color(14);

cout<<"★"<<endl;

}

while(1)//进入消息循环

{

tail[0]=snake[len-1][0];

tail[1]=snake[len-1][1];

gotoxy(tail[0],tail[1]);

color(11);

cout<<"■"<<endl;

for(i=len-1;i>0;i--)

{

snake[i][0]=snake[i-1][0];

snake[i][1]=snake[i-1][1];

gotoxy(snake[i][0],snake[i][1]);

color(14);

cout<<"★"<<endl;

}

if(kbhit())

{

gotoxy(0,N+2);

ch=getche();

}

switch(ch)

{

case 'w':snake[0][1]--;break;

case 's':snake[0][1]++;break;

case 'a':snake[0][0]--;break;

case 'd':snake[0][0]++;break;

default: break;

}

gotoxy(snake[0][0],snake[0][1]);

color(14);

cout<<"★"<<endl;

Sleep(abs(200-05score));

if(snake[0][0]==apple[0]&&snake[0][1]==apple[1])//吃掉苹果后蛇分数加1,蛇长加1

{

score++;

len++;

snake=(int)realloc(snake,sizeof(int)len);

snake[len-1]=(int)malloc(sizeof(int)2);

apple[0]=rand()%N+1;

apple[1]=rand()%N+1;

gotoxy(apple[0],apple[1]);

color(12);

cout<<"●"<<endl;

gotoxy(N+5,3);

color(20);

cout<<score<<endl;

}

if(snake[0][1]==0||snake[0][1]==N||snake[0][0]==0||snake[0][0]==N)//撞到围墙后失败

{

gotoxy(N/2,N/2);

color(30);

cout<<"失败!!!"<<endl;

for(i=0;i<len;i++)

free(snake[i]);

Sleep(INFINITE);

exit(0);

}

}

return 0;

}

我给你2个贪吃蛇c++代码

(1):

#include <stdioh>

#include <windowsh>

#include <timeh>

#include <conioh>

#include <stdlibh>

//方向键的ASCLL值:上72,左75,右77,下80

//背景颜色的代码: 0=黑色  1蓝色 2 绿色 3湖蓝色 4红色 5紫色 6** 7白色 8灰色 9淡蓝色

//改变当前光标方块的背景颜色和字体颜色//

void BackGround(unsigned int ForeColor = 7, unsigned int BackGroundColor = 0) {

HANDLE handle = GetStdHandle(STD_OUTPUT_HANDLE);  //获取控制台的句柄

SetConsoleTextAttribute(handle, ForeColor + BackGroundColor 0x10);//改变当前光标的背景和字体颜色

}

//改变光标的位置//

void gotoxy(int x, int y) {8

HANDLE handle;

COORD coord;   //获取坐标轴结构体

coordX = x;

coordY = y;

handle = GetStdHandle(STD_OUTPUT_HANDLE);  //获取控制台句柄,值为-11

SetConsoleCursorPosition(handle, coord);   //移动光标到x,y处

}

//初始化地图数据//

void restart(int bk[20][20], int look[4], int move[20][20]) {

//bk为总的地图数据记录整个地图,为1时表示墙体,为2时表示果实,为3时表示蛇

//look记录数据,为0时表示朝向,为1时表示长度,为3时表示胜负情况,为4表示分数

//move记录蛇走过的路程,用来打印蛇时判断用

int pp, qq;  //用来记录获取的随机坐标

//接下来要初始化整个地图//

for(int i=0;i<=16;i++)

for (int j = 0; j <= 16; j++) {

if (i == 0 || i == 16 || j == 0 || j == 16)  bk[i][j] = 1;//1表示墙体

else bk[i][j] = 0; //0表示什么都没有

move[i][j] = 0;    //该数组用来记录蛇移动的轨迹

}

//将蛇初始化在8,8坐标上

bk[8][8] = 3;

move[8][8] = 1;//则此时8,8,上的轨迹就应该记录为1

move[0][0] = 1;//用此来记录步数

pp = rand() % 15 + 1;//范围是1-15

qq = rand() % 15 + 1;

bk[pp][qq] = 2;//表示这个位置有果实了

look[0] = 1;//表示朝向,向上

look[1] = 1;//表示长度

look[2] = 0;//当为1是表示失败

look[3] = 0;//记录得分

//接下来要绘制地图//

for(int i=0;i<=16;i++)

for (int j = 0; j <= 16; j++) {

gotoxy(i 2, j);//光标移动,每个光标都是矩形

switch (bk[i][j]) {

case 0:

BackGround(0, 0);

break;//如果没有东西打印黑色

case 1:

BackGround(0, 1);

break;//墙打印蓝色

case 2:

BackGround(0, 2);

break;//果实打印绿色

case 3:

BackGround(0, 3);

break;//蛇打印湖蓝色

default:

break;

}

printf("  ");//地图中直接就是涂空格符

}

//接下来要显示积分//

gotoxy(35, 0);

BackGround(7, 0);//用白字黑底打印

printf("现在得分是:%d,请再接再厉!^_^", look[2]);

}

//运动主体//

void map(int bk[20][20], int look[4], int xy[2], int move[20][20]) {

//bk是地图信息,look作数据记录,xy记录坐标,move记录蛇的运动轨迹

int b[10], qq=0, pp=0;//b用来吸收输入,qq和pp用来随机初始化果实坐标

if (kbhit()) {//记录按下的是哪个方向键

b[0] = getch();//用b来记录

if (b[0] == 224)  b[0] = getch();//如果为224表示为方向键,但是要再一次获取才行

if (b[0] == 72 && look[0] != 2)

//如果输入的为上并且朝向不为下

look[0] = 1;

if (b[0] == 80 && look[0] != 1)

look[0] = 2;

if (b[0] == 75 && look[0] != 4)

look[0] = 3;

if (b[0] == 77 && look[0] != 3)

look[0] = 4;

}

switch (look[0]) {

case 1:

//往上走

xy[1]--;

break;

case 2:

//往下走

xy[1]++;

break;

case 3:

//往左走

xy[0]--;

break;

case 4:

//往右走

xy[0]++;

break;

}

//接下来蛇就开始走动了//

move[0][0]++;//蛇的步数加一

move[xy[0]][xy[1]] = move[0][0];//记录当前格子中蛇的轨迹

gotoxy(35, 2);

BackGround(7, 0);

printf("横坐标:%d,纵坐标:%d", xy[0],xy[1]);

gotoxy(xy[0] 2, xy[1]);//这里蛇头就往前移动了

BackGround(0, 3);//与蛇体一个颜色

printf("  ");

//如果吃了果实//

if (bk[xy[0]][xy[1]] == 2) {

look[2]++;//分数加一

look[1]++;//长度加一

//更新分数

gotoxy(35, 0);

BackGround(7, 0);

printf("现在得分是:%d,请再接再厉!^_^", look[2]);

while (bk[pp][qq] != 0) {

pp = rand() % 15 + 1;

qq = rand() % 15 + 1;

}

bk[pp][qq] = 2;//将这个地方变为果实

gotoxy(pp 2, qq);

BackGround(0, 2);

printf("  ");

}

//如果撞了墙或者自己//

if (bk[xy[0]][xy[1]] == 1 || bk[xy[0]][xy[1]] == 3) {

look[3] = 1;//表示已经输了

gotoxy(6, 6);

BackGround(7, 0);

printf("你输了,最后得分:%d", look[2]);

}

bk[xy[0]][xy[1]] = 3;//使这个位置变成蛇

//接下来要检测蛇然后刷新蛇的位置//

for(int i=0;i<=16;i++)

for (int j = 0; j <= 16; j++) {

if (move[i][j] == move[xy[0]][xy[1]] - look[1]){

//如果符合这个条件,则表示蛇已经移动出这个位置了

//要删除这个位置的蛇尾巴

//一次只有一个方块会符合要求吧?

bk[i][j] = 0;

gotoxy(i 2, j);

BackGround(0, 0);

printf("  ");

break;//一次只找一个

}

}

end:;

}

int main() {

int bk[20][20], xy[2], move[20][20], look[4];

xy[1] = xy[0] = 8;

srand((unsigned) time(NULL));//初始化随机种子

system("pause");

restart(bk, look, move);

while (look[3] == 0) {

Sleep(200);//休眠400ms一次

map(bk, look, xy, move);

}

system("pause");

printf("游戏结束,谢谢游玩!^_^");

return 0;

}

(2):

#include <stdioh>

#include <windowsh>

#include<conioh>

#include <stdlibh>

#include<timeh>

#define X 23//地图的x轴

#define Y 75//地图的y轴

#define UP 0

#define DOWN 1

#define LEFT 2

#define RIGHT 3

#define WAIT_TIME 200//等待蛇刷新的时间,可以说是速度  修改可变速

int map_0[X][Y];//地图

int Snake[XY][2]; // 蛇

int Slength; //蛇的长度

int direction;

int score=0;

bool pdEatFood=false;

void csh();

void huaMap();

void huaSnake();

void gotoxy(int x,int y);

void move();

void intokey();

int check(int x,int y);

void putfood();

bool gameover();

void dy_fs();

int main()

{

csh();

huaMap();

putfood();

while(1)

{

huaSnake();            

Sleep(WAIT_TIME);

intokey();

move();

dy_fs();

if(gameover())

{

system("cls");          //清除屏幕内容

printf("Game Over\n");

system("pause");

getchar();

break;

}

if(map_0[Snake[0][0]][Snake[0][1]]==-1)

{

map_0[Snake[0][0]][Snake[0][1]]=0;

pdEatFood=true;

putfood();

score+=10;

}

}

return 0;

}

void csh()//初始化

{

srand((unsigned)time(NULL)); //设置种子为现在的时间

Slength=4;

gotoxy(0,0);

CONSOLE_CURSOR_INFO cursor_info = {1, 0}; //清除光标

SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);

int x,y;

Snake[0][0]=X/2;

Snake[0][1]=Y/2;

for(x=0;x<X;x++){

map_0[x][0]=1;

map_0[x][Y-1]=1;

}

for(y=1;y<Y-1;y++){

map_0[0][y]=1;

map_0[X-1][y]=1;

}

for(x=1;x<4;x++){ //初始化蛇的坐标

Snake[x][0]=Snake[0][0]+x;

Snake[x][1]=Snake[0][1];

}

direction=UP;

}

void huaMap()//画地图

{

int x,y;

for(x=0;x<X101;x++){

for(y=0;y<Y101;y++){

if(map_0[x][y]==1){

printf("#");

}

if(map_0[x][y]==0){

printf(" ");

}

}

printf("\n");

}

}

void huaSnake()//画蛇

{

int x;

for(x=0;x<Slength;x++)

{

gotoxy(Snake[x][0],Snake[x][1]);

printf("@");

}

}

void gotoxy(int i,int j)//移动光标

{

COORD position={j,i};

SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),position);

}

void move()

{

int i;

gotoxy(Snake[Slength-1][0],Snake[Slength-1][1]);//擦除尾巴

printf(" ");                          

for(i=Slength-1;i>0;i--)    //从尾巴开始,每一个点的位置等于它前面一个点的位置

{

Snake[i][0]=Snake[i-1][0];

Snake[i][1]=Snake[i-1][1];

}

switch(direction)

{

case UP:

Snake[0][0]--;

break;

case DOWN:

Snake[0][0]++;

break;

case LEFT:

Snake[0][1]--;

break;

case RIGHT:

Snake[0][1]++;

break;

}

if(pdEatFood){

Slength++;

pdEatFood=false;

}

}

void intokey()

{

if(kbhit()!=0)          //kbhit()函数 检查当前是否有键盘输入,若有则返回一个非0值,否则返回0

{

char in;

while(!kbhit()==0)  //如果玩家输入了多个按键,以最后一个按键为准

in=getch();

switch(in)

{

case 'w':

case 'W':

if(direction!=DOWN)         //防止缩头

direction=UP;

break;

case 's':

case 'S':

if(direction!=UP)

direction=DOWN;

break;

case 'a':

case 'A':

if(direction!=RIGHT)

direction=LEFT;

break;

case 'd':

case 'D':

if(direction!=LEFT)

direction=RIGHT;

break;

case 'p':

case 'P':

gotoxy(X,0);      

system("pause");

gotoxy(X,0);

printf("                   ");  // 消去下面的按任意键继续

break;

}

}

}

int check(int ii,int jj){// 检查是否能投放食物

if(map_0[ii][jj]==1)

return 0;

if(ii==0 || jj==0 || ii==X-1 || jj==Y-1)

return 0;

int i;

for(i=0;i<Slength;i++){

if(ii==Snake[i][0] && jj==Snake[i][1])

return 0;

}

return 1;

}

void putfood()

{

int i,j;

do{

i=rand()%X;

j=rand()%Y;

}while(check(i,j)==0);

map_0[i][j]=-1;

gotoxy(i,j);

printf("$");

}

bool gameover()

{

bool isgameover=false;

int sX,sY;

sX=Snake[0][0],sY=Snake[0][1];

if(sX==0 || sX==X-1 || sY==0 || sY==Y-1)

isgameover=true;

int i;

for(i=1;i<Slength;i++){

if(sX==Snake[i][0] && sY==Snake[i][1])

isgameover=true;

}

return isgameover;

}

void dy_fs()

{

gotoxy(X,0);

printf("(c)Geek------2018122");

gotoxy(X+1,0);

printf("最终得分: %d",score);

}

管庆帆c/c++大师

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zz/9267983.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-26
下一篇 2023-04-26

发表评论

登录后才能评论

评论列表(0条)

保存