#include "defs.h"
RCSID("$NetBSD: board.cc,v 1.5 2021/12/05 09:22:45 rillig Exp $")
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include "board.h"
#include "gamescreen.h"
#include "box.h"
#include "player.h"
BOARD::BOARD(size_t y, size_t x, GAMESCREEN* scrn) :
_ny(y),
_nx(x),
_scrn(scrn)
{
_ty = 2 * _ny + 1;
_tx = 2 * _nx + 1;
_b = new int*[_ty];
for (y = 0; y < _ty; y++)
_b[y] = new int[_tx];
init();
}
BOARD::BOARD(const BOARD& b) :
_ty(b._ty),
_tx(b._tx),
_ny(b._ny),
_nx(b._nx),
_scrn(NULL)
{
_b = new int*[_ty];
for (size_t y = 0; y < _ty; y++) {
_b[y] = new int[_tx];
static_cast<void>(memcpy(_b[y], b._b[y], _tx * sizeof(int)));
}
}
BOARD::~BOARD()
{
size_t y;
for (y = 0; y < _ty; y++)
delete[] _b[y];
delete[] _b;
}
void BOARD::init(void)
{
size_t x, y;
for (y = 0; y < _ny; y++)
for (x = 0; x < _nx; x++) {
BOX box(y, x, *this);
box.reset();
}
}
int BOARD::domove(size_t y, size_t x, int dir, char c)
{
int closed = 0;
if (!bounds(y, x))
return -1;
BOX box1(y, x, *this);
if (box1.isset(dir))
return -1;
box1.set(dir);
if (box1.count() == 4) {
box1.name() = c;
closed++;
}
box1.paint();
x += BOX::edges[dir].x;
y += BOX::edges[dir].y;
if (bounds(y, x)) {
BOX box2(y, x, *this);
if (box2.count() == 4) {
box2.name() = c;
box2.paint();
closed++;
}
}
return closed;
}
int BOARD::full(void) const
{
for (size_t y = 0; y < _ny; y++)
for (size_t x = 0; x < _nx; x++) {
BOX box(y, x, const_cast<BOARD&>(*this));
if (box.count() != 4)
return 0;
}
return 1;
}
int BOARD::bounds(size_t y, size_t x) const
{
return x < _nx && y < _ny;
}
void BOARD::paint(void) const
{
for (size_t y = 0; y < _ny; y++)
for (size_t x = 0; x < _nx; x++) {
BOX box(y, x, const_cast<BOARD&>(*this));
box.paint();
}
}
void BOARD::clean(void) const
{
if (!_scrn)
return;
_scrn->clean();
}
void BOARD::setpos(size_t y, size_t x) const
{
if (!_scrn)
return;
_scrn->moveto(y, x);
_scrn->redraw();
}
int BOARD::getmove(void) const
{
if (!_scrn)
return 'q';
_scrn->redraw();
return _scrn->getinput();
}
void BOARD::bell(void) const
{
if (!_scrn)
return;
_scrn->bell();
}
void BOARD::score(size_t i, const PLAYER& p)
{
if (_scrn == NULL)
return;
_scrn->score(i, p);
}
void BOARD::games(size_t i, const PLAYER& p)
{
if (_scrn == NULL)
return;
_scrn->games(i, p);
}
void BOARD::total(size_t i, const PLAYER& p)
{
if (_scrn == NULL)
return;
_scrn->total(i, p);
}
void BOARD::ties(const PLAYER& p)
{
if (_scrn == NULL)
return;
_scrn->ties(p);
}
void BOARD::abort(const char* s, ...) const
{
for (size_t i = 0; i < _ny; i++)
fprintf(stderr, "\n");
va_list ap;
fprintf(stderr, "Algorithm internal error: ");
va_start(ap, s);
vfprintf(stderr, s, ap);
va_end(ap);
fprintf(stderr, "\n");
::abort();
}