Random timer trong winform


mình có viết code random việc xuất hiện và văng của 4 quả trái cây trên
nhưng nó vẫn không thể random việc xuất hiện chỉ 1 trái và văng tới cuối ms random trái khác , có lúc đang văng trái nay thì trái kia lại văng luôn
ai giúp mình xem lại code vs ạ
//code

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 TestRanDomGame
{
    public partial class Form1 : Form
    {

        string[] hinh = new string[] { "apple.png", "blueberry.png", "orange.png", "strawberry.png" };
         int[] vitrikhoitao = new int[] { 30, 120, 210, 300 };

         PictureBox[] picvatroi = new PictureBox[4];
        Random r = new Random();

        public Form1()
        {
            InitializeComponent();

            // biến cục bộ
            #region  cờ ẩn hiện picturebox
            pic1.Visible = false;
            pic2.Visible = false;
            pic3.Visible = false;
            pic4.Visible = false;
            #endregion
        }
        public bool anhienpic(PictureBox pic01, PictureBox pic02, PictureBox pic03, PictureBox pic04)
        {
            pic01.Visible = false;
            pic02.Visible = false;
            pic03.Visible = false;
            pic04.Visible = false;
            return pic01.Visible = true;

        }
       
        private void Form1_Load(object sender, EventArgs e)
        {
           //timerrotdo.Start();
            timerRanDom.Start();

        }
        private void timerrotdo_Tick(object sender, EventArgs e)
        {
            foreach (Control x in this.Controls)
                if (x is PictureBox && x.Tag == "vatroi") {
                    if (x.Top > 555)
                    {
                        x.Top = 1;
                        timerRanDom.Start();
                    } 
                    else x.Top += 10;

                }
        }
        private void timerRanDom_Tick(object sender, EventArgs e)
        {
          
                int a = r.Next(0, 4);
                if (a == 0) anhienpic(pic1, pic2, pic3, pic4);
                if (a == 1) anhienpic(pic2, pic1, pic3, pic4);
                if (a == 2) anhienpic(pic3, pic1, pic2, pic4);
                if (a == 3) anhienpic(pic4, pic1, pic2, pic3);
                timerrotdo.Start();
           
                timerRanDom.Stop();
            

           
           

        }
    }
}

Nó không liên quan đến random. Thuật toán trong time bị sai.

PS: Nên dùng Thread, BackgroundWorker thay Timer.

3 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?