1/***************************************************************************
2* KBlocks, a falling blocks game for KDE *
3* Copyright (C) 2010 Zhongjie Cai <squall.leonhart.cai@gmail.com> *
4* *
5* This program is free software; you can redistribute it and/or modify *
6* it under the terms of the GNU General Public License as published by *
7* the Free Software Foundation; either version 2 of the License, or *
8* (at your option) any later version. *
9***************************************************************************/
10#include "KBlocksPlayNetwork.h"
11
12#ifdef Q_OS_WIN
13#include <windows.h>
14#else
15#include <unistd.h>
16#endif
17
18KBlocksPlayNetwork::KBlocksPlayNetwork(int capacity, const string& serverIP, int localPort)
19{
20 mServerIP = serverIP;
21 mLocalPort = localPort;
22
23 mPlayerCount = 0;
24 mMaxCapacity = capacity;
25
26 maPlayerList = new KBlocksNetPlayer*[mMaxCapacity];
27
28 mpGameLogic = new KBlocksGameLogic(mMaxCapacity);
29 mpGameLogic->setGameSeed(0);
30 mpGameLogic->setGamePunish(false);
31 mpGameLogic->setGameStandbyMode(true);
32 mpGameLogic->setInitInterval(0);
33 mpGameLogic->setLevelUpInterval(0);
34}
35
36KBlocksPlayNetwork::~KBlocksPlayNetwork()
37{
38 mpGameLogic->stopGame();
39 delete mpGameLogic;
40
41 delete [] maPlayerList;
42}
43
44bool KBlocksPlayNetwork::addGamePlayer(GamePlayerInterface * p)
45{
46 if (mPlayerCount == mMaxCapacity)
47 {
48 return false;
49 }
50 maPlayerList[mPlayerCount] = new KBlocksNetPlayer(p, mServerIP, mLocalPort + mPlayerCount);
51 mPlayerCount++;
52 return true;
53}
54
55void KBlocksPlayNetwork::clearGamePlayer()
56{
57 for(int i = 0; i < mPlayerCount; i++)
58 {
59 delete maPlayerList[i];
60 maPlayerList[i] = 0;
61 }
62 mPlayerCount = 0;
63}
64
65void KBlocksPlayNetwork::startGame()
66{
67 mpGameLogic->startGame(mPlayerCount);
68 for(int i = 0; i < mPlayerCount; i++)
69 {
70 mpGameLogic->getSingleGame(i)->stopGame();
71 maPlayerList[i]->joinGame(i);
72 }
73 for(int i = 0; i < mPlayerCount; i++)
74 {
75 maPlayerList[i]->startGame(mpGameLogic->getSingleGame(i));
76 }
77}
78
79void KBlocksPlayNetwork::stopGame()
80{
81 for(int i = 0; i < mPlayerCount; i++)
82 {
83 maPlayerList[i]->stopGame();
84 maPlayerList[i]->quitGame();
85 }
86 mpGameLogic->stopGame();
87}
88
89int KBlocksPlayNetwork::execute()
90{
91 mRunning = true;
92
93 while(mRunning)
94 {
95 for(int i = 0; i < mPlayerCount; i++)
96 {
97 if (!maPlayerList[i]->execute())
98 {
99 mRunning = false;
100 break;
101 }
102 }
103#ifndef Q_OS_WIN
104 usleep(100000);
105#else
106 Sleep(100);
107#endif
108 }
109
110 return 0;
111}
112
113void KBlocksPlayNetwork::cancelExecute()
114{
115 mRunning = false;
116}
117