我目前正在編寫一個程序,根據房子的大小在屏幕上顯示一個房子,它也會檢測到'A'
'S'
'W'
'D'
按鍵和esc按鍵上的中斷。現在我已經獲得了所有這些功能,並借用了清晰的屏幕功能。我想將這張圖片在屏幕上上下移動。我知道我非常接近,但我不知道我應該如何去移動圖片。如果用戶按下「d」,我希望程序向右移動,我假設這將像在x座標上加1,按「a」向左移動,從x減去1,同樣向上向下,將按「w」或「s」並加上或減去y值。如何使用按鍵將圖片移動到屏幕上?
#include <windows.h>
#include <iostream>
#include <cstdlib>
#include <conio.h>
using namespace std;
void ClearScreen();
void draw(int j)
{
cout <<" /";
for(int c=0; c<j; c++)
{
cout <<" ";
}
{
cout << "\\ \n";
}
cout << " /";
for(int c=0; c<j; c++)
{
cout << " ";
}
cout <<" \\ \n";
cout << "/";
for(int c=0; c<j; c++)
{
cout <<" ";
}
cout <<" \\ \n";
cout <<"|";
for(int c=0; c<j; c++)
{
cout << "----";
}
cout <<"| \n";
cout <<"|";
for(int c=0; c<j; c++)
{
cout << " ";
}
cout <<"| \n";
cout <<"|";
for(int c=0; c<j; c++)
{
cout << " ";
}
cout <<"| \n";
cout <<"|";
for(int c=0; c<j; c++)
{
cout << "----";
}
cout <<"| \n";
}
/////////////////////////////////
////////////////////////////////
void Move(int key,int housesize)
{
if (key ==97)
{
cout << "you pressed 'a' \n";
draw(housesize);
}
else if (key==115)
{
cout<< "you pressed 's' \n \t";
draw(housesize);
}
else if (key==100)
{
cout<< "you pressed 'd' \n";
draw(housesize);
}
else if (key==119)
{
cout<< "you pressed 'w' \n";
draw(housesize);
}
}
////// MAIN //////////////
int main(int argc, char *argv[])
{
int i,number;
char letter;
cout << "How large would you like me to draw a house from 1 to 5? \n";
cin >> i;
draw(i);
cout << "Press a key to move the picture and esc to close \n";
while(1)
{
letter=getch();
number=letter;
if(number==27)
{
break;
}
else if (number !=27)
{
Move(number, i);
}
ClearScreen();
Move(number, i);
}
system ("PAUSE");
return 0;
}
////// CLEARSCREEN ////////////////////////////////////
void ClearScreen()
{
HANDLE hStdOut;
CONSOLE_SCREEN_BUFFER_INFO csbi;
DWORD count;
DWORD cellCount;
COORD homeCoords = { 0, 0 };
hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
if (hStdOut == INVALID_HANDLE_VALUE) return;
/* Get the number of cells in the current buffer */
if (!GetConsoleScreenBufferInfo(hStdOut, &csbi)) return;
cellCount = csbi.dwSize.X *csbi.dwSize.Y;
/* Fill the entire buffer with spaces */
if (!FillConsoleOutputCharacter(
hStdOut,(TCHAR) ' ',cellCount,homeCoords,&count)) return;
/* Fill the entire buffer with the current colors and attributes */
if (!FillConsoleOutputAttribute(
hStdOut,csbi.wAttributes,cellCount,homeCoords,&count)) return;
/* Move the cursor home */
SetConsoleCursorPosition(hStdOut, homeCoords);
}
好吧,它看起來不錯,你可以幫助我的參數部分,像50x50最大最小值,即時獲取運行時錯誤,如果我超過了箱子頂部。 – CaliBreeze
你需要一個函數來計算房屋的高度和寬度,這取決於房屋的大小。然後用Move()中的d和s來驗證你是否超出了限制(例如'if(v + width(housesize)<50)v ++;') – Christophe
你能解釋int&v和int&h部分?我從來沒有見過這樣的聲明 – CaliBreeze