我写了一个迷宫游戏,画图代码如下
void show()
{
BeginBatchDraw();
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++) {
if (a[i][j] == 1)
putimage(i * 75, j * 75, &kg, NOTSRCERASE);
else if (a[i][j] == 0)
putimage(i * 75, j * 75, &kk, NOTSRCERASE);
else if(a[i][j]== 5)
putimage(i * 75, j * 75, &people, NOTSRCERASE);
FlushBatchDraw();
}
}
EndBatchDraw();
Sleep(100);
}
这段代码我想实现的是,当人移动时,原来那个图片会被覆盖住,可是运行结果似乎是随机的,有时能覆盖住,有时不能,这样到达终点后,有好几个关于人的图片,不是我想要的,该如何解决?
还有几个小问题请教
1,屏幕仍然会闪烁,可是我加了flush,end这些函数啊?
2,按键控制移动的时候,按一下,会走好几下,这个该怎么办?
3,不贴图,直接打印出数(1,0,5)来表达迷宫的时候,运行是正确的,说明移动函数应该没有问题,但我发现不贴图和贴图之后,方向键反了,原本控制上下的变成了左右键,控制左右的变成了上下键,这是为什么?
以下是完整代码:
#include<iostream>
#include<stack>
#include<stdlib.h>
#define _CRT_SECURE_NO_WARNINGS
#include<graphics.h>
#include<conio.h>
# include<math.h>
# include< stdio.h>
#include<windows.h>
#include<time.h>
# pragma comment(lib,"Winmm.lib")
#define High 600 //游戏画面尺寸
#define Width 600
IMAGE kg, kk; //障碍和通路图片
IMAGE people; //人的图片
int a[8][8] = { {1,1,1,1,1,1,1,1},{1,5,0,1,0,0,1,1},{1,0,0,1,0,0,0,1},{1,1,0,0,0,1,0,1},{1,0,0,1,1,1,0,1},{1,0,0,0,0,0,1,1},{1,0,1,0,0,0,0,1},{1,1,1,1,1,1,1,1} };
int x=1, y=1;
void show();
void updateWithInput();
void starup();
int main() {
starup();
x = 1;
y = 1;
a[x][y] = 5;//设置起点,"5"表示人,"1"表示障碍,"0"表示通路
show();//显示画面
while (x!=6||y!=6)//终点为(6,6)
{
updateWithInput();//按键控制
}
Sleep(5000);
EndBatchDraw();
closegraph();
}
void updateWithInput()
{
if ((GetAsyncKeyState(VK_LEFT) & 0x8000)) //左方向键
{
if (a[x][y-1] != 1) {
a[x][y] = 0;
a[x ][y-1] = 5;
y--;
show();
show();
}
}
if ((GetAsyncKeyState(VK_RIGHT) & 0x8000))//右方向键
{
if (a[x][y+1] != 1) {
a[x][y] = 0;
a[x ][y+1] = 5;
y++;
show();
show();
}
}
if ((GetAsyncKeyState(VK_UP) & 0x8000))//上方向键
{
if (a[x-1][y ] != 1) {
a[x][y] = 0;
a[x-1][y ] = 5;
x--;
show();
show();
}
}
if ((GetAsyncKeyState(VK_DOWN) & 0x8000))//下方向键
{
if (a[x+1][y] != 1) {
a[x][y] = 0;
a[x+1][y] = 5;
x++;
show();
show();
}
}
}
void show()
{
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++) {
if (a[i][j] == 1)
putimage(i * 75, j * 75, &kg, NOTSRCERASE);
else if (a[i][j] == 0)
putimage(i * 75, j * 75, &kk, NOTSRCERASE);
else if(a[i][j]== 5)
putimage(i * 75, j * 75, &people, NOTSRCERASE);
}
}
FlushBatchDraw();
}
void starup() {
initgraph(Width, High);
BeginBatchDraw();
HWND hwnd = GetHWnd();
SetWindowText(hwnd, "迷宫游戏");
loadimage(&kk, ".\\kk.jpg");;
loadimage(&kg, ".\\kg.jpg");
loadimage(&people, ".\\people.jpg");
}