Почему так странно отрисовывает графику?
Выполняю функцию createMap в новом потоке при запуске игры. Почему не все квадраты отрисовывает? Вопрос частично решается введением задержки при отрисовке, но тогда карта рисуется ~секунду... При срабатывании таймера, который вызывает функцию update всё рисуется нормально. И ещё, подскажите, пожалуйста, правильно ли многопоточность организовал? Есть ощущение, что намудрил... Код:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Timers;
using System.IO;
namespace RTS
{
public partial class Game : Form
{
int time;
int gameSpeed;
const int width = 15;
const int height = 15;
int[,] map;
Graphics g;
Image grassImage = new Bitmap(Environment.CurrentDirectory + @"\Image\grass.png");
public Game(int countBot, int _gameSpeed)
{
InitializeComponent();
gameSpeed = _gameSpeed;
time = _gameSpeed;
map = new int[width, height]{
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
};
timeLastText.Text = Convert.ToString(_gameSpeed);
System.Timers.Timer timerLast = new System.Timers.Timer(1000);
timerLast.Elapsed += TimeLast;
timerLast.Start();
Thread.Sleep(1000);
System.Timers.Timer timer = new System.Timers.Timer(gameSpeed*1000);
timer.Elapsed += update;
timer.Start();
Thread thr = new Thread(createMap);
thr.Start();
}
public void createMap()
{
g = this.CreateGraphics();
for (int i = 0; i < 15; i++)
{
for (int j = 0; j < 15; j++)
{
//Thread.Sleep(5);
if (map[i, j] == 1)
{
g.DrawImage(grassImage, 0 + (59 * i), 60 + (59 * j), new Rectangle(new Point(0, 0), new Size(45, 45)), GraphicsUnit.Pixel);
}
}
}
}
private void Game_FormClosed(object sender, FormClosedEventArgs e)
{
Environment.Exit(0);
}
public void TimeLast(object sender, EventArgs e)
{
Action action = () =>
{
timeLastText.Text = Convert.ToString(time);
time--;
};
if (InvokeRequired)
{
Invoke(action);
} else
{
action();
}
}
public void update(object sender, EventArgs e)
{
time = gameSpeed;
createMap();
}
}
}
