最近学了一些c语言的可视化编程,因此编了小游戏玩玩,途中也遇到了一些问题,要记得放图片的时候要把图片存在文件夹里,这些可以只写相对路径,不然如果直接写相对路径而又忘记把图片放在文件夹里就不能够显示出想要的结果。废话了这么多,是时候上代码了
#include<graphics.h>
#include<stdio.h>
#include<conio.h>
IMAGE backimg, wall, blank, box, people, end, dbox;
const int rows = 7;
const int cols = 8;
// 0 空地, 1 墙, 3 目的地, 4 箱子, 5 人
int map[7][8] = {
1,1,1,1,1,1,1,1,
1,1,1,0,0,0,1,1,
1,1,0,3,4,4,1,1,
1,1,0,1,0,0,3,1,
1,5,0,0,1,0,1,1,
1,1,1,1,0,1,1,1,
0,1,1,1,1,1,1,0};
//加载资源
void LoadImg()
{
loadimage(&backimg, "background.jpg", 64 * cols, 64 * rows);
loadimage(&wall, "wall.jpg", 64 , 64);
loadimage(&blank, "blank.jpg", 64 , 64);
loadimage(&box, "box.jpg", 64 , 64);
loadimage(&end, "end.jpg", 64 , 64);
loadimage(&people, "people.jpg", 64 , 64);
loadimage(&dbox, "dbox.jpg", 64 , 64 );
}
//初始化游戏界面
void InitGame()
{
int x, y;
for (int i = 0; i < 7; i++)
{
for (int j = 0; j < 8; j++)
{
x = j * 64;
y = i * 64;
switch (map[i][j])
{
case 0:
putimage(x, y, &blank);
break;
case 1:
putimage(x, y, &wall);
break;
case 3:
putimage(x, y, &end);
break;
case 4:
putimage(x, y, &box);
break;
case 5:
putimage(x, y, &people);
break;
case 7:
putimage(x, y, &dbox);
break;
case 8:
putimage(x, y, &people);
break;
}
}
}
}
//玩游戏
//上下左右-------w s a d
//ASCII码:上:72 下:80 左:75 右:77
void playGame()
{
char user;
int i = 0, j = 0;
while (1)
{
for (i = 0; i < 7; i++)
{
for (j = 0; j < 8; j++)
{
if (map[i][j] == 5 || map[i][j] == 8)
break;
}
if (map[i][j] == 5 || map[i][j] == 8)
break;
}
InitGame();
user = _getch();
switch (user)
{
case 75:
case 'a':
case 'A':
if (map[i][j - 1] == 0 || map[i][j - 1] == 3)
{
map[i][j] = map[i][j] - 5;
map[i][j - 1] += 5;
}
else if (map[i][j - 1] == 4 || map[i][j - 1] == 7)
{
if (map[i][j - 2] == 0 || map[i][j - 2] == 3)
{
map[i][j - 2] += 4;
map[i][j - 1] += 1;
map[i][j] -= 5;
}
}
break;
case 77:
case 'd':
case 'D':
if (map[i][j + 1] == 0 || map[i][j + 1] == 3)
{
map[i][j] = map[i][j] - 5;
map[i][j + 1] += 5;
}
else if (map[i][j + 1] == 4 || map[i][j + 1] == 7)
{
if (map[i][j + 2] == 0 || map[i][j + 2] == 3)
{
map[i][j + 2] += 4;
map[i][j + 1] += 1;
map[i][j] -= 5;
}
}
break;
case 72:
case 'w':
case 'W':
if (map[i - 1][j] == 0 || map[i - 1][j] == 3)
{
map[i][j] = map[i][j] - 5;
map[i - 1][j] += 5;
}
else if (map[i - 1][j] == 4 || map[i - 1][j] == 7)
{
if (map[i - 2][j] == 0 || map[i - 2][j] == 3)
{
map[i - 2][j] += 4;
map[i - 1][j] += 1;
map[i][j] -= 5;
}
}
break;
case 80:
case 's':
case 'S':
if (map[i + 1][j] == 0 || map[i + 1][j] == 3)
{
map[i][j] = map[i][j] - 5;
map[i + 1][j] += 5;
}
else if (map[i + 1][j] == 4 || map[i + 1][j] == 7)
{
if (map[i + 2][j] == 0 || map[i + 2][j] == 3)
{
map[i + 2][j] += 4;
map[i + 1][j] += 1;
map[i][j] -= 5;
}
}
break;
}
}
}
int main()
{
LoadImg();
initgraph(64 * cols, 64 * rows);
putimage(0,0,&backimg);
playGame();
closegraph();
return 0;
}
注释有点少,希望大家不要介意,毕竟萌新。
图片之类的大家可以自己做或者网上找找。