관리 메뉴

막내의 막무가내 프로그래밍 & 일상

[Flutter] Udemy 플러터 강의 섹션 11 학습 (Boss Level Challenge 2 - Destini) 본문

플러터(Flutter) & Dart

[Flutter] Udemy 플러터 강의 섹션 11 학습 (Boss Level Challenge 2 - Destini)

막무가내막내 2022. 4. 3. 16:38
728x90

 

 

 

 

 

[이전학습]

https://youngest-programming.tistory.com/624

 

[Flutter] Udemy 플러터 강의 섹션 10 학습 (섹션 10: Quizzler -Modularising & Organising FlutterCode)

[이전학습] https://youngest-programming.tistory.com/623 [Flutter] Udemy 플러터 강의 섹션 9 학습 (Xylophone - Using Flutter and Dart Packages toSpeed Up Development) [이전학습] https://youngest-prog..

youngest-programming.tistory.com

 

[참고]

https://www.udemy.com/course/flutter-bootcamp-with-dart/

 

The Complete 2021 Flutter Development Bootcamp with Dart

Officially created in collaboration with the Google Flutter team.

www.udemy.com

 

https://github.com/mtjin/flutter-practice

 

GitHub - mtjin/flutter-practice: Learning About Flutter (플러터 공부)

Learning About Flutter (플러터 공부). Contribute to mtjin/flutter-practice development by creating an account on GitHub.

github.com

 

 


[105. Destini - A Choose Your Own Adventure Game]

 

이번 섹션은 보스 챌린지를 할 차례입니다.  

지금까지 배운 내용을 바탕으로 운명게임을 만들 예정입니다. 

운명게임이란 두가지 선택지에서 유저가 선택한 내용에 따라 앞으로 스토리가 달라지는 게임이라고 보시면 됩니다.

 

 


[108. Step 1 - Adding a Image as a Background]

 

 

 

풀스크린 배경을 하는 방법

BoxDecoration 사용

https://stackoverflow.com/questions/44179889/how-do-i-set-background-image-in-flutter

 

How do I Set Background image in Flutter?

I am trying to set a background image for the home page. I am getting the image place from start of the screen and filling the width but not the height. Am I missing something in my code? Are there

stackoverflow.com

class _StoryPageState extends State<StoryPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        //TODO: Step 1 - Add background.png to this Container as a background image.
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('images/background.png'),
            fit: BoxFit.cover,
          ),
        ),
        padding: EdgeInsets.symmetric(vertical: 50.0, horizontal: 15.0),
        constraints: BoxConstraints.expand(),

[110. Step 2/3/4 - Create a New Story Class]

 

//TODO: Step 2 - Create a new class called Story.
class Story {
  //TODO: Step 3 - Create 3 properties for this class, A. storyTitle to store the story text. B. choice1 to store the text for choice 1, C. choice2 to store the text for choice 2.
  String storyTitle;
  String choice1;
  String choice2;

  //TODO: Step 4 - Create a Constructor for this class to be able to initialise the properties created in step 3.
  Story({this.storyTitle, this.choice1, this.choice2});
}

여기서 Step4의 클래스 생성자 의미는 다음을 간단하게 한거다.

class Story {
  String storyTitle;
  String choice1;
  String choice2;
  Story({String storyTitle, String choice1, String choice2}) {
    this.storyTitle = storyTitle;
    this.choice1 = choice1;
    this.choice2 = choice2;
  }
}

 

 


 

[111. Step 5/6/7 - Create the Story Brain]

 

//TODO: Step 6 - import the story.dart file into this file.
import 'story.dart';
//TODO: Step 5 - Create a new class called StoryBrain.
class StoryBrain{

}
//TODO: Step 7 - Uncomment the lines below to include storyData as a private property in StoryBrain. Hint: You might need to change something in story.dart to make this work.

