Next: (1) Include Files
Up: DEVS Formalism and DEVS++
Previous: Verbal Description of Coupled
Contents
Index
Building Ping-Pong Game using DEVS++
This section shows what
DEVS++ code looks like using the ping-pong game introduced in
Example 1.2. All source codes below are
available in DEVSpp/Examples/Ex_PinPong folder. If you want
to build and run this example by yourself, Chapter
5 will be helpful for you.
#include <DEVSpp/Atomic.h> //--- (1)
#include <DEVSpp/Coupled.h>
#include <DEVSpp/SRTEngine.h>
#include <DEVSpp/RNG.h>
#include <iostream>
#include <math.h>
using namespace std;
using namespace DEVSpp; //--- (2)
const string WAIT = "Wait";
const string SEND = "Send";
//---- definition of atomic DEVS for Player --- (3)
class Player: public Atomic {
public:
OutputPort* send; //-- associated ports --- (4)
InputPort* receive;
protected: //-- associated internal state variables ----(5)
string m_phase;
bool m_width_ball;
public:
Player(const string& name="", bool with_ball=false): Atomic(name),
m_phase(WAIT), m_width_ball(with_ball)
{
send = AddOP("send"); //--- add ports --- (6)
receive = AddIP("receive");
}
//---- four characteristic functions ------- (7)
/*virtual*/ void init()
{
if(m_width_ball)
m_phase = SEND;
else
m_phase = WAIT;
}
/*virtual*/ TimeSpan tau() const
{
static rv urv;
if(m_phase == SEND)
return urv.uniform(0.1, 1.2); //---- (8)
else
return DBL_MAX;
}
/*virtual*/ bool delta_x(const PortValue& x)
{
if(x.port == receive)
{
if(m_phase == WAIT) {
m_phase = SEND;
return true;
}
}
return false;
}
/*virtual*/ void delta_y(PortValue& y)
{
if(m_phase == SEND) {
y.Set(send);
m_phase = WAIT;
}
}
//------ end of four characteristic functions -------
/*virtual*/ string Get_s() const //------(9)
{
return m_phase;
}
};
Coupled* MakePingPongGame(const string& name) {
Coupled* PingPong = new Coupled(name);// ----(10)
Player* A = new Player("A", true); //--- (11)
Player* B = new Player("B", false);
A->CollectStatistics(true); //-- (12)
B->CollectStatistics(true);
PingPong->AddModel(A); //-- (13)
PingPong->AddModel(B);
//-- Internal Coupling -------- (14)
PingPong->AddCP(A->send, B->receive);
PingPong->AddCP(B->send, A->receive);
PingPong->PrintCouplings(); //---- (15)
return PingPong;
}
void main(void) {
Coupled* PingPong = MakePingPongGame("PingPong");
SRTEngine simEngine(*PingPong);//-- (16)
simEngine.RunConsoleMenu(); //-- (17)
delete PingPong;
}
Subsections
MHHwang
2007-05-07