nibbles.cpp

(plain text)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
#include <algorithm>
#include <deque>
#include <exception>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>
#include <cctype>
#include <ctime>
#include <ncurses.h>
#include <sys/time.h>
#include <unistd.h>

using namespace std;

namespace ansi {
  void cls () { cout << "\x1B[2J\x1B[H" << flush; }
  void up (int rows) { cout << "\x1B[" << rows << 'A' << flush; }
  void left (int cols) { cout << "\x1B[" << cols << 'D' << flush; }
}

class Coord {
public:
  explicit Coord (int r = 0, int c = 0);
  int row () const;
  int col () const;

private:
  int myRow, myCol;
};

bool operator== (const Coord &p, const Coord &q);

class Snake;
class Board;

class Snake {
public:
  typedef deque<Coord> body_type;
  enum Orientation { up = 1, down = 1 | 2, left = 4, right = 4 | 8 };

  class DeadSnakeException : public exception {
  public:
    explicit DeadSnakeException (const char *msg = "");
    virtual ~DeadSnakeException () throw () { }
    virtual const char *what () const throw ();

  private:
    string myMessage;
  };

  explicit Snake ();
  void reorient (Orientation orientation);
  void move (Board &theBoard);

  body_type::const_iterator begin () const;
  body_type::const_iterator end () const;

private:
  body_type myBody;
  Orientation myOrientation;
  int hasEaten;
};

class Board {
public:
  explicit Board (int rows, int cols);
  int isNumberAt (const Coord &p);
  void draw (const Snake &snake);

  int rows () const;
  int cols () const;

private:
  int myRows, myCols;

  struct {
    Coord position;
    int value;
  } myNumber;

  typedef vector<string> buffer_type;
};

int main (int argc, char *argv[]) {
  srand(time(0));
  int ms = (argc > 1) ? atoi(argv[1]) : 100;
  if (ms < 0) ms = 100;

  /* set up Curses environment (for the 'getch' function) */
  initscr();
  nodelay(stdscr, 1);
  noecho();

  Board board(21, 78);
  Snake snake;
  ansi::cls();

  try {
    while (1) {
      for (int c; (c = getch()) != -1; ) {
	switch (toupper(c)) {
	case 'W': snake.reorient(Snake::up); break;
	case 'A': snake.reorient(Snake::left); break;
	case 'S': snake.reorient(Snake::down); break;
	case 'D': snake.reorient(Snake::right); break;
	}
      }

      snake.move(board);
      ansi::up(board.rows() + 2);
      board.draw(snake);

      timeval tv = { 0, 1000 * ms };
      select(0, 0, 0, 0, &tv);
    }
  }

  catch (const Snake::DeadSnakeException &e) {
    cout << "You're dead: " << e.what() << endl;
  }

  /* close up Curses environment */
  endwin();

  return 0;
}

Coord::Coord (int r, int c)
  : myRow(r),
    myCol(c) {
}

int Coord::row () const { return myRow; }
int Coord::col () const { return myCol; }

bool operator== (const Coord &p, const Coord &q) {
  return p.row() == q.row() && p.col() == q.col();
}

Snake::Snake ()
  : myOrientation(right),
    hasEaten(false) { 
  for (int col = 0; col < 3; ++col) {
    myBody.push_front(Coord(0, col));
  }
}

void Snake::reorient (Orientation orientation) {
  if ((myOrientation & orientation) == 0) myOrientation = orientation;
}

void Snake::move (Board &theBoard) {
  Coord head = myBody.front();

  switch (myOrientation) {
  case Snake::up:    head = Coord(head.row() - 1, head.col()); break;
  case Snake::down:  head = Coord(head.row() + 1, head.col()); break;
  case Snake::left:  head = Coord(head.row(), head.col() - 1); break;
  case Snake::right: head = Coord(head.row(), head.col() + 1); break;
  }

  myBody.push_front(head);

  if (hasEaten)
    --hasEaten;
  else
    myBody.pop_back();

  hasEaten += theBoard.isNumberAt(head);

  if (head.row() < 0 || theBoard.rows() <= head.row()
      || head.col() < 0 || theBoard.cols() <= head.col()) {
    throw DeadSnakeException("crashed into the wall");
  }
}

Snake::body_type::const_iterator Snake::begin () const {
  return myBody.begin();
}

Snake::body_type::const_iterator Snake::end () const {
  return myBody.end();
}

Snake::DeadSnakeException::DeadSnakeException (const char *msg)
  : myMessage(msg) {
}

const char *
Snake::DeadSnakeException::what () const throw () {
  return myMessage.c_str();
}

Board::Board (int rows, int cols)
  : myRows(rows),
    myCols(cols) {
  myNumber.position = Coord(rand() % myRows, rand() % myCols);
  myNumber.value = 1;
}

int Board::isNumberAt (const Coord &p) {
  if (p == myNumber.position) {
    myNumber.position = Coord(rand() % myRows, rand() % myCols);
    return myNumber.value++;
  }

  return 0;
}

void Board::draw (const Snake &snake) {
  buffer_type buffer(myRows, string(myCols, ' '));

  buffer[myNumber.position.row()][myNumber.position.col()] = ('0' + (myNumber.value % 10));

  for (Snake::body_type::const_iterator i = snake.begin(), j = snake.end(); i != j; ++i) {
    const Coord &p = *i;
    if (!isspace(buffer[p.row()][p.col()])) throw Snake::DeadSnakeException("ran over yourself");
    buffer[p.row()][p.col()] = 'X';
  }

  cout.put(' ');
  fill_n(ostream_iterator<char>(cout), myCols, '_');
  cout << "\r\n";

  for (int row = 0; row < myRows; ++row) {
    cout << '[';

    for (int col = 0; col < myCols; ++col) {
      cout << buffer[row][col];
    }

    cout << "]\r\n";
  }

  cout.put(' ');
  fill_n(ostream_iterator<char>(cout), myCols, '^');
  cout << "\r" << flush;
}

int Board::rows () const {
  return myRows;
}

int Board::cols () const {
  return myCols;
}