List<Story> _storyData = [
 Story(
     storyTitle:
     'Your car has blown a tire on a winding road in the middle of nowhere with no cell phone reception. You decide to hitchhike. A rusty pickup truck rumbles to a stop next to you. A man with a wide brimmed hat with soulless eyes opens the passenger door for you and asks: "Need a ride, boy?".',
     choice1: 'I\'ll hop in. Thanks for the help!',
     choice2: 'Better ask him if he\'s a murderer first.'),
 Story(
     storyTitle: 'He nods slowly, unphased by the question.',
     choice1: 'At least he\'s honest. I\'ll climb in.',
     choice2: 'Wait, I know how to change a tire.'),
 Story(
     storyTitle:
     'As you begin to drive, the stranger starts talking about his relationship with his mother. He gets angrier and angrier by the minute. He asks you to open the glovebox. Inside you find a bloody knife, two severed fingers, and a cassette tape of Elton John. He reaches for the glove box.',
     choice1: 'I love Elton John! Hand him the cassette tape.',
     choice2: 'It\'s him or me! You take the knife and stab him.'),
 Story(
     storyTitle:
     'What? Such a cop out! Did you know traffic accidents are the second leading cause of accidental death for most adult age groups?',
     choice1: 'Restart',
     choice2: ''),
 Story(
     storyTitle:
     'As you smash through the guardrail and careen towards the jagged rocks below you reflect on the dubious wisdom of stabbing someone while they are driving a car you are in.',
     choice1: 'Restart',
     choice2: ''),
 Story(
     storyTitle:
     'You bond with the murderer while crooning verses of "Can you feel the love tonight". He drops you off at the next town. Before you go he asks you if you know any good places to dump bodies. You reply: "Try the pier".',
     choice1: 'Restart',
     choice2: '')
];

 

 

 

 


[112. Display the Story in the App]

 

 

함수 만들기

//TODO: Step 8 - Create a method called getStory() that returns the first storyTitle from _storyData.
String getStory() {
  return _storyData[0].storyTitle;
}

 

객체 생성

//TODO: Step 9 - Create a new storyBrain object from the StoryBrain class.
StoryBrain storyBrain = StoryBrain();

 

객체 함수 호출

