我已经开始用 C++ 制作一个简单的游戏。
在这个阶段,我将所有字符和属性(图块)存储在一个文件中,然后将其加载到 CHAR_INFO。然后使用 WriteConsoleOutputA 我基本上可以绘制地图/世界。
这一切似乎都可以正常工作,并且没有显示问题。然而,当我开始移动我的角色时,他正在破坏瓷砖。有点难以解释,所以这里有一个小视频。http://www.youtube.com/watch?v=v5Be5qz30r8。
如您所见,绿色瓷砖没有问题(前景和背景颜色相同)。但是当我靠近灰色瓷砖时,它并没有按预期工作。
main.cpp 片段...
int main()
{
while (0 < 1)
{
if (GetAsyncKeyState(VK_UP) || GetAsyncKeyState(0x57))
player.Move('u');
if (GetAsyncKeyState(VK_DOWN) || GetAsyncKeyState(0x53))
player.Move('d');
if (GetAsyncKeyState(VK_LEFT) || GetAsyncKeyState(0x41))
player.Move('l');
if (GetAsyncKeyState(VK_RIGHT) || GetAsyncKeyState(0x44))
player.Move('r');
Sleep(100);
}
}
字符类片段
void Character::Move(char d)
{
COORD oldLoc = loc;
char walkableTiles[12] = {
4, 179, 191, 192, 193, 194, 195, 196, 197, 217, 218, 255
};
//set character
switch (d)
{
case 'u' :
loc.Y--;
break;
case 'd':
loc.Y++;
break;
case 'l':
loc.X--;
break;
case 'r':
loc.X++;
break;
}
//setup the buffer and location of tiles
CHAR_INFO newTile[1];
COORD buffSize = {1,1};
COORD buffPos = {0,0};
SMALL_RECT newBuffArea = {loc.X, loc.Y, loc.X, loc.Y};
SMALL_RECT oldBuffArea = {oldLoc.X, oldLoc.Y, oldLoc.X, oldLoc.Y};
//store newTile info
ReadConsoleOutputA(outHnd, newTile, buffSize, buffPos, &newBuffArea);
//check if newTile is valid
bool valid = 0; // assume not valid
for (int i=0; i < sizeof(walkableTiles); i++)
{
if (newTile[0].Char.AsciiChar == walkableTiles[i])
valid = 1;
}
if (!valid)
{
loc = oldLoc;
return;
}
//restore oldTile information
WriteConsoleOutputA(outHnd, oldTile, buffSize, buffPos, &oldBuffArea);
//newTile becomes oldTile
oldTile[0] = newTile[0];
//get bg of newTile and set character/attributes
int bg = (newTile[0].Attributes & Blue << BG ) | (newTile[0].Attributes & Red << BG) | (newTile[0].Attributes & Green << BG) | (newTile[0].Attributes & BACKGROUND_INTENSITY);
newTile[0].Char.AsciiChar = 1;
newTile[0].Attributes = White | bg;
//place character on newTile
WriteConsoleOutputA(outHnd, newTile, buffSize, buffPos, &newBuffArea);
为代码道歉,这是我的第一个游戏。