Объект в настоящее время используется в другом месте и System.InvalidOperationException - PullRequest
0 голосов
/ 20 мая 2019

Здравствуйте, я использую Picture Box с Visual Studio и C #, я сделал змейку, и она работает, но она падает сразу или через x раз.

Я прочитал проблему иэто потому, что я использую таймер для рисования на картинке Box, я пытался реализовать блокировку или избавиться от изображения, оба не удаются и, честно говоря, у меня нет большого опыта работы с C #, поэтому я, вероятно, сделал это неправильно, яЯ не уверен, что мой подход к рисованию - лучший вариант в этой степени, поэтому я спрашиваю, что я делаю неправильно, чтобы получить эти ошибки, и какое решение, пожалуйста?

Exception thrown: 'System.InvalidOperationException' in System.Drawing.dll
ERROR System.InvalidOperationException: Object is currently in use 
elsewhere.
at System.Drawing.Graphics.FromImage(Image image)
at game.Form1.Loop(Object source, ElapsedEventArgs e) in 
C:\Users\Edwin\source\repos\game\game\Form1.cs:line 42
The program '[16372] game.exe' has exited with code 0 (0x0).



using System;
using System.Drawing;
using System.Timers;
using System.Windows.Forms;

namespace game
{
public partial class Form1 : Form
{
    bool gameOver = false; // to do
    byte dir = 2, previosDirection = 2;
    int width, height, x, y, fruitX, fruitY, score, nTail = 30;
    int[] tailX = new int[1048576];
    int[] tailY = new int[1048576];
    Random rand = new Random();

    public Form1()
    {
        InitializeComponent();
        this.KeyPreview = true;
        this.KeyPress += new KeyPressEventHandler(Form1_KeyPress);
        width = pictureBox1.Width;
        height = pictureBox1.Height;
        x = width / 2;
        y = height / 2;
        fruitX = rand.Next(2, width - 2);
        fruitY = rand.Next(2, height - 2);
        var aTimer = new System.Timers.Timer(10);
        aTimer.Elapsed += new ElapsedEventHandler(Loop);
        aTimer.AutoReset = true;
        aTimer.Enabled = true;
    }

    private void Loop(object source, ElapsedEventArgs e)
    {
        try // An unhandled exception of type 'System.InvalidOperationException' occurred in System.Drawing.dll System.InvalidOperationException: 'Object is currently in use elsewhere.'
        {
            pictureBox1.Image = new Bitmap(pictureBox1.Width, pictureBox1.Height);
            // lock(pictureBox1.Image)
            // {
            // score
            Graphics g = Graphics.FromImage(pictureBox1.Image);
            g.FillRectangle(new SolidBrush(Color.White), new Rectangle(0, 0, pictureBox1.Width, pictureBox1.Height)); // i used this code to make the background color white 
            g.DrawString("Score", new Font("Times New Roman", 10), new SolidBrush(Color.Black), new PointF(0, 0));
            g.DrawString(score.ToString(), new Font("Times New Roman", 10), new SolidBrush(Color.Black), new PointF(35, 0));
            // head - replace for bitmap and rotate by 90' for given direction of travel
            ((Bitmap)pictureBox1.Image).SetPixel(x, y, Color.Black);
            ((Bitmap)pictureBox1.Image).SetPixel(x + 1, y, Color.Black);
            ((Bitmap)pictureBox1.Image).SetPixel(x, y + 1, Color.Black);
            ((Bitmap)pictureBox1.Image).SetPixel(x + 1, y + 1, Color.Black);
            // fruit - replace for bitmap - need to add bonus treat at some point
            ((Bitmap)pictureBox1.Image).SetPixel(fruitX, fruitY, Color.Red);
            ((Bitmap)pictureBox1.Image).SetPixel(fruitX + 1, fruitY, Color.Red);
            ((Bitmap)pictureBox1.Image).SetPixel(fruitX, fruitY + 1, Color.Red);
            ((Bitmap)pictureBox1.Image).SetPixel(fruitX + 1, fruitY + 1, Color.Red);
            // tail
            for (int k = 0; k < nTail; k++)
            {
                ((Bitmap)pictureBox1.Image).SetPixel(tailX[k], tailY[k], Color.Black);
                ((Bitmap)pictureBox1.Image).SetPixel(tailX[k] + 1, tailY[k], Color.Black);
                ((Bitmap)pictureBox1.Image).SetPixel(tailX[k], tailY[k] + 1, Color.Black);
                ((Bitmap)pictureBox1.Image).SetPixel(tailX[k] + 1, tailY[k] + 1, Color.Black);
            }
            //}
            Logic();
            // pictureBox1.Image.Dispose();
        }
        catch (Exception f)
        {
            Console.WriteLine("ERROR " + f);
        }
    }

    private void Form1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if ((e.KeyChar == 'a' || e.KeyChar == 'A') && previosDirection != 2) dir = 1;
        else if ((e.KeyChar == 'd' || e.KeyChar == 'D') && previosDirection != 1) dir = 2;
        else if ((e.KeyChar == 'w' || e.KeyChar == 'W') && previosDirection != 4) dir = 3;
        else if ((e.KeyChar == 's' || e.KeyChar == 'S') && previosDirection != 3) dir = 4;
        else if (e.KeyChar == 'x' || e.KeyChar == 'X')
        {
            this.Close();
        }
        previosDirection = dir;
    }

    private void Logic()
    {
        // keep track of snake pixels
        int prevX = tailX[0];
        int prevY = tailY[0];
        int prev2X, prev2Y;
        tailX[0] = x;
        tailY[0] = y;
        for (int i = 1; i < nTail; i++)
        {
            prev2X = tailX[i];
            prev2Y = tailY[i];
            tailX[i] = prevX;
            tailY[i] = prevY;
            prevX = prev2X;
            prevY = prev2Y;
        }
        // change direction of travel
        if (dir == 1) x--;
        else if (dir == 2) x++;
        else if (dir == 3) y--;
        else if (dir == 4) y++;
        // screen overflow
        if (x >= width - 3) x = 3;
        else if (x <= 3) x = width - 3;
        if (y >= height - 2) y = 2;
        else if (y <= 3) y = height - 3;
        // tail collision
        for (int i = 0; i < nTail; i++)
        {
            if (tailX[i] == x && tailY[i] == y)
            {
                gameOver = true;
            }
        }
        // eatten fruit
        if (x >= fruitX - 2 && x <= fruitX + 2 && y >= fruitY - 2 && y <= fruitY + 2)
        {
            score += 10;
            fruitX = rand.Next(4, width - 4);
            fruitY = rand.Next(4, height - 4);
            nTail += 4;
        }
    }
}

}

...