child: SafeArea(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Expanded(
                flex: 12,
                child: Center(
                  child: Text(
                    //TODO: Step 10 - use the storyBrain to get the first story title and display it in this Text Widget.
                    storyBrain.getStory(),
                    style: TextStyle(
                      fontSize: 25.0,
                    ),
                  ),
                ),
              ),

 


[113. Step 11/12/13/14 - Display the Choices in the App]

 

//TODO: Step 11 - Create a method called getChoice1() that returns the text for the first choice1 from _storyData.
  String getChoice1() {
    return _storyData[0].choice1;
  }

//TODO: Step 12 - Create a method called getChoice2() that returns the text for the first choice2 from _storyData.
  String getChoice2() {
    return _storyData[0].choice2;
  }

`

Expanded(
                flex: 2,
                child: FlatButton(
                  onPressed: () {
                    //Choice 1 made by user.
                    //TODO: Step 18 - Call the nextStory() method from storyBrain and pass the number 1 as the choice made by the user.
                  },
                  color: Colors.red,
                  child: Text(
                    //TODO: Step 13 - Use the storyBrain to get the text for choice 1.
                    storyBrain.getChoice1(),
                    style: TextStyle(
                      fontSize: 20.0,
                    ),
                  ),
                ),
              ),
 child: FlatButton(
                  onPressed: () {
                    //Choice 2 made by user.
                    //TODO: Step 19 - Call the nextStory() method from storyBrain and pass the number 2 as the choice made by the user.
                  },
                  color: Colors.blue,
                  child: Text(
                    //TODO: Step 14 - Use the storyBrain to get the text for choice 2.
                    storyBrain.getChoice2(),
                    style: TextStyle(
                      fontSize: 20.0,
                    ),
                  ),
                ),

 

 


[114. Update the Story Based on User Choice]

 

변수 초기화 및 함수 생성

//TODO: Step 16 - Create a property called storyNumber which starts with a value of 0. This will be used to track which story the user is currently viewing.
  int storyNumber = 0;

//TODO: Step 17 - Create a method called nextStory(), it should not have any outputs but it should have 1 input called choiceNumber which will be the choice number (int) made by the user.
  void nextStory(int choiceNumber) {}

 

클릭 이벤트 함수 호출

 child: FlatButton(
                  onPressed: () {
                    //Choice 1 made by user.
                    //TODO: Step 18 - Call the nextStory() method from storyBrain and pass the number 1 as the choice made by the user.
                    storyBrain.nextStory(1);
                  },
  child: FlatButton(
                  onPressed: () {
                    //Choice 2 made by user.
                    //TODO: Step 19 - Call the nextStory() method from storyBrain and pass the number 2 as the choice made by the user.
                    storyBrain.nextStory(2);
                  },

 

 

 

 

 


[115. Step 21 - Use the Story Plan to Progress through the Story]

 

위와 같이 스토리가 선택에 따라 진행되도록 로직 구현

 if/else 문 사용

//TODO: Step 17 - Create a method called nextStory(), it should not have any outputs but it should have 1 input called choiceNumber which will be the choice number (int) made by the user.
  void nextStory(int choiceNumber) {
    //TODO: Step 21 - Using the story plan, update nextStory to change the storyNumber depending on the choice made by the user.
    if (choiceNumber == 1 && storyNumber == 0) {
      storyNumber = 2;
    } else if (choiceNumber == 2 && storyNumber == 0) {
      storyNumber = 1;
    } else if (choiceNumber == 1 && storyNumber == 1) {
      storyNumber = 2;
    } else if (choiceNumber == 2 && storyNumber == 1) {
      storyNumber = 3;
    } else if (choiceNumber == 1 && storyNumber == 2) {
      storyNumber = 5;
    } else if (choiceNumber == 2 && storyNumber == 2) {
      storyNumber = 4;
    }
  }

 

 


[116. Step 22/23/24 - Restart the Game When the User Reaches the End]

 

restart() 재시작 구현

//TODO: Step 17 - Create a method called nextStory(), it should not have any outputs but it should have 1 input called choiceNumber which will be the choice number (int) made by the user.
  void nextStory(int choiceNumber) {
    //TODO: Step 20 - Download the story plan here: https://drive.google.com/uc?export=download&id=1KU6EghkO9Hf2hRM0756xFHgNaZyGCou3
    //TODO: Step 21 - Using the story plan, update nextStory to change the storyNumber depending on the choice made by the user.
    if (choiceNumber == 1 && storyNumber == 0) {
      storyNumber = 2;
    } else if (choiceNumber == 2 && storyNumber == 0) {
      storyNumber = 1;
    } else if (choiceNumber == 1 && storyNumber == 1) {
      storyNumber = 2;
    } else if (choiceNumber == 2 && storyNumber == 1) {
      storyNumber = 3;
    } else if (choiceNumber == 1 && storyNumber == 2) {
      storyNumber = 5;
    } else if (choiceNumber == 2 && storyNumber == 2) {
      storyNumber = 4;
    }
//TODO: Step 22 - In nextStory() if the storyNumber is equal to 3 or 4 or 5, that means it's the end of the game and it should call a method called restart() that resets the storyNumber to 0.
    else if (storyNumber == 3 || storyNumber == 4 || storyNumber == 5) {
      restart();
    }
  }

  //TODO: Step 22
  void restart() {
    storyNumber = 0;
  }

 

기존 0으로 하드코딩되어있던거 변수로 변경 (step 23)

//TODO: Step 23 - Use the storyNumber property inside getStory(), getChoice1() and getChoice2() so that it gets the updated story and choices rather than always just the first (0th) one.
//TODO: Step 8 - Create a method called getStory() that returns the first storyTitle from _storyData.
  String getStory() {
    return _storyData[storyNumber].storyTitle;
  }

//TODO: Step 11 - Create a method called getChoice1() that returns the text for the first choice1 from _storyData.
  String getChoice1() {
    return _storyData[storyNumber].choice1;
  }

//TODO: Step 12 - Create a method called getChoice2() that returns the text for the first choice2 from _storyData.
  String getChoice2() {
    return _storyData[storyNumber].choice2;
  }

 

기존에 클릭리스너에 구현되어어있던거 함수 구현에 따라 UI상태가 바뀔 수 있도록 setState() 해줌

onPressed: () {
                    //Choice 2 made by user.
                    //TODO: Step 19 - Call the nextStory() method from storyBrain and pass the number 2 as the choice made by the user.
                    //TODO: Step 24 - Run the app and try to figure out what code you need to add to this file to make the story change when you press on the choice buttons.
                    setState(() {
                      storyBrain.nextStory(2);
                    });
                  },

 

 


 

[117. Step 25 - Renaming and Refactoring Using Android Studio]

 

dart 에서는 변수 앞에 _를 붙이면 private

//TODO: Step 16 - Create a property called storyNumber which starts with a value of 0. This will be used to track which story the user is currently viewing.
  int _storyNumber = 0;

 


 

[118. Step 26/27/28 - Hiding Buttons]

 

Visibility 위젯 사용 (Show/Hide 기능이 있는 위젯) - step 26

//TODO: Step 26 - Use a Flutter Visibility Widget to wrap this FlatButton.
                //TODO: Step 28 - Set the "visible" property of the Visibility Widget to equal the output from the buttonShouldBeVisible() method in the storyBrain.
                child: Visibility(
                  child: FlatButton(
                    onPressed: () {
                      //Choice 2 made by user.
                      //TODO: Step 19 - Call the nextStory() method from storyBrain and pass the number 2 as the choice made by the user.
                      //TODO: Step 24 - Run the app and try to figure out what code you need to add to this file to make the story change when you press on the choice buttons.
                      setState(() {
                        storyBrain.nextStory(2);
                      });
                    },
                    color: Colors.blue,
                    child: Text(
                      //TODO: Step 14 - Use the storyBrain to get the text for choice 2.
                      storyBrain.getChoice2(),
                      style: TextStyle(
                        fontSize: 20.0,
                      ),
                    ),

 

StoryBrain 클래스에 bool 함수 구현

//TODO: Step 27 - Create a method called buttonShouldBeVisible() which checks to see if storyNumber is 0 or 1 or 2 (when both buttons should show choices) and return true if that is the case, else it should return false.
  bool buttonShouldBeVisible() {
    return _storyNumber < 3;
  }

 

Visiblity 위젯에 visible 속성추가하여 마지막 스토리일때 버튼이 보이게끔 설정한다.

child: Visibility(
                  //TODO: Step 28 - Set the "visible" property of the Visibility Widget to equal the output from the buttonShouldBeVisible() method in the storyBrain.
                  visible: storyBrain.buttonShouldBeVisible(),
                  child: FlatButton(
                    onPressed: () {
                      //Choice 2 made by user.
                      //TODO: Step 19 - Call the nextStory() method from storyBrain and pass the number 2 as the choice made by the user.
                      //TODO: Step 24 - Run the app and try to figure out what code you need to add to this file to make the story change when you press on the choice buttons.
                      setState(() {
                        storyBrain.nextStory(2);
                      });
                    },

 

 

 

THE END..

 

 

 

 

이상 섹션 11 학습을 완료했습니다.

댓글과 공감은 큰 힘이 됩니다. 감사합니다. !!

 

 

 

 

[다음강의]

https://youngest-programming.tistory.com/685

 

[Flutter] Udemy 플러터 강의 섹션 12 학습 (학습중....) (BMI Calculator - Building Flutter for intermediates)

[이전학습] https://youngest-programming.tistory.com/682 [Flutter] Udemy 플러터 강의 섹션 11 학습 (섹션 11: Boss Level Challenge 2 - Destini) [이전학습] https://youngest-programming.tistory.com/624..

youngest-programming.tistory.com

 

 

 

 

728x90
Comments