Skip to content

Instantly share code, notes, and snippets.

@000hen
Created July 8, 2022 15:38
Show Gist options
  • Select an option

  • Save 000hen/38b9b2e1b5ff2fa0653905dde11085f6 to your computer and use it in GitHub Desktop.

Select an option

Save 000hen/38b9b2e1b5ff2fa0653905dde11085f6 to your computer and use it in GitHub Desktop.
Light Table
/*
Light game
This source code is following the rules of the game rules.
Rules should be "Click one light on the table, then the light and its around (top, bottom, left, right) will be toggled."
Author: Muisnow (@000hen)
*/
#include<iostream>
#include<vector>
#include<string>
#include<iomanip>
std::vector<std::string> split(std::string data, std::string delimiter) {
std::vector<std::string> opt;
size_t pos;
while ((pos = data.find(delimiter)) != std::string::npos) {
opt.push_back(data.substr(0, pos));
data.erase(0, pos + delimiter.length());
}
opt.push_back(data);
return opt;
}
std::string getLines() {
std::string input;
std::cout << "> ";
std::getline(std::cin, input);
return input;
}
void showTable(bool* table, int width, int height) {
std::cout << std::setw(7) << "|";
for (int i = 0; i < width; i++) {
std::cout << std::setw(6) << i << "|";
}
std::cout << std::endl;
for (int y = 0; y < height; y++) {
std::cout << std::setw(6) << y;
for (int x = 0; x < width; x++) {
std::cout << "|" << std::setw(6) << (table[y * width + x] ? "X" : " ");
}
std::cout << "|" << std::endl;
}
}
int main() {
int width, height;
printf("Light table size ([height] [width])\n");
std::string size = getLines();
std::vector<std::string> sizeOpt = split(size, " ");
height = std::stoi(sizeOpt[0]);
width = std::stoi(sizeOpt[1]);
bool table[height * width];
for (int i = 0; i < height * width; i++) {
table[i] = false;
}
printf("Light table with %d x %d\n", width, height);
printf("Command:\n");
printf("\t[x] [y]: set light at x, y\n");
printf("\texit: exit\n\n");
showTable(table, width, height);
while (true) {
std::string input;
input = getLines();
std::string delimiter = " ";
std::vector<std::string> data = split(input, delimiter);
if (data[0] == "exit") break;
int x = std::stoi(data[0].c_str());
int y = std::stoi(data[1].c_str());
if (x < 0 || x >= width || y < 0 || y >= height) {
printf("Out of range\n");
continue;
}
int index = y * width + x;
table[index] = table[index] ? false : true;
if (index % width != 0) table[index - 1] = table[index - 1] ? false : true;
if (index % width != width - 1) table[index + 1] = table[index + 1] ? false : true;
table[index + width] = table[index + width] ? false : true;
table[index - width] = table[index - width] ? false : true;
showTable(table, width, height);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment