Tutorial of OMNeT++

 

This document provides a quick introduction to OMNeT++. The aim is to get the interested user up and running with a simple game NIM. After finishing this, the user can start exploiting more of OMNeT++’s functionality based on the extensive user manual and the sample directories.

1      Introduction. 1

1.1       What is OMNeT++?. 1

1.2       Why OMNeT++?. 2

1.3       Where to Get the Software?. 5

1.4       Install the OMNeT++. 7

1.4.1        Prerequisites. 7

1.4.2        Begin to Install 7

2      Starting a simple example. 10

2.1       Example Introduction. 10

2.2       Start the Nim.. 10

2.2.1        Find the folder of the Nim example. 11

2.2.2        Start Nim program.. 11

2.2.3        Run the program step by step. 12

2.2.4        Play the program again. 25

2.3       Change some parameters. 25

2.3.1        Where can you find the parameters?. 25

2.3.2        How to change parameters?. 27

2.3.3        Start newly generated Nim.. 36

3      Understanding the code. 38

3.1       NED file. 39

3.2       The .cpp and .h Files. 41

4      References. 46

 


1      Introduction

 

1.1      What is OMNeT++?

OMNeT++ is an object-oriented modular discrete event simulator. The name itself stands for Objective Modular Network Testbed in C++. OMNeT++ has its distant roots in OMNeT, a simulator written in Object Pascal by dr. György Pongor. The simulator can be used for:

ü      traffic modeling of telecommunication networks

ü      protocol modeling

ü      modeling queueing networks

ü      modeling multiprocessors and other distributed hardware systems

ü      validating hardware architectures

ü      evaluating performance aspects of complex software systems

ü      modeling any other system where the discrete event approach is suitable.

1.2      Why OMNeT++?

There are numerous network simulation tools on the market today, both commercial and non-commercial. In this section I will try to give an overview by picking some of the most important or most representative ones in both categories and comparing them to OMNeT++: PARSEC, SMURPH, NS, Ptolemy, NetSim++, C++SIM, CLASS as non-commercial, and OPNET, COMNET III as commercial tools. (The OMNeT++ Home Page contains a list of Web sites with collections of references to network simulation tools where the reader can get a more complete list.) In the commercial category, OPNET is widely held to be the state of the art in network simulation. OMNeT++ is targeted at roughly the same segment of network simulation as OPNET.

Seven issues are examined to get an overview about the network simulation tools:

  • Detail Level. Does the simulation tool have the necessary power to express details in the model? In other words, can the user implement arbitrary new building blocks like in OMNeT++ or he is confined to the predefined blocks implemented by the supplier? Some tools like COMNET III are not programmable by the user to this extent therefore they cannot be compared to OMNeT++. Specialized network simulation tools like NS (for IP) and CLASS (for ATM) also rather fall into this category.
  • Available Models. What protocol models are readily available for the simulation tool? On this point, non-commercial simulation tools cannot compete with some commercial ones (especially OPNET) which have a large selection of ready-made protocol models. OMNeT++ is no exception.
  • Defining Network Topology. How does the simulation tool support defining the network topology? Is it possible to create some form of hierarchy (nesting) or only “flat” topologies are supported? Network simulation tools naturally share the property that a model (network) consists of “nodes” (blocks, entities, modules, etc.) connected by “links” (channels, connections, etc.). Many commercial simulators have graphical editors to define the network; however, this is only a good solution if there is an alternative form of topology description (e.g. text file) which allows one to generate the topology by program. OPNET follows a unique way: the network topology is stored in a proprietary binary file format which can be generated (and read) by the graphical editor and C programs linked against a special library. On the other hand, most non-commercial simulation tools do not provide explicit support for topology description: one must program a “driver entity” which will boot the model by creating the necessary nodes and interconnecting them (PARSEC, SMURPH, NS). Finally, a large part of the tools that do support explicit topology description supports only flat topologies (CLASS). OMNeT++ probably uses the most flexible method: it has a human-readable textual topology description format (the NED language) which is easy to create with any text-processing tool (perl, awk, etc.), and the same format is used by the graphical editor. It is also possible to create a “driver entity” to build a network at run-time by program. OMNeT++ also supports submodule nesting.
  • Programming Model. What is the programming model supported by the simulation environment? Network simulators typically use either thread/coroutine-based programming (such as activity() in OMNeT++), or FSMs built upon a handleMessage()-like function. For example, OPNET, SMURPH and NetSim++ use FSMs (with underlying handleMessage()), PARSEC and C++SIM use threads. OMNeT++ supports both programming models; the author does not know of another simulation tool that does so.
  • Debugging and Tracing Support. What debugging or tracing facilities does the simulation tool offer? Simulation programs are infamous for long debugging periods. C++-based simulation tools rarely offer much more than printf()-style debugging; often the simulation kernel is also capable of dumping selected debug information on the standard output. Animation is also often supported, either off-line (record&playback) or in some client-server architecture, where the simulation program is the “server” and it can be viewed using the “client”. Off-line animation naturally lacks interactivity and is therefore little use in debugging. The client-server solution typically has limited power because the simulation and the viewer run as independent operating system processes, and the viewer has limited access to the simulation program’s internals and/or it does not have enough control over the course of simulation execution. OPNET has a very good support for command-line debugging and provides both off-line and client-server style animation. NetSim++ and Ptolemy use the client-server method of animation. OMNeT++ goes a different way by linking the GUI library with the debugging/tracing capability into the simulation executable. This architecture enables the GUI to be very powerful: every user-created object is visible (and modifiable) in the GUI via inspector windows and the user has tight control over the execution. To the author’s best knowledge, the tracing feature OMNeT++ provides is unique among the C++-based simulation tools.
  • Performance. What performance can be expected from the simulation? Simulation programs typically run for several hours. Probably the most important factor is the programming language; almost all network simulation tools are C/C++-based. Performance is a particularly interesting issue with OMNeT++ since the GUI debugging/tracing support involves some extra overhead in the simulation library. However, in a reported case, an OMNeT++ simulation was only 1.3 slower than its counterpart implemented in plain C (i.e. one containing very little administration overhead), which is a very good showing. A similar result was reported in a performance comparison with a PARSEC simulation.
  • Source Availability. Is the simulation library available in source? This is a trivial question but it immediately becomes important if one wants to examine or teach the internal workings of a simulation kernel, or one runs into trouble because some function in the simulation library has a bug and/or it is not documented well enough. In general it can be said that noncommercial tools (like OMNeT++) are open-source and commercial ones are not. This is also true for OPNET: the source for simulation kernel is not available (although the ready-made protocol models come with sources).

In conclusion, it can be said that OMNeT++ has enough features to make it a good alternative to most network simulation tools, and it has a strong potential to become one of the most widely used network simulation packages in academic and research environments. The most serious shortcoming is the lack of available protocol models, but since this is mostly due to the fact that it is a relatively new simulation tool, with the help of the OMNeT++ user community the situation is likely to become much better in the future.

 

1.3      Where to Get the Software?

You can find OMNeT++ at http://www.omnetpp.org/. If you are too lazy to type this in, a search with www.google.com on omnet++ will give an instant hit.

The following graph is the screenshot of the homepage of OMNeT++

Since most students use windows operation system, we should download the file OMNet++ 2.3 Win32(exe) (Circled in above graph)or simple click the following link http://www.omnetpp.org/filemgmt/visit.php?lid=31 and download the file.

1.4      Install the OMNeT++

1.4.1      Prerequisites

 

  • Windows XP, Windows 2000, NT4.0 or other NT-derivative. OMNeT++ is not supported by WIN95/98/ME, because it uses the Win32 Fiber API which is only available on NT systems. Moreover, the makefiles and some batch (.cmd) files use syntax which is not supported by the old command.com. Besides the above "hard" prohibitive factors, it is anyway advisable to use a more stable operating system.
  • Microsoft Visual Studio 6.0, Very Important with at least Service Pack 1 installed. I recommend Service Pack 5 which can be downloaded from Microsoft's site under the name vs6sp5.exe. You should first install Visual C++ 6.0, then install OMNeT++. Otherwise, you will get frustrated by doing a lot of links with OMNeT++ and Visual C++ 6.0.
  • 40MB free space on your hard disk. If your want to compile from source, you'll need about 20MB more. Generally speaking it is not a problem for most computers.

1.4.2      Begin to Install

a)      Double click the downloaded file , you will see the following license window

b)      Choose I Agree and you will see the following window

c)      Choose default configuration and go to Next step

d)      You can choose current configure to Install OMNeT++

You can also choose another directory. But the directory can not have space in its name. For example please don't install under C:\Program files! (Otherwise you'll probably have problems with the makefiles.) After click Install you will find the following installation window.

e)      After a while you will see the successful installation window as follow

f)        Then click Yes and restart your computer and the OMNeT++ will be ready for you to use

<to top> <to back>


2         Starting a simple example

 

In this chapter we will show you the basic concepts of OMNeT++ via the simulation model of a simple game, NIM.

2.1      Example Introduction

 

Nim is an ancient game with two players and a bunch of sticks (here also called tokens). The players take turns, removing 1, 2, 3 or 4 sticks from the heap of sticks at each turn. The one who takes the last stick is the loser. The game is modeled in OMNeT++ as a network with three modules: the 'game' (a manager module) and two players. The model of the Nim game is similar to 'Hello world!' by complexity, but it nicely demonstrates the modeling approach used by OMNeT++.

2.2      Start the Nim

 

Let us first start the Nim and have a brief review of OMNeT++.

 

2.2.1      Find the folder of the Nim example.

 

If you installed as default configuration, it should be at C:\OMNeT++\samples\nim. If you changed to other folder the position of the Nim is similar. The following figure shows the folder position in my computer.

 

2.2.2      Start Nim program

You can double click the EXE file nim.exe with icon to start the program. Then a lot of windows will appear as follow.

2.2.3      Run the program step by step

 

1.      Since the graphics window is clear and straightforward, we first click run in this window to see what happens. Then we find the TKenv window displays some messages.

 

2.      We continue to run the game by clicking  in the graphics window. We can see the following events happen. Player1 named “InteractivePlayer” come out of player 1 box and go to game circle.

The Tkenv window shows the detailed event explanation. ** Event #1.  T=0.0000000  ( 0.00s).  Module #3 `nim.player1'

3.      Continue to run the game, we will notice a “smartplayer” comes out of player2 box and goes to game circle. The windows is showed as follow.

Then the Tkenv window shows the detailed event explanation. ** Event #2.  T=0.0000000  ( 0.00s).  Module #4 `nim.player2'

4.      Continue to run the game by clicking , we will see ** Event #3.  T=0.0000000  ( 0.00s).  Module #2 `nim.game' appear in the Tkenv window

5.      Click again and the game will begin. The Tkenv window shows the following message

In the graphics window we can see a very interesting animation. The ball changes its color, and the text with the ball also changes to “26 sticks left”. Then, the ball goes to player2’ box. The following graph is the final result of this step.

6.      Continue to run the game by clicking , the smart player begins to take some sticks from the 26 sticks. By the smart algorithm he takes 1 out of 26 sticks. If you are the smart player, how many sticks are you going to take? The Tkenv windows displays the message like following

The graphics window looks like following

7.      Continue to run the game by clicking , it is your turn to take sticks. The ball named 25 sticks goes to player1’s box. The Tkenv window looks like following

8.      Continue to run the game by clicking . A new dialogue window appears and asks you how many sticks you take. You can only input 1, 2,3,4, the new window look like the following graph

9.      Input a number, for example, 3, and click Ok to continue the game. The Tkenv window will show the message

10.  Now each of the two players has taken some sticks. You can easily continue the game until all the sticks are taken. Finally, you will pick up the last stick, then the game is over and the following window appears.

The Tkenv window shows the following message

The last screenshot of graphics window is shown by follow

2.2.4      Play the program again

You can continue to play the game by clicking , you can also click  in the Tkenv window.

The following dialogue window will appear

Click Yes and you can restart the game. You will find that the number of stick may change and sometime the player who first picks up sticks may also change. If you are selected to first pick up sticks, try to think about it and be a smart player.

2.3      Change some parameters

 

This game is very simple and does not have many parameters to change. The number of sticks and the player who first pick up sticks are two parameters we can change. Let us find how we can change it.

2.3.1      Where can you find the parameters?

Click  and have a look at the structure of Nim

You can expand the object tree to see every item. The two parameters we are looking for are at the following place

The variable “num_sticks” indicates the number of initial sticks and the “first_move” indicates the player who will first move the sticks

double click “num_sticks” you will see the following window

intuniform(21,31) means the number of sticks uniformly distributed between 21 and 31.

double click “num_sticks” you will see the following window

intuniform(1,2) means the number of sticks uniformly distributed between 1 and 2. ‘1’ refers to the player1 and ‘2’ refers to the player2. It means both players have equal probability to be the first player.

2.3.2      How to change parameters?

You may want to change these two parameters, but it is not straightforward to do so. You need to follow the following steps:

1.      Find the nim.ned file in the directory C:\OMNeT++\samples\nim

2.      Right click the file and open with notepad.

The following is the content of nim.ned. It defines all the modules and their input, output, and parameters.

//-------------------------------------------------------------

// file: nim.ned

//        (part of NIM - an OMNeT++ demo simulation)

//

//  NIM is an ancient game with two players and a bunch of sticks.

//

//  The players take turns, removing 1..4 sticks from the heap

//  at each turn.

//

//  The player who must take the *last* stick is the loser.

//

//-------------------------------------------------------------

 

 

// Game --

//

// Declaration of simple module type Game

//

simple Game

    parameters:

        num_sticks : numeric, // starting number of sticks

        first_move : numeric; // 1=Player1, 2=Player2

    gates:

        in: from_player1; // input and output gates

        in: from_player2; // for connecting to Player1/Player2

        out: to_player1;

        out: to_player2;

endsimple

 

 

// Player --

//

// Interface declaration for different modules implementing players

//

simple Player

    gates:

        in: in; // gates for connecting to Game

        out: out;

endsimple

 

 

// Nim --

//

// The NIM game's network: Game and two players interconnected

//

module Nim

    parameters:

        player1_type : string,

        player2_type : string;

    submodules:

        // create the Game module, with the initial number of

        // sticks and the starting player as random parameters

        game: Game;

            parameters:

                num_sticks = intuniform (21, 31),

                first_move = intuniform (1, 2);

        // for players, define module type as parameter to

        // the parent module, Nim

        player1: player1_type like Player;

        player2: player2_type like Player;

    connections:

        player1.out --> game.from_player1;

        player1.in <-- game.to_player1;

                                       

        player2.out --> game.from_player2;

        player2.in <-- game.to_player2;

endmodule

 

 

// nim --

//

// an instance of the Nim module

//

network nim : Nim

    parameters:

        player1_type = input("InteractivePlayer"),

        player2_type = input("SmartPlayer");

endnetwork

 

3.      The red text is the parameters. We change them to, for example,

                num_sticks =27,

                first_move = 1;

Save it and close the notepad.

open DOS command window by Start->Run->cmd

You will see the command window

Change directory to cd c:\omnet++\samples\nim

4.      Input the command opp_nmakemake -f

5.      Then you can build the program by typing:

nmake -f Makefile.vc

The most common problem is that nmake (which is is part of MSVC) cannot be found because it is not in the path. You can fix this by running vcvars32.bat, which can be found in the MSVC bin directory (usually C:\Program Files\Microsoft Visual Studio\VC98\Bin). After successfully execute the nmake command, you will see the following message in the command window

You will find a newly generated nim.exe in the directory.

2.3.3      Start newly generated Nim

1.      Start the newly configured Nim game and see whether the parameters are changed or not. Double click game in the object tree as follow.

You will see the following window

2.      Click Params to see the parameters of game

All the two parameters are listed and we notice their values have been changed. Double Click each of the parameters you can see its value as follow.

3.      Run the game and it is your turn to first pick up sticks. Pick up 4, then the other player will pick 1, then, pick up 4 again, and you will win.

Now you have learned how change parameters and make file in OMNeT++

<to top> <to back>


3         Understanding the code

 

There are various ways to understand the implementation of a new simulation. I found the following approach the most useful. First I run it, of course, to get an understanding of where the various entities reside and how they exchange jobs. Then I work through the files belonging to each entity separately. I start with the .ned file to understand what goes in and out of a module, and the parameters it needs. Then I give the header file a brief look to become familiar with the module’s specific internal variables and functions. Finally I study the C++ code belonging to the module. Once I somewhat understand what this first module does, I take the next module in the simulation chain, that is, the module that gets its messages from the one I just studied. Working this way, I gain a quicker understanding of what is going on than by first working through all .ned files, than all the C++ files, etc.

 

3.1      NED file

Each entity in a simulation needs to communicate via messages with itself and other entities. Messages can be used for various purposes. One is to represent sticks that are available. Another is to convey information of the entity’s state to itself in the future, or to other entities. Specifically, the Nim example contains three entities: a game module, two player modules. Clearly, all these modules need in- and output gates to receive and send messages. The .ned file specifies these gates. In our example, the game module has two input and two output gates. Furthermore these modules may need parameters such as number of sticks, first players, etc. These parameters need be declared in the .ned files too. The definition of the parameters, i.e., giving them a value, takes place when the simulation starts.

 

