홍시홍의 프로그래밍

[C#]타이머를 활용한 간단한 자동차 경기(윈도우 폼) 본문

C#

[C#]타이머를 활용한 간단한 자동차 경기(윈도우 폼)

홍시홍 2017. 4. 5. 14:45

윈도우폼에 라벨 2개 버튼 1개 텍스트상자 2개 타이머 2개를 활용해 간단한 자동차 경기를 만든다

라벨 대신 자동차 이미지를 활용해 만들 수 있다.


//자동차가 랜덤숫자로 평행하기 가기위한 숫자 생성
public partial class Form1 : Form 
    { 
        Random r = new Random(); 
        public Form1() 
        { 
            InitializeComponent(); 
        } 
//타이머 1
label1 의 x좌표가 랜덤 숫자에 맞게 움직일 수 있도록 설정
        private void timer1_Tick(object sender, EventArgs e) 
        { 
            int x = r.Next(20); 
            textBox1.Text = x + ""; 
            x = x + label1.Location.X; 
            label1.Location = new Point(x, 150); 

            if (label1.Location.X >= 500) 
                label1.Location = new Point(50, 150); 

        } 
//타이머2
label2의 x좌표가 랜덤 숫자에 맞게 움직일 수 있도록 설정
        private void timer2_Tick(object sender, EventArgs e) 
        { 
            int x = r.Next(20); 
            textBox2.Text = x + ""; 
            x = x + label2.Location.X; 
            label2.Location = new Point(x, 200); 

            if (label2.Location.X >= 500) 
                label2.Location = new Point(50, 200); 
        } 

//버튼
버튼을 누를 시 타이머가 작동되어 움직이는 화면이 출력된다.
        private void button1_Click(object sender, EventArgs e) 
        { 
            timer1.Enabled = true; 
            timer2.Enabled = true; 
        } 
    }

실행결과


0~20까지의 숫자가 생성되고 생성된 숫자에 따라 label1,2의 x좌표가 움직이게 된다.


Comments