private void loadButton_Click( object sender, EventArgs e )
{
// show file selection dialog
if ( openFileDialog.ShowDialog( ) == DialogResult.OK )
{
StreamReader reader = null;
try
{
// open selected file
reader = File.OpenText( openFileDialog.FileName );
string str = null;
// line counter
int lines = 0;
int j = 0;
// read the file
while ( ( str = reader.ReadLine( ) ) != null )
{
str = str.Trim( );
// skip comments and empty lines
if ( ( str == string.Empty ) || ( str[0] == ';' ) || ( str[0] == '\0' ) )
continue;
// split the string
string[] strs = str.Split( ' ' );
// check the line
if ( lines == 0 )
{
// get world size
mapWidth = int.Parse( strs[0] );
mapHeight = int.Parse( strs[1] );
map = new int[mapHeight, mapWidth];
}
else if ( lines == 1 )
{
// get agents count
if ( int.Parse( strs[0] ) != 1 )
{
MessageBox.Show( "The application supports only 1 agent in the worlds", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error );
break;
}
}
else if ( lines == 2 )
{
// agent position
agentStartX = int.Parse( strs[0] );
agentStartY = int.Parse( strs[1] );
agentStopX = int.Parse( strs[2] );
agentStopY = int.Parse( strs[3] );
// check position
if (
( agentStartX < 0 ) || ( agentStartX >= mapWidth ) ||
( agentStartY < 0 ) || ( agentStartY >= mapHeight ) ||
( agentStopX < 0 ) || ( agentStopX >= mapWidth ) ||
( agentStopY < 0 ) || ( agentStopY >= mapHeight )
)
{
MessageBox.Show( "Agent's start and stop coordinates should be inside the world area ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error );
break;
}
}
else if ( lines > 2 )
{
// map lines
if ( j < mapHeight )
{
for ( int i = 0; i < mapWidth; i++ )
{
map[j, i] = int.Parse( strs[i] );
if ( map[j, i] > 1 )
map[j, i] = 1;
}
j++;
}
}
lines++;
}
// set world's map
mapToDisplay = (int[,]) map.Clone( );
mapToDisplay[agentStartY, agentStartX] = 2;
mapToDisplay[agentStopY, agentStopX] = 3;
cellWorld.Map = mapToDisplay;
// show world's size
worldSizeBox.Text = string.Format( "{0} x {1}", mapWidth, mapHeight );
// enable learning button
startLearningButton.Enabled = true;
}
catch ( Exception )
{
MessageBox.Show( "Failed reading the map file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error );
return;
}
finally
{
// close file
if ( reader != null )
reader.Close( );
}
}
}