The next step is to glue all the modules together to form a network. This should be done by a compound module. This new module uses the simple modules and connects them into networks. Besides this, it passes parameter values on to them during the simulation. Finally it gives some directives on where on the canvas the simple modules should appear. Take especially notice of the syntax, and be aware of when to use a comma ‘,’, and a semicolon ‘;’. I made some time consuming errors by not using them in the appropriate way. Note that this hierarchy of modules—simple modules forming compound modules, forming in turn other compound modules–provides a very efficient way to build large, complex networks. Start by building the parts, and then connect these parts to larger compound modules up to entire networks. The following is the source code of nim.ned

 

//-------------------------------------------------------------

// file: nim.ned

//        (part of NIM - an OMNeT++ demo simulation)

//

//  NIM is an ancient game with two players and a bunch of sticks.

//

//  The players take turns, removing 1..4 sticks from the heap

//  at each turn.

//

//  The player who must take the *last* stick is the loser.

//

//-------------------------------------------------------------

 

 

// Game --

//

// Declaration of simple module type Game

//

simple Game

    parameters:

        num_sticks : numeric, // starting number of sticks

        first_move : numeric; // 1=Player1, 2=Player2

    gates:

        in: from_player1; // input and output gates

        in: from_player2; // for connecting to Player1/Player2

        out: to_player1;

        out: to_player2;

endsimple

 

 

// Player --

//

// Interface declaration for different modules implementing players

//

simple Player

    gates:

        in: in; // gates for connecting to Game

        out: out;

endsimple

 

 

// Nim --

//

// The NIM game's network: Game and two players interconnected

//

module Nim

    parameters:

        player1_type : string,

        player2_type : string;

    submodules:

        // create the Game module, with the initial number of // intuniform (21, 31),

        // sticks and the starting player as random parameters

        game: Game;

            parameters:

                num_sticks =10,

                first_move = 1;

        // for players, define module type as parameter to

        // the parent module, Nim

        player1: player1_type like Player;

        player2: player2_type like Player;

    connections:

        player1.out --> game.from_player1;

        player1.in <-- game.to_player1;

                                       

        player2.out --> game.from_player2;

        player2.in <-- game.to_player2;

endmodule

 

 

// nim --

//

// an instance of the Nim module

//

network nim : Nim

    parameters:

        player1_type = input("InteractivePlayer"),

        player2_type = input("SmartPlayer");

endnetwork

 

3.2      The .cpp and .h Files

 

There are two .cpp files in this game. One is game.cpp and the other is players.cpp. Once you understand thes code, which may be a bit hard at first, you have mastered the core of the game. For the game.cpp, it organizes the game, counts the recent available sticks, decides who the next one to pick up sticks is, gives sticks to him, and outputs messages to terminal. For the players.cpp, it receives the sticks, decides the number of sticks it will take, and returns messages to game. Pay attention to the algorithm to be a smart player. It is easy and very interesting. Because there are a lot of API functions, it is very easy to get lost in code detail. Try to first understand its structure, then, check each API function detail.

The following is the game.cpp

//-------------------------------------------------------------

// file: game.cc

//        (part of NIM - an OMNeT++ demo simulation)

//-------------------------------------------------------------

 

#include <stdio.h>

#include <string.h>

 

#include "omnetpp.h"

 

// derive Game from cSimpleModule

class Game : public cSimpleModule

{

    Module_Class_Members(Game,cSimpleModule,16384)

       // this is a macro; it expands to constructor definition etc.

       // 16384 is the size for the coroutine stack (in bytes)

 

    virtual void activity();

       // this redefined virtual function holds the algorithm

};

 

// register the simple module class to OMNeT++

Define_Module( Game );

 

// Operation of Game:

//  The Game module first waits for a message from both players and extracts

//  the message names that are also the players' names. Then it enters a loop,

//  with the player_to_move variable alternating between 1 and 2. With each

//  iteration, it sends out a message with the current number of sticks to

//  the corresponding player and gets back the number of sticks taken by that

//  player. When the sticks are out, the module announces the winner and ends

//  the simulation.

 

void Game::activity()

