Last active
August 29, 2015 14:04
-
-
Save ivycheung1208/cd8fccd3bc997b159ee0 to your computer and use it in GitHub Desktop.
CC150 5.8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* CC150 5.8 | |
* Implement a function drawHorizontalLine(byte[] screen, int width, int x1, int x2, int y) | |
* which draws a horizontal line from (x1, y) to (x2, y). | |
*/ | |
#include <iostream> | |
#include <vector> | |
using namespace std; | |
void drawHorizontalLine(vector<unsigned char> &screen, int width, int x1, int x2, int y) | |
{ | |
if (x1 > x2 || x1 < 0 || x1 >= width || x2 < 0 || x2 >= width) // invalid x coordinates | |
return; | |
int height = screen.size() / width * 8; | |
if (y < 0 || y >= height) // invalid y coordinate | |
return; | |
int pixStart = y * width + x1; | |
int pixEnd = y * width + x2; | |
for (int byte = pixStart / 8; byte != pixEnd / 8; ++byte) | |
screen[byte] |= 0xFF; // roughly draw the line | |
screen[pixStart / 8] &= (0xFF >> (pixStart % 8)); // clear the leading pixels | |
screen[pixEnd / 8] |= ~(0xFF >> (pixEnd % 8 + 1)); // fill the tailing pixels | |
return; | |
} | |
void display(vector<unsigned char> screen, int width) | |
{ | |
int count = 0; | |
for (auto byte : screen) { | |
for (int k = 7; k >= 0; --k) | |
cout << ((byte & (1 << k)) >> k); | |
count += 8; | |
if (count % width == 0) | |
cout << endl; | |
} | |
cout << endl; | |
} | |
int main() | |
{ | |
vector<unsigned char> screen(64, 0x00); // 32 * 16 | |
int width = 32; | |
int x1, x2, y; | |
while (cin >> x1 >> x2 >> y) { // support multiple inputs | |
drawHorizontalLine(screen, width, x1, x2, y); | |
display(screen, width); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment