
/贪吃蛇/
#include<stdioh>
#include<timeh>
#include<conioh>
#include<stdlibh>
inthead=3,tail=0;
intmain()
{
inti,j,k=0;
intzuobiao[2][80];
longstart;
intdirection=77;
intgamespeed;
inttimeover;
intchange(charqipan[20][80],
intzuobiao[2][80],
chardirection);
zuobiao[0][tail]=1;
zuobiao[1][tail]=1;
zuobiao[0][1]=1;
zuobiao[1][1]=2;zuobiao[0
[2]=1;
zuobiao[1][2]=3;
zuobiao[0][head]=1;
zuobiao[1][head]=4;
/处理棋盘/
charqipan[20][80];
//定义棋盘
for(i=0;i<20;i++)
for(j=0;j<80;j++)
qipan[i][j]='';//初始化棋盘
for(i=0;i<80;i++)
qipan[0][i]='_';
for(i=0;i<20;i++)
qipan[i][0]='|';
for(i=0;i<20;i++)
qipan[i][79]='|';
for(i=0;i<80;i++)
C语言是一门通用计算机编程语言,应用广泛。C语言的设计目标是提供一种能以简易的方式编译、处理低级存储器、产生少量的机器码以及不需要任何运行环境支持便能运行的编程语言。
//友情提示:如想速度快点,请改小_sleep(500)函数中参数
#include <stdioh>
#include <stdlibh>
#include <conioh>
#include <stringh>
#include <timeh>
const int H = 8; //地图的高
const int L = 16; //地图的长
char GameMap[H][L]; //游戏地图
int key; //按键保存
int sum = 1, over = 0; //蛇的长度, 游戏结束(自吃或碰墙)
int dx[4] = {0, 0, -1, 1}; //左、右、上、下的方向
int dy[4] = {-1, 1, 0, 0};
struct Snake //蛇的每个节点的数据类型
{
int x, y; //左边位置
int now; //保存当前节点的方向, 0,1,2,3分别为左右上下
}Snake[HL];
const char Shead = '@'; //蛇头
const char Sbody = '#'; //蛇身
const char Sfood = ''; //食物
const char Snode = ''; //''在地图上标示为空
void Initial(); //地图的初始化
void Create_Food(); //在地图上随机产生食物
void Show(); //刷新显示地图
void Button(); //取出按键,并判断方向
void Move(); //蛇的移动
void Check_Border(); //检查蛇头是否越界
void Check_Head(int x, int y); //检查蛇头移动后的位置情况
int main()
{
Initial();
Show();
return 0;
}
void Initial() //地图的初始化
{
int i, j;
int hx, hy;
system("title 贪吃蛇"); //控制台的标题
memset(GameMap, '', sizeof(GameMap)); //初始化地图全部为空''
system("cls");
srand(time(0)); //随机种子
hx = rand()%H; //产生蛇头
hy = rand()%L;
GameMap[hx][hy] = Shead;
Snake[0]x = hx; Snake[0]y = hy;
Snake[0]now = -1;
Create_Food(); //随机产生食物
for(i = 0; i < H; i++) //地图显示
{
for(j = 0; j < L; j++)
printf("%c", GameMap[i][j]);
printf("\n");
}
printf("\n小小C语言贪吃蛇\n");
printf("按任意方向键开始游戏\n");
getch(); //先接受一个按键,使蛇开始往该方向走
Button(); //取出按键,并判断方向
}
void Create_Food() //在地图上随机产生食物
{
int fx, fy;
while(1)
{
fx = rand()%H;
fy = rand()%L;
if(GameMap[fx][fy] == '') //不能出现在蛇所占有的位置
{
GameMap[fx][fy] = Sfood;
break;
}
}
}
void Show() //刷新显示地图
{
int i, j;
while(1)
{
_sleep(500); //延迟半秒(1000为1s),即每半秒刷新一次地图
Button(); //先判断按键在移动
Move();
if(over) //自吃或碰墙即游戏结束
{
printf("\n游戏结束\n");
printf(" >_<\n");
getchar();
break;
}
system("cls"); //清空地图再显示刷新吼的地图
for(i = 0; i < H; i++)
{
for(j = 0; j < L; j++)
printf("%c", GameMap[i][j]);
printf("\n");
}
printf("\n小小C语言贪吃蛇\n");
printf("按任意方向键开始游戏\n");
}
}
void Button() //取出按键,并判断方向
{
if(kbhit() != 0) //检查当前是否有键盘输入,若有则返回一个非0值,否则返回0
{
while(kbhit() != 0) //可能存在多个按键,要全部取完,以最后一个为主
key = getch(); //将按键从控制台中取出并保存到key中
switch(key)
{ //左
case 75: Snake[0]now = 0;
break;
//右
case 77: Snake[0]now = 1;
break;
//上
case 72: Snake[0]now = 2;
break;
//下
case 80: Snake[0]now = 3;
break;
}
}
}
void Move() //蛇的移动
{
int i, x, y;
int t = sum; //保存当前蛇的长度
//记录当前蛇头的位置,并设置为空,蛇头先移动
x = Snake[0]x; y = Snake[0]y; GameMap[x][y] = '';
Snake[0]x = Snake[0]x + dx[ Snake[0]now ];
Snake[0]y = Snake[0]y + dy[ Snake[0]now ];
Check_Border(); //蛇头是否越界
Check_Head(x, y); //蛇头移动后的位置情况,参数为: 蛇头的开始位置
if(sum == t) //未吃到食物即蛇身移动哦
for(i = 1; i < sum; i++) //要从蛇尾节点向前移动哦,前一个节点作为参照
{
if(i == 1) //尾节点设置为空再移动
GameMap[ Snake[i]x ][ Snake[i]y ] = '';
if(i == sum-1) //为蛇头后面的蛇身节点,特殊处理
{
Snake[i]x = x;
Snake[i]y = y;
Snake[i]now = Snake[0]now;
}
else //其他蛇身即走到前一个蛇身位置
{
Snake[i]x = Snake[i+1]x;
Snake[i]y = Snake[i+1]y;
Snake[i]now = Snake[i+1]now;
}
GameMap[ Snake[i]x ][ Snake[i]y ] = '#'; //移动后要置为'#'蛇身
}
}
void Check_Border() //检查蛇头是否越界
{
if(Snake[0]x < 0 || Snake[0]x >= H
|| Snake[0]y < 0 || Snake[0]y >= L)
over = 1;
}
void Check_Head(int x, int y) //检查蛇头移动后的位置情况
{
if(GameMap[ Snake[0]x ][ Snake[0]y ] == '') //为空
GameMap[ Snake[0]x ][ Snake[0]y ] = '@';
else
if(GameMap[ Snake[0]x ][ Snake[0]y ] == '') //为食物
{
GameMap[ Snake[0]x ][ Snake[0]y ] = '@';
Snake[sum]x = x; //新增加的蛇身为蛇头后面的那个
Snake[sum]y = y;
Snake[sum]now = Snake[0]now;
GameMap[ Snake[sum]x ][ Snake[sum]y ] = '#';
sum++;
Create_Food(); //食物吃完了马上再产生一个食物
}
else
over = 1;
}
/
Desc: 俄罗斯方块游戏
By: hoodlum1980
Email: jinfd@126com
Date: 20080312 22:30
/
#include <stdioh>
#include <biosh>
#include <dosh>
#include <graphicsh>
#include <stringh>
#include <stdlibh>
#define true 1
#define false 0
#define BoardWidth 12
#define BoardHeight 23
#define _INNER_HELPER / inner helper method /
/Scan Codes Define/
enum KEYCODES
{
K_ESC =0x011b,
K_UP =0x4800, / upward arrow /
K_LEFT =0x4b00,
K_DOWN =0x5000,
K_RIGHT =0x4d00,
K_SPACE =0x3920,
K_P =0x1970
};
/ the data structure of the block /
typedef struct tagBlock
{
char c[4][4]; / cell fill info array, 0-empty, 1-filled /
int x; / block position cx [ 0,BoardWidht -1] /
int y; / block position cy [-4,BoardHeight-1] /
char color; / block color /
char size; / block max size in width or height /
char name; / block name (the block's shape) /
} Block;
/ game's global info /
int FrameTime= 1300;
int CellSize= 18;
int BoardLeft= 30;
int BoardTop= 30;
/ next block grid /
int NBBoardLeft= 300;
int NBBoardTop= 30;
int NBCellSize= 10;
/ score board position /
int ScoreBoardLeft= 300;
int ScoreBoardTop=100;
int ScoreBoardWidth=200;
int ScoreBoardHeight=35;
int ScoreColor=LIGHTCYAN;
/ infor text postion /
int InfoLeft=300;
int InfoTop=200;
int InfoColor=YELLOW;
int BorderColor=DARKGRAY;
int BkGndColor=BLACK;
int GameRunning=true;
int TopLine=BoardHeight-1; / top empty line /
int TotalScore=100;
char info_score[20];
char info_help[255];
char info_common[255];
/ our board, Board[x][y][0]-isFilled, Board[x][y][1]-fillColor /
unsigned char Board[BoardWidth][BoardHeight][2];
char BufferCells[4][4]; / used to judge if can rotate block /
Block curBlock; / current moving block /
Block nextBlock; / next Block to appear /
/ function list /
int GetKeyCode();
int CanMove(int dx,int dy);
int CanRotate();
int RotateBlock(Block block);
int MoveBlock(Block block,int dx,int dy);
void DrawBlock(Block block,int,int,int);
void EraseBlock(Block block,int,int,int);
void DisplayScore();
void DisplayInfo(char text);
void GenerateBlock(Block block);
void NextBlock();
void InitGame();
int PauseGame();
void QuitGame();
/Get Key Code /
int GetKeyCode()
{
int key=0;
if(bioskey(1))
{
key=bioskey(0);
}
return key;
}
/ display text! /
void DisplayInfo(char text)
{
setcolor(BkGndColor);
outtextxy(InfoLeft,InfoTop,info_common);
strcpy(info_common,text);
setcolor(InfoColor);
outtextxy(InfoLeft,InfoTop,info_common);
}
/ create a new block by key number,
the block anchor to the top-left corner of 44 cells
/
void _INNER_HELPER GenerateBlock(Block block)
{
int key=(random(13)random(17)+random(1000)+random(3000))%7;
block->size=3;/ because most blocks' size=3 /
memset(block->c,0,16);
switch(key)
{
case 0:
block->name='T';
block->color=RED;
block->c[1][0]=1;
block->c[1][1]=1, block->c[2][1]=1;
block->c[1][2]=1;
break;
case 1:
block->name='L';
block->color=YELLOW;
block->c[1][0]=1;
block->c[1][1]=1;
block->c[1][2]=1, block->c[2][2]=1;
break;
case 2:
block->name='J';
block->color=LIGHTGRAY;
block->c[1][0]=1;
block->c[1][1]=1;
block->c[1][2]=1, block->c[0][2]=1;
break;
case 3:
block->name='z';
block->color=CYAN;
block->c[0][0]=1, block->c[1][0]=1;
block->c[1][1]=1, block->c[2][1]=1;
break;
case 4:
block->name='5';
block->color=LIGHTBLUE;
block->c[1][0]=1, block->c[2][0]=1;
block->c[0][1]=1, block->c[1][1]=1;
break;
case 5:
block->name='o';
block->color=BLUE;
block->size=2;
block->c[0][0]=1, block->c[1][0]=1;
block->c[0][1]=1, block->c[1][1]=1;
break;
case 6:
block->name='I';
block->color=GREEN;
block->size=4;
block->c[1][0]=1;
block->c[1][1]=1;
block->c[1][2]=1;
block->c[1][3]=1;
break;
}
}
/ get next block! /
void NextBlock()
{
/ copy the nextBlock to curBlock /
curBlocksize=nextBlocksize;
curBlockcolor=nextBlockcolor;
curBlockx=(BoardWidth-4)/2;
curBlocky=-curBlocksize;
memcpy(curBlockc,nextBlockc,16);
/ generate nextBlock and show it /
EraseBlock(&nextBlock,NBBoardLeft,NBBoardTop,NBCellSize);
GenerateBlock(&nextBlock);
nextBlockx=1,nextBlocky=0;
DrawBlock(&nextBlock,NBBoardLeft,NBBoardTop,NBCellSize);
}
/ rotate the block, update the block struct data /
int _INNER_HELPER RotateCells(char c[4][4],char blockSize)
{
char temp,i,j;
switch(blockSize)
{
case 3:
temp=c[0][0];
c[0][0]=c[2][0], c[2][0]=c[2][2], c[2][2]=c[0][2], c[0][2]=temp;
temp=c[0][1];
c[0][1]=c[1][0], c[1][0]=c[2][1], c[2][1]=c[1][2], c[1][2]=temp;
break;
case 4: / only 'I' block arived here! /
c[1][0]=1-c[1][0], c[1][2]=1-c[1][2], c[1][3]=1-c[1][3];
c[0][1]=1-c[0][1], c[2][1]=1-c[2][1], c[3][1]=1-c[3][1];
break;
}
}
/ judge if the block can move toward the direction /
int CanMove(int dx,int dy)
{
int i,j,tempX,tempY;
for(i=0;i<curBlocksize;i++)
{
for(j=0;j<curBlocksize;j++)
{
if(curBlockc[i][j])
{
/ cannot move leftward or rightward /
tempX = curBlockx + i + dx;
if(tempX<0 || tempX>(BoardWidth-1)) return false; / make sure x is valid! /
/ cannot move downward /
tempY = curBlocky + j + dy;
if(tempY>(BoardHeight-1)) return false; / y is only checked lower bound, maybe negative!!!! /
/ the cell already filled, we must check Y's upper bound before check cell ! /
if(tempY>=0 && Board[tempX][tempY][0]) return false;
}
}
}
return true;
}
/ judge if the block can rotate /
int CanRotate()
{
int i,j,tempX,tempY;
/ update buffer /
memcpy(BufferCells, curBlockc, 16);
RotateCells(BufferCells,curBlocksize);
for(i=0;i<curBlocksize;i++)
{
for(j=0;j<curBlocksize;j++)
{
if(BufferCells[i][j])
{
tempX=curBlockx+i;
tempY=curBlocky+j;
if(tempX<0 || tempX>(BoardWidth-1))
return false;
if(tempY>(BoardHeight-1))
return false;
if(tempY>=0 && Board[tempX][tempY][0])
return false;
}
}
}
return true;
}
/ draw the block /
void _INNER_HELPER DrawBlock(Block block,int bdLeft,int bdTop,int cellSize)
{
int i,j;
setfillstyle(SOLID_FILL,block->color);
for(i=0;i<block->size;i++)
{
for(j=0;j<block->size;j++)
{
if(block->c[i][j] && (block->y+j)>=0)
{
floodfill(
bdLeft+cellSize(i+block->x)+cellSize/2,
bdTop+cellSize(j+block->y)+cellSize/2,
BorderColor);
}
}
}
}
/ Rotate the block, if success, return true /
int RotateBlock(Block block)
{
char temp,i,j;
int b_success;
if(curBlocksize==2)
return;
if(( b_success=CanRotate()))
{
EraseBlock(block,BoardLeft,BoardTop,CellSize);
memcpy(curBlockc,BufferCells,16);
DrawBlock(block,BoardLeft,BoardTop,CellSize);
}
return b_success;
}
/ erase a block, only fill the filled cell with background color /
void _INNER_HELPER EraseBlock(Block block,int bdLeft,int bdTop,int cellSize)
{
int i,j;
setfillstyle(SOLID_FILL,BkGndColor);
for(i=0;i<block->size;i++)
{
for(j=0;j<block->size;j++)
{
if(block->c[i][j] && (block->y+j>=0))
{
floodfill(
bdLeft+cellSize(i+block->x)+cellSize/2,
bdTop+cellSize(j+block->y)+cellSize/2,
BorderColor);
}
}
}
}
/ move by the direction if can, donothing if cannot
return value: true - success, false - cannot move toward this direction
/
int MoveBlock(Block block,int dx,int dy)
{
int b_canmove=CanMove(dx,dy);
if(b_canmove)
{
EraseBlock(block,BoardLeft,BoardTop,CellSize);
curBlockx+=dx;
curBlocky+=dy;
DrawBlock(block,BoardLeft,BoardTop,CellSize);
}
return b_canmove;
}
/ drop the block to the bottom! /
int DropBlock(Block block)
{
EraseBlock(block,BoardLeft,BoardTop,CellSize);
while(CanMove(0,1))
{
curBlocky++;
}
DrawBlock(block,BoardLeft,BoardTop,CellSize);
return 0;/ return value is assign to the block's alive /
}
/ init the graphics mode, draw the board grid /
void InitGame()
{
int i,j,gdriver=DETECT,gmode;
struct time sysTime;
/ draw board cells /
memset(Board,0,BoardWidthBoardHeight2);
memset(nextBlockc,0,16);
strcpy(info_help,"P: Pause Game --by hoodlum1980");
initgraph(&gdriver,&gmode,"c:\\tc\\");
setcolor(BorderColor);
for(i=0;i<=BoardWidth;i++)
{
line(BoardLeft+iCellSize, BoardTop, BoardLeft+iCellSize, BoardTop+ BoardHeightCellSize);
}
for(i=0;i<=BoardHeight;i++)
{
line(BoardLeft, BoardTop+iCellSize, BoardLeft+BoardWidthCellSize, BoardTop+ iCellSize);
}
/ draw board outer border rect /
rectangle(BoardLeft-CellSize/4, BoardTop-CellSize/4,
BoardLeft+BoardWidthCellSize+CellSize/4,
BoardTop+BoardHeightCellSize+CellSize/4);
/ draw next block grids /
for(i=0;i<=4;i++)
{
line(NBBoardLeft+iNBCellSize, NBBoardTop, NBBoardLeft+iNBCellSize, NBBoardTop+4NBCellSize);
line(NBBoardLeft, NBBoardTop+iNBCellSize, NBBoardLeft+4NBCellSize, NBBoardTop+ iNBCellSize);
}
/ draw score rect /
rectangle(ScoreBoardLeft,ScoreBoardTop,ScoreBoardLeft+ScoreBoardWidth,ScoreBoardTop+ScoreBoardHeight);
DisplayScore();
/ set new seed! /
gettime(&sysTime);
srand(sysTimeti_hour3600+sysTimeti_min60+sysTimeti_sec);
GenerateBlock(&nextBlock);
NextBlock(); / create first block /
setcolor(DARKGRAY);
outtextxy(InfoLeft,InfoTop+20,"Up -rotate Space-drop");
outtextxy(InfoLeft,InfoTop+35,"Left-left Right-right");
outtextxy(InfoLeft,InfoTop+50,"Esc -exit");
DisplayInfo(info_help);
}
/ set the isFilled and fillcolor data to the board /
void _INNER_HELPER FillBoardData()
{
int i,j;
for(i=0;i<curBlocksize;i++)
{
for(j=0;j<curBlocksize;j++)
{
if(curBlockc[i][j] && (curBlocky+j)>=0)
{
Board[curBlockx+i][curBlocky+j][0]=1;
Board[curBlockx+i][curBlocky+j][1]=curBlockcolor;
}
}
}
}
/ draw one line of the board /
void _INNER_HELPER PaintBoard()
{
int i,j,fillcolor;
for(j=max((TopLine-4),0);j<BoardHeight;j++)
{
for(i=0;i<BoardWidth;i++)
{
fillcolor=Board[i][j][0] Board[i][j][1]:BkGndColor;
setfillstyle(SOLID_FILL,fillcolor);
floodfill(BoardLeft+iCellSize+CellSize/2,BoardTop+jCellSize+CellSize/2,BorderColor);
}
}
}
/ check if one line if filled full and increase the totalScore! /
void _INNER_HELPER CheckBoard()
{
int i,j,k,score=10,sum=0,topy,lines=0;
/ we find the top empty line! /
j=topy=BoardHeight-1;
do
{
sum=0;
for(i=0;i< BoardWidth; i++)
{
sum+=Board[i][topy][0];
}
topy--;
} while(sum>0 && topy>0);
/ remove the full filled line (max remove lines count = 4) /
do
{
sum=0;
for(i=0;i< BoardWidth; i++)
sum+=Board[i][j][0];
if(sum==BoardWidth)/ we find this line is full filled, remove it! /
{
/ move the cells data down one line /
for(k=j; k > topy;k--)
{
for(i=0;i<BoardWidth;i++)
{
Board[i][k][0]=Board[i][k-1][0];
Board[i][k][1]=Board[i][k-1][1];
}
}
/ make the top line empty! /
for(i=0;i<BoardWidth;i++)
{
Board[i][topy][0]=0;
Board[i][topy][1]=0;
}
topy++; / move the topline downward one line! /
lines++; / lines <=4 /
TotalScore+=score;
score=2; / adding: 10, 30, 70, 150 /
}
else
j--;
} while(sum>0 && j>topy && lines<4);
/ speed up the game when score is high, minimum is 400 /
FrameTime=max(1200-100(TotalScore/200), 400);
TopLine=topy;/ update the top line /
/ if no lines remove, only add 1: /
if(lines==0)
TotalScore++;
}
/ display the score /
void _INNER_HELPER DisplayScore()
{
setcolor(BkGndColor);
outtextxy(ScoreBoardLeft+5,ScoreBoardTop+5,info_score);
setcolor(ScoreColor);
sprintf(info_score,"Score: %d",TotalScore);
outtextxy(ScoreBoardLeft+5,ScoreBoardTop+5,info_score);
}
/ we call this function when a block is inactive /
void UpdateBoard()
{
FillBoardData();
CheckBoard();
PaintBoard();
DisplayScore();
}
/ pause the game, and timer handler stop move down the block! /
int PauseGame()
{
int key=0;
DisplayInfo("Press P to Start or Resume!");
while(key!=K_P && key!=K_ESC)
{
while(!(key=GetKeyCode())){}
}
DisplayInfo(info_help);
return key;
}
/ quit the game and do cleaning work /
void QuitGame()
{
closegraph();
}
/ the entry point function /
void main()
{
int i,flag=1,j,key=0,tick=0;
InitGame();
if(PauseGame()==K_ESC)
goto GameOver;
/ wait until a key pressed /
while(key!=K_ESC)
{
/ wait until a key pressed /
while(!(key=GetKeyCode()))
{
tick++;
if(tick>=FrameTime)
{
/ our block has dead! (can't move down), we get next block /
if(!MoveBlock(&curBlock,0,1))
{
UpdateBoard();
NextBlock();
if(!CanMove(0,1))
goto GameOver;
}
tick=0;
}
delay(100);
}
switch(key)
{
case K_LEFT:
MoveBlock(&curBlock,-1,0);
break;
case K_RIGHT:
MoveBlock(&curBlock,1,0);
break;
case K_DOWN:
MoveBlock(&curBlock,0,1);
break;
case K_UP:
RotateBlock(&curBlock);
break;
case K_SPACE:
DropBlock(&curBlock);
break;
case K_P:
PauseGame();
break;
}
}
GameOver:
DisplayInfo("GAME OVER! Press any key to exit!");
getch(); / wait the user Press any key /
QuitGame();
}
俄罗斯方块的C语言实现,在WIN-TC上编译通过。
一个“歼灭敌机”的小游戏,DEVc++编译通过:
#include <stdioh>
#include <conioh>
#include <stdlibh>
#include <windowsh>
#include <timeh>
#define zlx 10 //增量坐标(x)让游戏框不靠边
#define zly 3 //增量坐标(y)让游戏框不靠边
#define W 26 //游戏框的宽度
#define H 24 //游戏框的高度
int jiem[22][22]={0}, wj=10; //界面数组, 我机位置(初值为10)
int speed=4,density=30, score=0,death=0; //敌机速度, 敌机密度, 玩家成绩,死亡次数
int m=0,n=0; // m,n是控制敌机的变量
void gtxy (int x, int y) //控制光标位置的函数
{ COORD pos;
posX = x; posY = y;
SetConsoleCursorPosition ( GetStdHandle (STD_OUTPUT_HANDLE), pos );
}
void Color(int a) //设定颜色的函数(a应为1-15)
{ SetConsoleTextAttribute( GetStdHandle(STD_OUTPUT_HANDLE), a ); }
void yinc(int x=1,int y=0) //隐藏光标的函数
{ CONSOLE_CURSOR_INFO gb={x,y}; //y设为0即隐藏
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &gb);
}
void csh( ) //初始化函数
{ int i;
Color(7);
gtxy(zlx,zly); printf("╔"); gtxy(zlx+W-2,zly); printf("╗"); //左上角和右上角的框角
gtxy(zlx,zly+H-1); printf("╚"); gtxy(zlx+W-2,zly+H-1); printf("╝"); //下边两框角
for(i=2;i<W-2;i+=2) {gtxy(zlx+i,zly); printf("═"); } //打印上横框
for(i=2;i<W-2;i+=2) {gtxy(zlx+i,zly+H-1); printf("═"); } //打印下横框
for(i=1;i<H-1;i++) { gtxy(zlx,zly+i); printf("║"); } //打印左竖框
for(i=1;i<H-1;i++) {gtxy(zlx+W-2,zly+i); printf("║"); } //打印右竖框
Color(14);gtxy(19,2); printf("歼灭敌机"); Color(10);
gtxy(37,5); printf("设置:Esc ");
gtxy(37,7); printf("发射:↑ ");
gtxy(37,9); printf("控制:← → ");
gtxy(37,11);printf("得分:%d",score);
gtxy(37,13); printf("死亡:%d",death);
yinc(1,0);
}
void qcjm( ) //清除界面函数
{int i,j;
for(i=0;i<H-2;i++)
for(j=0;j<W-4;j++){gtxy(zlx+2+j,zly+1+i);printf(" ");}
}
void feiji( ) //飞机移动函数
{int i,j;
for(i=21;i>=0;i--) //从底行往上是为了避免敌机直接冲出数组
for(j=0;j<22;j++)
{if(i==21&&jiem[i][j]==3) jiem[i][j]=0; //底行赋值0 以免越界
if(jiem[i][j]==3) jiem[i][j]=0, jiem[i+1][j]=3;
}
if(jiem[20][wj]==3&&jiem[21][wj]==1) death++;
}
void zidan( ) //子d移动函数
{ int i,j;
for(i=0;i<22;i++)
for(j=0;j<22;j++)
{if(i==0&&jiem[i][j]==2) jiem[i][j]=0;
if(jiem[i][j]==2) { if(jiem[i-1][j]==3) score+=100,printf("\7");
jiem[i][j]=0,jiem[i-1][j]=2; }
}
}
void print( ) //输出界面函数
{int i,j;
qcjm( );
for(i=0;i<22;i++)
for(j=0;j<22;j++)
{ gtxy(12+j,4+i);
if(jiem[i][j]==3) {Color(13);printf("□");}
if(jiem[i][j]==2) {Color(10);printf("");}
if(jiem[i][j]==1) {Color(10);printf("■");}
}
gtxy(37,11); Color(10);printf("得分:%d",score);
gtxy(37,13); printf("死亡:%d",death);
}
void setting( ) //游戏设置函数
{ qcjm( );
gtxy(12,4);printf("选择敌机速度:");
gtxy(12,5);printf(" 1快 2中 3慢>>");
switch(getche( ))
{case '1': speed=2; break;
case '2': speed=4; break;
case '3': speed=5; break;
default: gtxy(12,6);printf(" 错误!默认值");
}
gtxy(12,7);printf("选择敌机密度:");
gtxy(12,8);printf(" 1大 2中 3小>>");
switch(getche( ))
{case '1': density=20; break;
case '2': density=30; break;
case '3': density=40; break;
default: gtxy(12,9);printf(" 错误!默认值");
}
for(int i=0;i<22;i++)
for(int j=0;j<22;j++)jiem[i][j]=0;
jiem[21][wj=10]=1; jiem[0][5]=3;
gtxy(12,10);printf(" 按任意键保存");
getch( );
qcjm( );
}
void run( ) //游戏运行函数
{ jiem[21][wj]=1; //值为1代表我机(2则为子d)
jiem[0][5]=3; //值为3代表敌机
SetConsoleTitle("歼灭敌机"); //设置窗口标题
while(1)
{ if (kbhit( )) //如有键按下,控制我机左右移动、发射或进行设定
{int key;
if((key=getch( ))==224) key=getch( );
switch(key)
{ case 75: if(wj>0) jiem[21][wj]=0,jiem[21][--wj]=1; break;
case 77: if(wj<20) jiem[21][wj]=0,jiem[21][++wj]=1; break;
case 72: jiem[20][wj]=2; break;
case 27: setting( );
}
}
if(++n%density==0) //控制产生敌机的速度
{ n=0;srand((unsigned)time(NULL));
jiem[0][rand( )%20+1]=3;
}
if(++m%speed==0) {feiji( ); m=0;} //控制敌机移动速度(相对子d而言)
zidan( );
print( );
Sleep(120); //延时120毫秒
}
}
int main( )
{csh( );
run( );
return 0;
}
新手要方便写代码,可以收藏下面几个自编函数:
SetConsoleTitle("俄罗斯方块"); //设置窗口左上角标题栏处出现"俄罗斯方块"5个字
srand( (unsigned) time(NULL) ); //初始化随机数发生器
n= rand( ) % 20; //产生随机数0-19中的一个 如 rand( )%5 就产生0-4中的一个数
SetConsoleTitle( )函数在<windowsh>里, srand( )函数与rand( )函数要配合用,
就是同时要用,在<stdlibh>里。如果 rand( )%10+1 就产生1-10之中的一个数。
Sleep(300); //延时300毫秒(就是程序暂停300毫秒后继续运行)
system("cls"); //清屏(把窗口里的内容全部清除,光标定于(0,0)位置处)
这两个函数都在<windowsh>里。开头4个自编函数 编写如下:
void gtxy (int x, int y) //控制光标位置的函数
{ COORD pos;
posX = x;
posY = y;
SetConsoleCursorPosition ( GetStdHandle (STD_OUTPUT_HANDLE), pos );
}
void Color (int a) //设定颜色的函数
{ SetConsoleTextAttribute ( GetStdHandle ( STD_OUTPUT_HANDLE ),a ); }
void yinc (int x,int y) //隐藏光标的函数
{ CONSOLE_CURSOR_INFO gb={ x , y }; //gb代表光标
SetConsoleCursorInfo ( GetStdHandle(STD_OUTPUT_HANDLE), &gb );
}
void kou(int w,int h) //设置窗口大小的函数
{HANDLE hl=GetStdHandle ( STD_OUTPUT_HANDLE ) ;
COORD size={ w , h };
SetConsoleScreenBufferSize( hl , size );
SMALL_RECT rc={ 0, 0, w, h };
SetConsoleWindowInfo( hl, 1, &rc );
}
最后这个函数,参数w是宽h是高。里边5行中第一行定义了句柄型变量hl,并给它赋值。
第二行定义了坐标型结构体变量size,它的取值决定了缓冲区的大小。第三行就是使用
size的值设置好缓冲区大小。第四行定义了变量rc,它的值决定当前窗口显示的位置与
大小(不得超过缓冲区的大小)。前两个0,0是从缓冲区左上角0列0行位置处开始,后两
个参数可以小于w和h比如 rc={0,0,w-10,h-5}; 最后一行使用rc的值设置好窗口,中间
那个参数要为" 1 "或写“ true ”才有效。
以上就是关于用C语言编写的小游戏代码是什么全部的内容,包括:用C语言编写的小游戏代码是什么、C语言的贪吃蛇源代码、帮忙编写小游戏c语言小程序 谢谢等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)