{

    // strings to store player names; [0] is unused

    char player[3][32];

 

    // read parameter values

    int num_sticks = par("num_sticks");

    int player_to_move = par("first_move");

 

    // make the variables visible from Tkenv

    WATCH(num_sticks);

    WATCH(player_to_move);

 

    // waiting for players to tell their names

    ev << "Waiting for players to tell their names...\n";

    for (int i=0; i<2; i++)

    {

        cMessage *msg = receive();

        if (msg->arrivedOn("from_player1"))

                strcpy( player[1], msg->name());

        else

                strcpy( player[2], msg->name());

        delete msg;

    }

 

    ev << "OK, let the game begin!\n";

    ev << "Player 1: " << player[1] << "   Player 2: " << player[2]

       << "\n\n";

 

    // main loop of the game

    do

    {

        ev << "Sticks left: " << num_sticks << "\n";

        ev << "Player " << player_to_move << " ("

           << player[player_to_move] << ") to move.\n";

 

        // send out how many sticks we have

        char msgname[32];

        sprintf(msgname,"%d sticks left",num_sticks);

        cMessage *msg = new cMessage(msgname);

        msg->setKind(num_sticks);

 

        if (player_to_move == 1)

                send(msg, "to_player1");

        else

                send(msg, "to_player2");

 

        // wait for the player to answer how many he takes

        msg = receive();

        int sticks_taken = msg->kind();

        delete msg;

 

        num_sticks -= sticks_taken;

 

        ev << "Player " << player_to_move << " ("

           << player[player_to_move] << ") took "

           << sticks_taken << " stick(s).\n";

 

        // switch to the other player

        player_to_move = 3 - player_to_move;

    }

    while (num_sticks>0);

 

    ev << "\nPlayer " << player_to_move << " ("

       << player[player_to_move] << ") won!\n";

 

    endSimulation();

}

 

the following is players.cpp

//-------------------------------------------------------------

// file: players.cc

//        (part of NIM - an OMNeT++ demo simulation)

//-------------------------------------------------------------

 

#include <stdio.h>

#include <string.h>

 

#include "omnetpp.h"

#include "players.h"

 

// register player module types with the Player interface

Define_Module_Like( SmartPlayer, Player )

Define_Module_Like( SimplePlayer, Player )

Define_Module_Like( InteractivePlayer, Player )

 

 

// Operation of Player:

//  A Player first introduces himself by sendings its namestr to the Game

//  module. Then it enters an infinite loop; with each iteration, it receives

//  a message from Game with the number of sticks left, calculates its move

//  and sends back a message containing the move.

 

void Player::activity ()

{

    // initialisation phase: send module type to Game module

    cMessage *msg = new cMessage( playerName() );  // create a message

    send (msg, "out");                             // send it to Game

 

    // infinite loop to process moves; simulation will be terminated by Game

    for (;;)

    {

        // messages have several fields; here, we'll use the message kind

        // member to store the number of sticks

        cMessage *msgin = receive();        // receive message from Game

        int num_sticks = msgin->kind();    // extract message kind (an int)

                                           // this hold the number of sticks

                                           // still on the stack

        delete msgin;                      // dispose of the message

 

        // call virtual function (implemented in cSmartPlayer etc.)

        // to calculate the number of sticks to take.

        int move = calculateMove( num_sticks );

 

        ev << playerName() << " is taking " << move <<

              " out of "  << num_sticks << " sticks.\n";

 

        // send answer back to the Game module

        char msgname[32];

        sprintf(msgname,"Taking %d", move);

        cMessage *msgout = new cMessage(msgname); // create message

        msgout->setKind( move );

 

        send( msgout, "out");       // send the message to Game

    }

}

 

char *SimplePlayer::playerName()

{

    return "SimplePlayer";

}

 

int SimplePlayer::calculateMove( int num_sticks )

{

    // random choice, at least 1, at most 4

    return 1 + intrand( num_sticks<4 ? num_sticks : 4 );

}

 

char *SmartPlayer::playerName()

{

    return "SmartPlayer";

}

 

int SmartPlayer::calculateMove( int num_sticks )

{

    // calculate move

    int move = (num_sticks + 4) % 5;

 

    // if it comes out to be zero, it needs to be adjusted to one;

    // this means that the other player is in the winning position

    if (move == 0)  move = 1;

    return move;

}

 

char *InteractivePlayer::playerName()

{

    return "InteractivePlayer";

}

 

int InteractivePlayer::calculateMove( int num_sticks )

{

    // ask the user interactively

    int move;

    int max_sticks = num_sticks<4 ? num_sticks : 4;

 

    char prompt[64];

    sprintf(prompt,"%d sticks left. How many do you take (1..%d)?", num_sticks,max_sticks);

    ev.setPrompt(prompt);

    ev >> move;

    while (move<1 || move>max_sticks)

    {

        ev.printfmsg("Please enter a number in range 1..%d", max_sticks);

        ev >> move;

    }

    return move;

}

<to top> <to back>


4      References

[1] Nicky van Foreest” Simulating Queueing Networks with OMNeT++

[2] András Varga “OMNeT++ User Manual”