(root)/mainwindow.cpp - Rev 31
Rev 30 |
Rev 32 |
Go to most recent revision |
Blame |
Compare with Previous |
Last modification |
View Log
| RSS feed
#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QGLWidget(parent)
{
this->setFixedSize(800, 600);
server = new QTcpServer(this);
connect(server, SIGNAL(newConnection()), this, SLOT(newConnection()));
server->listen(QHostAddress::Any, 4567);
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(update()));
timer->start(50);
id = 0;
}
MainWindow::~MainWindow()
{
delete server;
}
void MainWindow::reset()
{
for (int i = 0; i < bikes.count(); i++)
{
bikes[i]->reset();
}
}
void MainWindow::paintEvent(QPaintEvent *e)
{
e->accept();
QPainter painter(this);
painter.fillRect(0, 0, 800, 600, Qt::white);
bool ready = true;
for (int i = 0; i < bikes.count(); i++)
{
if (!bikes[i]->isReady)
{
ready = false;
}
}
if (ready)
{
for (int i = 0; i < bikes.count(); i++)
{
if (bikes[i]->show)
{
bikes[i]->hasHadGo = false;
bikes[i]->run(bikes);
}
}
Bike *bike;
foreach(bike,bikes)
{
while(!bike->hasHadGo)
{
}
}
for (int i = 0; i < bikes.count(); i++)
{
if (bikes[i]->show)
{
bikes[i]->draw(&painter,bikes);
}
}
}
checkClients();
}
void MainWindow::newConnection()
{
while (server->hasPendingConnections())
{
QTcpSocket *socket = server->nextPendingConnection();
Bike *bike = new Bike(socket, id);
connect(bike, SIGNAL(chat(QString,QString)), this, SLOT(chat(QString,QString)));
id += 1;
reset();
bikes.append(bike);
cout << ":: New Bike: " << socket->peerAddress().toString().toStdString() << endl;
}
}
void MainWindow::checkClients()
{
bool everyoneDied = true;
for (int i = bikes.count() - 1; i >= 0; i--)
{
if (bikes[i]->isDisconnected)
{
for (int j = 0; j < bikes.count(); j++)
{
bikes[j]->setText(QString("DISCO ") + bikes[i]->name + QString("\n"));
}
delete bikes[i];
bikes.removeAt(i);
cout << ":: Removed Bike: " << i << endl;
}
else
{
if (!bikes[i]->collided)
{
everyoneDied = false;
}
else if (bikes[i]->dead)
{
everyoneDied = false;
}
}
}
if (everyoneDied)
{
reset();
}
}
void MainWindow::chat(QString name, QString message)
{
QString packet = "CHAT ";
packet.append(name);
packet.append(" ");
packet.append(message);
packet.append("\n");
for (int i = 0; i < bikes.count(); i++)
{
bikes[i]->setText(packet);
}
}