Member 13200081 Ответов: 1

Как заставить графические блоки перемещаться из одной фиксированной точки в другую фиксированную точку?


У меня есть четыре коробки с картинками
1 2
4 3

в указанный формат.
когда я нажимаю на кнопку, она поворачивает мои графические поля только один раз, как это
2 3
1 4

и таймер запустится и будет считать до 3 секунд, а затем автоматически нажимает мою кнопку, чтобы повернуть снова, но в этом случае мой код неверен, пожалуйста, помогите, чтобы я мог повернуть эту картинку коробки случайное количество раз?

Что я уже пробовал:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MoveBox
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            if (pictureBox1.Location.Equals(pictureBox1.Location))
            {
                //This swaps positions of picture boxes clockwise
                // first -90 degree rotation of four boxes
                pictureBox1.Location = new Point(0, 160);
                pictureBox2.Location = new Point(0, 0);
                pictureBox3.Location = new Point(180, 0);
                pictureBox4.Location = new Point(180, 160);
                moveTimer1.Enabled = true;
            }
            else if (pictureBox1.Location.Equals(pictureBox3.Location))
            {
                //This swaps positions of picture boxes clockwise
                // second -90 degree rotation of four boxes
                pictureBox1.Location = new Point(0, 0);
                pictureBox2.Location = new Point(180, 0);
                pictureBox3.Location = new Point(180, 160);
                pictureBox4.Location = new Point(0, 160);
            }
        }

        private void moveTimer1_Tick(object sender, EventArgs e)
        {
            int timer = Convert.ToInt32(label1.Text);
            label1.Text = Convert.ToString(timer + 1);
            while (timer == 3)
            {
                  moveTimer1.Enabled = false;
                  button1.PerformClick();
            }
            
        }
    }
}

Richard MacCutchan

while (timer == 3)
Вы будете перемещать ящики только в том случае, если таймер равен 3, Что произойдет только один раз.

1 Ответов

Рейтинг:
9

Maciej Los

Предполагая, что вы хотите вращать/перемещать изображения каждые 3 секунды, вы должны предоставить метод, который получает два случайных pictureboxes и заменяет изображения в них вместо замены мест pricuteboxes (если только вы не хотите перемещать pictureboxes).

Нажмите кнопку вкл:

Timer1.Interval = 3000 // Here 3000 milliseconds = 3 seconds  
Timer1.Start()  


На ТИКе таймера вы должны позвонить (например): MovePicture() метод.
Подумай об этом! Кажется, это легко осуществить. Вы должны определить List<Point> чтобы иметь возможность перетасовать их с помощью Случайный класс[^]:

//create initial list of picture locations
List<System.Drawing.Point> picLocations = new List<System.Drawing.Point>()
	{
		new System.Drawing.Point(0, 0),
		new System.Drawing.Point(180, 0),
		new System.Drawing.Point(180, 160),
		new System.Drawing.Point(0, 160)
	};


//...

//MovePicture method
//randomize 
Random r = new Random();
int f = r.Next(0,2); //get random number between 0 and 1 - a picture location from first row
System.Drawing.Point first = picLocations[f]; 
int s = r.Next(2,4); //get random number between 2 and 3 - a picture location from second row
System.Drawing.Point second = picLocations[s]; 

//replace locations
picLocations[f] = second;
picLocations[s] = first;

//finall
PictureBox1.Location = picLocation[0];
PictureBox2.Location = picLocation[1];
PictureBox3.Location = picLocation[2];
PictureBox4.Location = picLocation[3];


Пример расположения изображений выполнение одного таймера:
X    Y
180 160 
180 0 
0   0 
0   160 


Удачи вам!