subindev 개발 블로그

[C#] 1. 산성비 게임 - C#적응과 windform 본문

.NET/windform

[C#] 1. 산성비 게임 - C#적응과 windform

subindev 2025. 12. 1. 17:47

 

c#과 친해지기 위해 오늘은 산성비 게임을 만들어봤다.

 

🎮 C# 윈폼으로 만드는 ‘산성비 게임’ 

(동적 라벨, 타이머, 점수/목숨, 게임 종료까지 구현)


📌 1. 화면 구성 요소

✔ 기본 UI 구성

  • TextBox (입력창)
  • 입력 버튼
  • 게임 시작 버튼
  • 점수 라벨(scoreLbl)
  • 목숨 라벨(lifeLbl)

📌 2. 게임 시작 시 라벨 생성

게임을 시작하면 단어가 적힌 라벨을 동적으로 생성해 떨어지도록 구현.

  • 랜덤한 단어 선택
  • 랜덤 위치에 Label 생성
  • 리스트에 넣어 관리

📌 3. 단어 입력 처리

  • 입력값이 비어 있으면 무시
  • 떨어지고 있는 모든 라벨과 입력값 비교
  • 맞는 단어 →
    ✔ 화면에서 제거
    ✔ 리스트에서도 제거
    ✔ 점수 +1

📌 4. 타이머 기반 단어 생성 & 낙하 로직

✔ createTimer

일정 시간마다 새로운 단어 라벨 생성.

✔ fallingTimer

짧은 간격으로 모든 라벨의 Top 값을 증가시켜 아래로 떨어뜨림.

✔ 화면 밖으로 내려오면

  • 라벨 제거
  • life--
  • 목숨이 0 되면 → 게임 종료

📌 5. 목숨 시스템 & 게임 종료

  • 처음 목숨은 3개
  • 단어가 입력칸 아래로 내려가면 life -= 1
  • 0 이하 → 게임 종료 처리
  • 게임 종료 시 모든 상태 초기화

📌 6. 주요 메서드 정리

메서드 설명

Form1() UI 초기 설정, 타이머 설정 및 이벤트 연결
StartBtn_Click() 기존 라벨 제거, 리스트 초기화, 게임 시작
InputBtn_Click() 입력 단어와 떨어지는 단어 비교 후 맞으면 제거 + 점수 증가
CreateFallingWord() 새로운 단어 라벨 생성 및 화면에 추가
CreateTimer_Tick() 일정 시간마다 새 단어 생성
FallingTimer_Tick() 단어 내려가게 하고 바닥에 닿으면 생명 감소
GameOver() 타이머 중지, 모든 라벨 제거, 점수/목숨 초기화

📌 전체 코드 (form1.cs)

using Microsoft.VisualBasic.Logging;
using System.Web;
using Timer = System.Windows.Forms.Timer;

namespace DEV_EDU
{
    public partial class Form1 : Form
    {
        Random rand = new Random();

        // 점수, 목숨 변수
        int score = 0;
        int life = 3;

        // 타이머
        Timer createTimer = new Timer();
        Timer fallingTimer = new Timer();

        int fallSpeed = 2;

        string[] words = {
                "apple", "banana", "cat", "dog", "rain", "cloud", "water",
                "phone", "mouse", "table", "chair", "happy", "sad", "fast"
            };

        List<Label> fallingLabels = new List<Label>();

        public Form1()
        {
            InitializeComponent();

            this.AcceptButton = inputBtn;

            createTimer.Interval = 2000;
            createTimer.Tick += CreateTimer_Tick;

            fallingTimer.Interval = 30;
            fallingTimer.Tick += FallingTimer_Tick;
        }

        // 입력 버튼 클릭
        private void InputBtn_Click(object sender, EventArgs e)
        {
            string userInput = textBox1.Text.Trim();

            if (string.IsNullOrEmpty(userInput))
            {
                return;
            }

            foreach (Label lbl in fallingLabels)
            {

📌 전체 코드 (form1Designer.cs)

namespace DEV_EDU
{
    partial class Form1
    {
        /// <summary>
        ///  Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        ///  Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code

        /// <summary>
        ///  Required method for Designer support - do not modify
        ///  the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            inputBtn = new Button();
            textBox1 = new TextBox();
            startBtn = new Button();
            scoreLbl = new Label();
            lifeLbl = new Label();
            SuspendLayout();
            // 
            // inputBtn
            // 
            inputBtn.Location = new Point(484, 380);
            inputBtn.Name = "inputBtn";
            inputBtn.Size = new Size(126, 27);
            inputBtn.TabIndex = 0;
            inputBtn.Text = "입력";
            inputBtn.UseVisualStyleBackColor = true;
            inputBtn.Click += InputBtn_Click;
            // 
            // textBox1
            // 
            textBox1.Location = new Point(277, 380);
            textBox1.Name = "textBox1";
            textBox1.Size = new Size(190, 27);
            textBox1.TabIndex = 1;
            // 
            // startBtn
            // 
            startBtn.Location = new Point(12, 14);
            startBtn.Name = "startBtn";
            startBtn.Size = new Size(94, 29);
            startBtn.TabIndex = 3;
            startBtn.Text = "게임 시작";
            startBtn.UseVisualStyleBackColor = true;
            startBtn.Click += StartBtn_Click;
            // 
            // scoreLbl
            // 
            scoreLbl.AutoSize = true;
            scoreLbl.Location = new Point(722, 18);
            scoreLbl.Name = "scoreLbl";
            scoreLbl.Size = new Size(0, 20);
            scoreLbl.TabIndex = 4;
 
            // 
            // lifeLbl
            // 
            lifeLbl.AutoSize = true;
            lifeLbl.Location = new Point(722, 43);
            lifeLbl.Name = "lifeLbl";
            lifeLbl.Size = new Size(0, 20);
            lifeLbl.TabIndex = 5;
            // 
            // Form1
            // 
            AutoScaleDimensions = new SizeF(9F, 20F);
            AutoScaleMode = AutoScaleMode.Font;
            ClientSize = new Size(800, 450);
            Controls.Add(lifeLbl);
            Controls.Add(scoreLbl);
            Controls.Add(startBtn);
            Controls.Add(textBox1);
            Controls.Add(inputBtn);
            Name = "Form1";
            Text = "Form1";
            Load += Form1_Load;
            ResumeLayout(false);
            PerformLayout();
        }

        #endregion

        private Button inputBtn;
        private TextBox textBox1;
        private Button startBtn;
        private Label scoreLbl;
        private Label lifeLbl;
    }
}

 

📌 결과 화면

결과창

 

 

 

'.NET > windform' 카테고리의 다른 글

[C#] 2. 산성비 게임 - Oracle & windform 연동  (0) 2025.12.01