CSC112 Spring 2016 Examples
// The main file for the puzzle program.1// This plays the cross-4 puzzle.2// Revision: $Revision: 1.1 $3// Change Log4// $Log: puzzle.cpp,v $5// Revision 1.1 2016/03/17 15:57:00 pngwen6// Initial revision7//89#include <iostream>10#include <string>11#include <unistd.h>12#include <iomanip>13#include "termmanip.h"14#include "keystream.h"15#include "crossFour.h"16#include "tty_functions.h"1718using namespace std;1920// One static global variable, used sparingly but in good faith as there is but one tty21static ttySize sz;2223//display elements24void displayHeader();25void displayFooter();26void displayMessage(int line, const string &msg);27void displayMoveResponse(CrossFour *p, bool valid);2829int main()30{31CrossFour *p;32keycode kc;3334//initialize things35sz = ttyGetSize(STDIN_FILENO);36p=new CrossFour(sz.cols / 2 - 35/2, 6);3738//display the puzzle39cout << clearScreen << cursorOff;40p->display();4142displayHeader();43displayFooter();4445//get the input into the right state46kin.cbreakMode();4748//do the puzzle49do {50kc = kin.getKey();5152//moves begin valid53displayMoveResponse(p, true);5455switch(kc) {5657case LEFT: //left58case 'h': //with vim bindings!59case CTRL_B: //and emacs!60case 'a': //gamer!61p->left();62break;6364case RIGHT: //right65case 'l': //vim!66case CTRL_F: //emacs!67case 'd': //gamer!68p->right();69break;7071case 'r':72p->reset();73break;7475case 's':76p->solve();77break;7879case ENTER: //make yer move!80displayMoveResponse(p, p->move());81break;8283case ESC:84kc = CTRL_C; //escape moves too85break;86}87} while(kin && kc != CTRL_C);8889//clean up the screen90cout << cursorOn << clearScreen << cursorPosition(1,1);91cout.flush();9293return 0;94}959697void98displayHeader()99{100//put a header on the screen101cout << cursorPosition(1,1)102<< reverseVideo103<< clearLine << setw(sz.cols) << ' ';104displayMessage(1, "Cross-4 Peg Puzzle");105cout << cursorPosition(1,2) << normal;106cout.flush();107}108109110void111displayFooter()112{113displayMessage(sz.rows-2, "s- Solve")114displayMessage(sz.rows-1, "Arrows/jkhl/wasd - Move Cursor Enter: Select/Place Peg");115displayMessage(sz.rows, "r- Reset ESC - Exit");116}117118119void120displayMessage(int line, const string &msg)121{122//compute the x-coordinate to center the message123int x = sz.cols/2;124x -= msg.length()/2;125cout << cursorPosition(x, line) << msg;126cout.flush();127}128129130void131displayMoveResponse(CrossFour *p, bool valid)132{133int y;134135//get the line to display the message on136y=p->y() - 1;137138//clear the message line139cout << cursorPosition(1,y) << clearLine;140cout.flush();141142//display the message (if there is one)143if(!valid) {144cout << red;145displayMessage(y, "Invalid Selection. Please Try Again");146cout << normal;147cout.flush();148}149}150151152