본문 바로가기
IT/swift

100 days of SwiftUI - Day20, Day21, Day22

by 가능성1g 2024. 11. 18.
반응형

유우명한 깃발 게임을 swiftUI를 이용해 만드는 방법이다. 

이제 좀 봐줄만 하면서 내가 만들었지만 재밌다 흐흐..

색감? 같은게 정하는 방법이 있어서 간단한데 제법 이쁘게 나오니 먼가 한거 같은 감도가 업!

 

도전과제 ( 점수 표시하기, 8번 하면 다시 처음으로 돌아가기, 정답 틀리면 찍은 국기명 보여주기 ) 까지 완료해본 소스

 

//
//  ContentView.swift
//  GuessTheFlag
//
//  Created by HanTJ on 11/18/24.
//

import SwiftUI

struct ContentView: View {
    @State private var showingScore = false
    @State private var gameEnd = false
    @State private var scoreTitle = ""
    @State private var flagTappedName = ""
    
    @State private var countries = ["Estonia", "France", "Germany", "Ireland", "Italy", "Nigeria", "Poland", "Spain", "UK", "Ukraine", "US"].shuffled()
    @State private var correctAnswer = Int.random(in:0...2)
    
    @State private var score: Int = 0
    
    @State private var gameCount = 0
    
    var body: some View {
        ZStack{
//            LinearGradient(colors: [.blue, .black], startPoint: .top, endPoint: .bottom)
//                .ignoresSafeArea()
            RadialGradient(stops: [
                .init(color: Color(red: 0.1, green: 0.2, blue: 0.45), location: 0.3),
                .init(color: Color(red: 0.76, green: 0.15, blue: 0.26), location: 0.3)
            ], center: .top, startRadius: 200, endRadius: 400)
            .ignoresSafeArea()
            
            VStack {
                Spacer()
                Text("Guess The Flag")
                    .font(.largeTitle.bold())
                    .foregroundColor(.white)
                
                VStack(spacing: 15) {
                    VStack {
                        Text("Tap the flag of")
                            .font(.subheadline.weight(.heavy))
                            .foregroundStyle(.white)
                        
                        Text(countries[correctAnswer])
                            .font(.largeTitle.weight(.semibold))
                            .foregroundStyle(.white)
                    }
                    
                    ForEach(0..<3) { number in
                        Button {
                            flagTapped(number)
                        } label: {
                            Image(countries[number])
                                .clipShape(.capsule)
                                .shadow(radius: 5)
                        }
                        
                    }
                }
                Spacer()
                Spacer()
                Text("Score: \(score)")
                    .foregroundStyle(.secondary)
                    .font(.title.bold())
                Spacer()
            }
            .frame(maxWidth: .infinity)
            .padding(.vertical, 20)
            .background(.regularMaterial)
            .clipShape(.rect(cornerRadius: 20))
            .padding()
        }
        .alert(scoreTitle, isPresented: $showingScore) {
            Button("Continue", action: askQuestion)
        } message: {
            if scoreTitle == "Wrong" {
                Text("Your Tapped Flag is \(flagTappedName)")
            }
            Text("Your score is \(score)")
        }
        .alert("GameEnd", isPresented: $gameEnd) {
            Button("Reset", action: resetGame )
        } message: {
            Text("Your Last score is \(score)")
        }
    }
    
    func flagTapped(_ number: Int) {
        gameCount += 1
        if number == correctAnswer {
            scoreTitle = "Correct"
            score += 100
        } else {
            scoreTitle = "Wrong"
            flagTappedName = countries[number]
        }
        if gameCount < 8 {
            showingScore = true
        } else {
            gameEnd = true
        }
    }
    
    func askQuestion() {
        countries.shuffle()
        correctAnswer = Int.random(in: 0...2)
    }
    
    func resetGame() {
        score = 0
    }
}

#Preview {
    ContentView()
}

 호옥시 진짜로 실행해 보려면 프로젝트에 이미지를 추가 해야함. 필요하면 댓글 ㄱㄱ (아마도 아무도 없겠지)

저장이 필요한 변수는 @State를 남발하고 있는데 맞나 고민이 시작됨

Gradient의 종류가 많다! 이쁘게 꾸밀때 좋다

ZStack, VStack, HStack, Spacer()

alert 을 이용한 알림창 만들기

배열의 기본 함수로 shuffle 이 있다니, 난사람들이구만.

반응형