├── main.dart ├── .gitignore ├── pubspec.yaml ├── solutions ├── exercise_04.dart ├── exercise_03.dart ├── exercise_02.dart ├── exercise_01.dart ├── exercise_07.dart ├── exercise_06.dart ├── exercise_13.dart ├── exercise_22.dart ├── exercise_14.dart ├── exercise_05.dart ├── exercise_11.dart ├── exercise_23.dart ├── exercise_10.dart ├── exercise_12.dart ├── exercise_26.dart ├── exercise_17.dart ├── exercise_19.dart ├── exercise_15.dart ├── exercise_09.dart ├── exercise_28.dart ├── exercise_08.dart ├── exercise_27.dart ├── exercise_16.dart ├── exercise_21.dart ├── exercise_24.dart ├── exercise_18.dart ├── exercise_25.dart └── exercise_20.dart ├── README.md └── birthdays.json /main.dart: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .dart_tool/* 2 | .packages 3 | pubspec.lock -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: Practice_Dart 2 | dependencies: 3 | intl: ^0.16.1 -------------------------------------------------------------------------------- /solutions/exercise_04.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | stdout.write("Please choose a number: "); 5 | int number = int.parse(stdin.readLineSync()); 6 | for (var i = 1; i <= number; i++) { 7 | if (number % i == 0) { 8 | print(i); 9 | } 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /solutions/exercise_03.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | List a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]; 3 | 4 | for (var i in a) { 5 | if (i < 5) { 6 | print(i); 7 | } 8 | } 9 | 10 | // One liner 11 | print([ 12 | for (var i in a) 13 | if (i < 5) i 14 | ]); 15 | } 16 | -------------------------------------------------------------------------------- /solutions/exercise_02.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | stdout.write("Hi, please choose a number: "); 5 | int number = int.parse(stdin.readLineSync()); 6 | 7 | if (number % 2 == 0) { 8 | print("Chosen number is even"); 9 | } else { 10 | print("Chosen number is odd"); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /solutions/exercise_01.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | stdout.write("What's your name? "); 5 | String name = stdin.readLineSync(); 6 | 7 | print("Hi, $name! What is your age?"); 8 | int age = int.parse(stdin.readLineSync()); 9 | 10 | int yearsToHunderd = 100 - age; 11 | print("$name, You have $yearsToHunderd years to be 100"); 12 | } 13 | -------------------------------------------------------------------------------- /solutions/exercise_07.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | List a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]; 3 | 4 | int i = 0; 5 | List l = []; 6 | 7 | for (var e in a) { 8 | if (++i % 2 == 0) { 9 | l.add(e); 10 | } 11 | } 12 | print(l); 13 | 14 | // One liner 15 | print([ 16 | for (var e in a) 17 | if (++i % 2 == 0) e 18 | ]); 19 | } 20 | -------------------------------------------------------------------------------- /solutions/exercise_06.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | stdout.write("Please give a word: "); 5 | String input = stdin.readLineSync().toLowerCase(); 6 | String revInput = input.split('').reversed.join(''); 7 | 8 | // Ternary operator 9 | input == revInput 10 | ? print("The word is palindrome") 11 | : print("The word is not a palindrome"); 12 | } 13 | -------------------------------------------------------------------------------- /solutions/exercise_13.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | void main() { 4 | final random = Random(); 5 | List randList = List.generate(10, (_) => random.nextInt(10)); 6 | 7 | print("Initial list is $randList\n"); 8 | print("Cleaned list is ${removeDuplicates(randList)}"); 9 | } 10 | 11 | List removeDuplicates(List initialList) { 12 | return initialList.toSet().toList(); 13 | } 14 | -------------------------------------------------------------------------------- /solutions/exercise_22.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | var max; 3 | int a = 32; 4 | int b = 12; 5 | int c = 64; 6 | 7 | if (a > b) { 8 | max = a; 9 | } else { 10 | max = b; 11 | } 12 | 13 | if (c > max) { 14 | max = c; 15 | } 16 | print(max); 17 | 18 | // Another method, which will work with any length 19 | List l = [a, b, c, 4, 5, 2, 1]; 20 | l.sort(); 21 | print(l.last); 22 | } 23 | -------------------------------------------------------------------------------- /solutions/exercise_14.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | stdout.write("Please give a sentence: "); 5 | String sentence = stdin.readLineSync(); 6 | 7 | reverseSentence(sentence); 8 | } 9 | 10 | void reverseSentence(String sentence) { 11 | /* Split the sentence into a list of words 12 | Reverse the list, then join the words back */ 13 | String a = sentence.split(" ").reversed.toList().join(" "); 14 | print(a); 15 | } 16 | -------------------------------------------------------------------------------- /solutions/exercise_05.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | List a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]; 3 | List b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 89]; 4 | Set c = {}; 5 | 6 | for (var i in a) { 7 | for (var j in b) { 8 | if (i == j) { 9 | c.add(i); 10 | } 11 | } 12 | } 13 | print(c.toList()); 14 | 15 | // One liner using set intersections 16 | print(Set.from(a).intersection(Set.from(b)).toList()); 17 | } 18 | -------------------------------------------------------------------------------- /solutions/exercise_11.dart: -------------------------------------------------------------------------------- 1 | import 'dart:math'; 2 | 3 | void main() { 4 | // Initialize the random list 5 | final random = Random(); 6 | List randList = List.generate(10, (_) => random.nextInt(100)); 7 | 8 | // Pass it to the function 9 | print(randList); 10 | print(newList(randList)); 11 | } 12 | 13 | // Function that returns the first and the last element of given list 14 | List newList(List initialList) { 15 | return [initialList.first, initialList.last]; 16 | } 17 | -------------------------------------------------------------------------------- /solutions/exercise_23.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | void main() { 5 | String word = randomWord("sowpods.txt"); 6 | print(word); 7 | } 8 | 9 | String randomWord(String txt) { 10 | /* 11 | Reads the given file as a list 12 | Then picks a random word from it 13 | */ 14 | final random = Random(); 15 | var file = File(txt); 16 | List wordList = file.readAsLinesSync(); 17 | String word = wordList[random.nextInt(wordList.length)]; 18 | return word; 19 | } 20 | -------------------------------------------------------------------------------- /solutions/exercise_10.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | stdout.write("Please give us a number: "); 5 | int chosenNumber = int.parse(stdin.readLineSync()); 6 | 7 | checkPrime(chosenNumber); 8 | } 9 | 10 | void checkPrime(int number) { 11 | // List comprehensions 12 | List a = [ 13 | for (var i = 1; i <= number; i++) 14 | if (number % i == 0) i 15 | ]; 16 | 17 | // Check for prime 18 | a.length == 2 19 | ? print("The chosen number is a prime") 20 | : print("The chosen number is not a prime"); 21 | } 22 | -------------------------------------------------------------------------------- /solutions/exercise_12.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | stdout.write("How many Fibonacci numbers do you want? "); 5 | int chosenNumber = int.parse(stdin.readLineSync()); 6 | 7 | List result = fibonacciNumbers(chosenNumber); 8 | print(result); 9 | } 10 | 11 | // Function to calulcate the Fibonacci numbers 12 | List fibonacciNumbers(int chosenNumber) { 13 | List fibList = [1, 1]; 14 | 15 | for (var i = 0; i < chosenNumber; i++) { 16 | fibList.add(fibList[i] + fibList[i + 1]); 17 | } 18 | return fibList; 19 | } 20 | -------------------------------------------------------------------------------- /solutions/exercise_26.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | // Map of birthdays of people 5 | Map birthdays = { 6 | "Albert Einstein": "14/03/1879", 7 | "Benjamin Franklin": "17/01/1706", 8 | "Ada Lovlace": "10/12/1815", 9 | }; 10 | 11 | print("\nHello there!. We know the birthdays of the following people: \n"); 12 | 13 | birthdays.forEach((key, value) { 14 | print(key); 15 | }); 16 | 17 | stdout.write("\nWho's birthday do you want to know? "); 18 | String choice = stdin.readLineSync(); 19 | 20 | print("\n$choice's birthday is ${birthdays[choice]}\n"); 21 | } 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Practice Dart 2 | 3 | Credits go to Michele Pratusevich, who is the author of [**Practice Python**](https://www.practicepython.org). 4 | 5 | All the exercises are adopted from there. The exercises that are too Python specific are omitted. 6 | 7 | New exercises will be added over time. 8 | 9 | Solutions are given in [Dart language](https://dart.dev/guides/language/language-tour), and confirmed to be working in version 2.9.0 of the SDK on Windows 10, as well as on [Repl.it](https://repl.it). 10 | 11 | - [Language tour of Dart](https://dart.dev/guides/language/language-tour) 12 | - [Markdown version with solutions](https://hackmd.io/@kuzmapetrovich/S1x90jWGP) -------------------------------------------------------------------------------- /solutions/exercise_17.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | stdout.write("What square size do you want: "); 5 | int userChoice = int.parse(stdin.readLineSync()); 6 | print("Here is a $userChoice by $userChoice board: \n"); 7 | 8 | drawBoard(userChoice); 9 | } 10 | 11 | void drawBoard(int squareSize) { 12 | // Basic building blocks 13 | String rowLines = " ---"; 14 | String colLines = "| "; 15 | 16 | // For loop for drawing the board 17 | for (var i = 0; i < squareSize; i++) { 18 | print(rowLines * squareSize); 19 | print(colLines * (squareSize + 1)); 20 | } 21 | 22 | // Add the last line to the board 23 | print("${rowLines * squareSize}\n"); 24 | } 25 | -------------------------------------------------------------------------------- /solutions/exercise_19.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | // Empty board 5 | List> initialBoard = 6 | List.generate(3, (_) => List.generate(3, (_) => ' ')); 7 | drawBoard(initialBoard, 2); 8 | } 9 | 10 | void drawBoard(List> board, int currentUser) { 11 | /* 12 | Takes an initial board and populates it 13 | either with X or with O depending on 14 | the currentUser and their choice 15 | */ 16 | var move; 17 | currentUser == 1 ? move = 'X' : move = 'O'; 18 | 19 | stdout.write("Please choose a coordinate: "); 20 | List choice = stdin.readLineSync().split(" "); 21 | board[int.parse(choice[0])][int.parse(choice[1])] = move; 22 | print(board); 23 | } 24 | -------------------------------------------------------------------------------- /birthdays.json: -------------------------------------------------------------------------------- 1 | { 2 | "Albert Einstein": "14/03/1879", 3 | "Benjamin Franklin": "17/01/1706", 4 | "Ada Lovelace": "10/12/1815", 5 | "Isaac Newton": "25/12/1642", 6 | "Paul Dirac": "08/08/1902", 7 | "Marie Curie": "07/11/1867", 8 | "Galileo Galilei": "15/02/1564", 9 | "Murray Gell-Mann": "15/09/1929", 10 | "Stephen Hawking": "08/01/1942", 11 | "Werner Heisenberg": "05/12/1901", 12 | "Alfred Nobel": "21/10/1833", 13 | "Carl Sagan": "09/11/1934", 14 | "John Nash": "13/06/1928", 15 | "Henry Cavendish": "10/10/1731", 16 | "Dmitri Mendeleev": "08/02/1834", 17 | "Leonhard Euler": "15/04/1707", 18 | "Max Planck": "23/04/1858", 19 | "Niels Bohr": "07/10/1885" 20 | } -------------------------------------------------------------------------------- /solutions/exercise_15.dart: -------------------------------------------------------------------------------- 1 | import 'dart:convert'; 2 | import 'dart:io'; 3 | import 'dart:math'; 4 | 5 | void main() { 6 | stdout.write("How strong a password do you want? Weak, Medium or Strong: "); 7 | String choice = stdin.readLineSync().toLowerCase(); 8 | 9 | passwordGenerator(choice); 10 | } 11 | 12 | // Create a random sequence of characters 13 | void shuffleGenerator(int strength) { 14 | final random = Random.secure(); 15 | List intList = List.generate(strength, (_) => random.nextInt(255)); 16 | List charList = base64UrlEncode(intList).split('').toList(); 17 | charList.shuffle(); 18 | print("\nYour password is: ${charList.join('')}\n"); 19 | } 20 | 21 | void passwordGenerator(String strength) { 22 | if (strength == "weak") { 23 | shuffleGenerator(5); 24 | } else if (strength == "medium") { 25 | shuffleGenerator(15); 26 | } else if (strength == "strong") { 27 | shuffleGenerator(25); 28 | } else { 29 | print("Incorrect word is given"); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /solutions/exercise_09.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | void main() { 5 | print("Type exit to quit the game"); 6 | guessingGame(); 7 | } 8 | 9 | guessingGame() { 10 | final random = Random(); 11 | int randNumber = random.nextInt(100); 12 | int attempt = 0; 13 | 14 | while (true) { 15 | attempt += 1; 16 | stdout.write("Please choose a number between 0 and 100: "); 17 | String chosenNumber = stdin.readLineSync(); 18 | 19 | // Make sure user does not go out of limits 20 | if (chosenNumber.toLowerCase() == "exit") { 21 | print("\nBye"); 22 | break; 23 | } else if (int.parse(chosenNumber) > 100) { 24 | print("Please do not go over 100"); 25 | continue; 26 | } 27 | 28 | // Main logic 29 | if (int.parse(chosenNumber) == randNumber) { 30 | print("Bingo! You tried $attempt times\n"); 31 | continue; 32 | } else if (int.parse(chosenNumber) > randNumber) { 33 | print("You are higher"); 34 | continue; 35 | } else { 36 | print("You are lower"); 37 | continue; 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /solutions/exercise_28.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:convert'; 3 | import 'package:intl/intl.dart'; 4 | 5 | void main() { 6 | // Read the Json file 7 | File file = File("../birthdays.json"); 8 | Map data = json.decode(file.readAsStringSync()); 9 | 10 | // Extract the months to a list 11 | DateFormat extractor = DateFormat("MMMM"); 12 | List months = [ 13 | for (var d in data.values) extractor.format(formatter(d)) 14 | ]; 15 | 16 | // Count the occurance of each month 17 | counter(months); 18 | } 19 | 20 | DateTime formatter(String birthday) { 21 | /* 22 | Takes a string and returns a Datetime object 23 | */ 24 | return DateFormat("dd/MM/yyyy").parse(birthday); 25 | } 26 | 27 | void counter(List m) { 28 | /* 29 | Takes a lits of months and counts their occurances 30 | Saves them to a map and prints the results 31 | */ 32 | Map occurances = {}; 33 | 34 | m.forEach((e) { 35 | if (!occurances.containsKey(e)) { 36 | occurances[e] = 1; 37 | } else { 38 | occurances[e] += 1; 39 | } 40 | }); 41 | 42 | print("\nHere are the counts:\n"); 43 | occurances.forEach((key, value) { 44 | print("$key: $value"); 45 | }); 46 | } 47 | -------------------------------------------------------------------------------- /solutions/exercise_08.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | void main() { 5 | print("Welcome to Rock, Paper, Scissors\nType 'exit' to stop the game"); 6 | final random = Random(); 7 | 8 | // Rules of the game 9 | Map rules = { 10 | "rock": "scissors", 11 | "scissors": "paper", 12 | "paper": "rock" 13 | }; 14 | 15 | // Initial score 16 | int user = 0; 17 | int comp = 0; 18 | 19 | // Options for computer to choose 20 | List options = ["rock", "paper", "scissors"]; 21 | 22 | // Actual game 23 | while (true) { 24 | String compChoice = options[random.nextInt(options.length)]; 25 | stdout.write("\nPlease choose Rock, Paper or Scissors: "); 26 | String userChoice = stdin.readLineSync().toLowerCase(); 27 | 28 | if (userChoice == "exit") { 29 | print("\nYou: $user Computer: $comp\nBye Bye!"); 30 | break; 31 | } 32 | 33 | if (!options.contains(userChoice)) { 34 | print("Incorrect choice"); 35 | continue; 36 | } else if (compChoice == userChoice) { 37 | print("We have a tie!"); 38 | } else if (rules[compChoice] == userChoice) { 39 | print("Computer wins: $compChoice vs $userChoice"); 40 | comp += 1; 41 | } else if (rules[userChoice] == compChoice) { 42 | print("You win: $userChoice vs $compChoice"); 43 | user += 1; 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /solutions/exercise_27.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:convert'; 3 | 4 | void main() { 5 | birthdays("../birthdays.json"); 6 | } 7 | 8 | void birthdays(String txt) { 9 | // Read the file and decode to Json 10 | var file = File(txt); 11 | Map data = json.decode(file.readAsStringSync()); 12 | 13 | // Current list of people 14 | print("\nHello there!. We know the birthdays of the following people: \n"); 15 | data.forEach((key, value) { 16 | print(key); 17 | }); 18 | 19 | // User interaction 20 | stdout.write("\nWho's birthday do you want to know? "); 21 | String choice = stdin.readLineSync(); 22 | print("\n$choice's birthday is ${data[choice]}\n"); 23 | 24 | stdout.write("\nWould you like to add more people's birthdays? "); 25 | String answer = stdin.readLineSync().toLowerCase(); 26 | 27 | // Update the file 28 | if (answer == "yes") { 29 | stdout.write("Give us a name: "); 30 | String name = stdin.readLineSync(); 31 | stdout.write("Give us their birthday (dd/mm/yyyy): "); 32 | String birthday = stdin.readLineSync(); 33 | 34 | data[name] = birthday; 35 | file.writeAsStringSync(json.encode(data)); 36 | 37 | print("\nThank you! We have more people now!\n"); 38 | 39 | data.forEach( 40 | (key, value) { 41 | print("$key: $value"); 42 | }, 43 | ); 44 | } else { 45 | print("\nOK. Bye bye!\n"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /solutions/exercise_16.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | void main() { 5 | /* Generate random number 6 | Range is between 1000 and 9999 */ 7 | final random = Random(); 8 | String randomNumber = (1000 + random.nextInt(9999 - 1000)).toString(); 9 | print(randomNumber); 10 | 11 | stdout.write("Welcome to Cows and Bulls\nType 'exit' to stop the game\n"); 12 | 13 | int attempts = 0; 14 | 15 | // Actual game 16 | while (true) { 17 | int cows = 0; 18 | int bulls = 0; 19 | attempts += 1; 20 | 21 | stdout.write("\nPlease choose a four digit number: "); 22 | String chosenNumber = stdin.readLineSync(); 23 | 24 | // Conditions to check if the game is over 25 | if (chosenNumber == randomNumber) { 26 | print("Bullseye! You took $attempts attempts"); 27 | break; 28 | } else if (chosenNumber == "exit") { 29 | print("Bye bye!"); 30 | break; 31 | } else if (chosenNumber.length != randomNumber.length) { 32 | print("Incorrect number. Make sure to give 4 digit number"); 33 | continue; 34 | } 35 | 36 | /* If a digit is in the same index increase the cow 37 | If it is somewhere else increase the bull*/ 38 | for (var i = 0; i < randomNumber.length; i++) { 39 | if (chosenNumber[i] == randomNumber[i]) { 40 | cows += 1; 41 | } else if (randomNumber.contains(chosenNumber[i])) { 42 | bulls += 1; 43 | } 44 | } 45 | print("\nAttempts: $attempts \nCows: $cows, Bulls: $bulls"); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /solutions/exercise_21.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | void main() { 5 | print("""\n 6 | Hello boss. I am your laptop. 7 | Please, think of a number between 0 and 100. 8 | I will try to guess it and blow your mind. 9 | 10 | If my guess is too low, type "low". If I am too high, type "high". 11 | If I guess your number correctly, type "yes". 12 | """); 13 | 14 | compGuess(); 15 | } 16 | 17 | void compGuess() { 18 | /* 19 | Generates a list from 0 to 100 20 | Picks a random number from it 21 | Asks the user if the guess is correct 22 | If low, removes the lower numbers from the list 23 | If high, removes the higher numbers from the list 24 | Keeps repeating it until it guesses correctly 25 | */ 26 | 27 | final random = Random(); 28 | List numList = List.generate(101, (i) => i); 29 | int guess = numList[random.nextInt(numList.length)]; 30 | int count = 0; 31 | 32 | while (true) { 33 | count += 1; 34 | 35 | stdout.write("\nIs $guess your number? "); 36 | String response = stdin.readLineSync().toLowerCase(); 37 | 38 | if (response == "yes") { 39 | print("\nI got it! Attempts: $count\n"); 40 | break; 41 | } else if (response == "low") { 42 | numList = numList.where((e) => e > guess).toList(); 43 | guess = numList[random.nextInt(numList.length)]; 44 | } else if (response == "high") { 45 | numList = numList.where((e) => e < guess).toList(); 46 | guess = numList[random.nextInt(numList.length)]; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /solutions/exercise_24.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | // Pick a random word 5 | String randomWord = "EVAPORATE"; 6 | hangman(randomWord); 7 | } 8 | 9 | void hangman(String word) { 10 | /* 11 | Takes the word and create a clue 12 | Ask the user to guess a letter 13 | Check if the letter is in the word 14 | If yes, put the letter in the same index of the clue 15 | */ 16 | 17 | List clue = ("___ " * word.length).split(" "); 18 | 19 | // Initial state 20 | print(clue.join(" ")); 21 | int count = 0; 22 | 23 | // Game 24 | while (true) { 25 | // User input 26 | count += 1; 27 | stdout.write("\nPlease guess a letter: "); 28 | String choice = stdin.readLineSync().toUpperCase(); 29 | 30 | /* 31 | Allow user to type the whole word or exit the game 32 | Any other incorrect case, demand a single letter */ 33 | if (choice == word) { 34 | print("\nBingo! Attemps: $count"); 35 | break; 36 | } else if (choice == "EXIT") { 37 | print("\nBye bye!\n"); 38 | break; 39 | } else if (choice.length > 1) { 40 | print("\nNope!"); 41 | continue; 42 | } 43 | 44 | // Check the word for guessed letter 45 | for (var i = 0; i < word.length; i++) { 46 | if (clue[i] == choice) { 47 | continue; 48 | } else if (word[i] == choice) { 49 | clue[i] = choice; 50 | } 51 | } 52 | 53 | // Current state 54 | print(clue.join(" ")); 55 | 56 | // End the game if there are no more guesses 57 | if (clue.join("") == word) { 58 | print("\nBingo! Attemps:$count\n"); 59 | break; 60 | } 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /solutions/exercise_18.dart: -------------------------------------------------------------------------------- 1 | void main() { 2 | List> finalBoard = [ 3 | [1, 0, 0], 4 | [0, 1, 0], 5 | [2, 1, 0] 6 | ]; 7 | 8 | theGame(finalBoard); 9 | } 10 | 11 | void theGame(List> board) { 12 | /* 13 | Accepts: list of list of integers 14 | Does: first checks the rows, then columns then diagonals 15 | and prints the results if conditions are met 16 | Returns: nothing 17 | */ 18 | if (rowCheck(board)) { 19 | print("Row wins"); 20 | } else if (rowCheck(transpose(board))) { 21 | print("Column wins"); 22 | } else if (rowCheck(diagonals(board))) { 23 | print("Diagonal wins"); 24 | } else { 25 | print("Draw!"); 26 | } 27 | } 28 | 29 | bool rowCheck(List> board) { 30 | /* 31 | Accepts: list of lists of integers 32 | Does: checks if any row consists of the same values 33 | Returns: true if any, false otherwise 34 | */ 35 | for (List row in board) { 36 | if (row.toSet().length == 1) { 37 | return true; 38 | } 39 | } 40 | return false; 41 | } 42 | 43 | List> transpose(List> board) { 44 | /* 45 | Accepts: list of lists of integers 46 | Does: transposes it so each row becomes a column 47 | Returns: the transposed list of lists 48 | */ 49 | return [ 50 | for (var i = 0; i < board.length; i++) [for (List r in board) r[i]] 51 | ]; 52 | } 53 | 54 | List> diagonals(List> board) { 55 | /* 56 | Accepts: list of list of integers 57 | Does: takes both diagonals and adds them to a new list 58 | Returns: new list of lists 59 | 60 | Left-to-right diagonal is fairly easy. 61 | To take the right-to-left diagonal, first we reverse the each row 62 | then take left-to-right diagonal one more time 63 | */ 64 | return [ 65 | [for (var i = 0; i < board.length; i++) board[i][i]], 66 | [for (var i = 0; i < board.length; i++) board[i].reversed.toList()[i]] 67 | ]; 68 | } 69 | -------------------------------------------------------------------------------- /solutions/exercise_25.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | import 'dart:math'; 3 | 4 | void main() { 5 | // Pick a random word 6 | String theWord = randomWord("../sowpods.txt"); 7 | 8 | intro(); 9 | hangman(theWord); 10 | } 11 | 12 | void hangman(String word) { 13 | /* 14 | Takes the word and create a clue 15 | Ask the user to guess a letter 16 | Check if the letter is in the word 17 | If yes, put the letter in the same index of the clue 18 | */ 19 | 20 | List clue = ("___ " * word.length).split(" "); 21 | 22 | // Initial state 23 | print(clue.join(" ")); 24 | int count = 0; 25 | int attempts = word.length + 1; 26 | List history = []; 27 | 28 | // Game 29 | while (true) { 30 | count += 1; 31 | attempts -= 1; 32 | 33 | // User input 34 | stdout.write("\nPlease guess a letter: "); 35 | String choice = stdin.readLineSync().toUpperCase(); 36 | if (history.contains(choice)) { 37 | print("\nYou already tried this letter!"); 38 | attempts += 1; 39 | } else { 40 | history.add(choice); 41 | } 42 | 43 | /* 44 | Allow user to type the whole word or exit the game 45 | Any other incorrect case, demand a single letter */ 46 | if (choice == word) { 47 | print("\nBingo! Attemps: $count"); 48 | break; 49 | } else if (choice == "EXIT") { 50 | print("\nBye bye!\n"); 51 | break; 52 | } else if (choice.length > 1) { 53 | attempts += 1; 54 | print("\nNope! Attemps left: $attempts"); 55 | continue; 56 | } else if (attempts < 1) { 57 | print("\nAttemps left: $attempts. \nGame over!"); 58 | print("\nThe word was: $word"); 59 | break; 60 | } 61 | 62 | // Check the word for guessed letter 63 | for (var i = 0; i < word.length; i++) { 64 | if (word[i] == choice) { 65 | clue[i] = choice; 66 | } 67 | } 68 | print("\nAttempts left: $attempts"); 69 | 70 | // Current state 71 | print(clue.join(" ")); 72 | 73 | // End the game if there are no more guesses 74 | if (clue.join("") == word) { 75 | print("\nBingo! Attemps:$count\n"); 76 | break; 77 | } 78 | } 79 | } 80 | 81 | String randomWord(String txt) { 82 | /* 83 | Reads the given file as a list 84 | Then picks a random word from it 85 | */ 86 | final random = Random(); 87 | var file = File(txt); 88 | List wordList = file.readAsLinesSync(); 89 | String word = wordList[random.nextInt(wordList.length)]; 90 | return word; 91 | } 92 | 93 | void intro() { 94 | print("""\n 95 | Welcome to Hangman! 96 | We prepared a word for you. 97 | You have 6 attempts to guess it correctly 98 | You can type the whole word anytime before attempts are over 99 | To quit the game type "exit" 100 | """); 101 | } 102 | -------------------------------------------------------------------------------- /solutions/exercise_20.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | void main() { 4 | // Empty board 5 | List> theBoard = 6 | List.generate(3, (_) => List.generate(3, (_) => ' ')); 7 | 8 | // Print out the rules and instructions 9 | startGame(theBoard); 10 | 11 | // Alternate between users: 1 or 2 12 | int a = 1, user = 2, tmp; 13 | 14 | while (true) { 15 | // Establish the current user 16 | tmp = a; 17 | a = user; 18 | user = tmp; 19 | currentBoard(theBoard); 20 | 21 | // Ask for coordinates 22 | stdout.write("Please User $user, choose a coordinate: "); 23 | List userChoice = stdin.readLineSync().split(" "); 24 | if (userChoice.join(" ") == "exit") { 25 | print("\nGame quitted in the following state: "); 26 | break; 27 | } 28 | 29 | // Populate the board with the choice 30 | theBoard = makeMove(theBoard, user, userChoice); 31 | 32 | // Check the game 33 | if (rowCheck(theBoard)) { 34 | print("\nUser $user: Row win!"); 35 | break; 36 | } else if (rowCheck(transpose(theBoard))) { 37 | print("\nUser $user: Column win!"); 38 | break; 39 | } else if (rowCheck(diagonals(theBoard))) { 40 | print("\nUser $user: Diagonal win!"); 41 | break; 42 | } else if (drawGame(theBoard) == 1) { 43 | print("\nThe game ended in draw!"); 44 | break; 45 | } 46 | } 47 | 48 | // Current state of the game 49 | currentBoard(theBoard); 50 | } 51 | 52 | void startGame(List> board) { 53 | print("""\n 54 | Welcome to Tic Tac Toe! 55 | The game is for two users: User 1 (X) and User 2 (O). 56 | To make a move, give the coordinates of the board separated by space. 57 | For instance, 0 0 is the top left corner, 1 1 is the middle cell 58 | and 2 2 is the bottom right corner and so on. 59 | If you want to quite the game, type exit. 60 | """); 61 | } 62 | 63 | void currentBoard(List> board) { 64 | /* 65 | Draws the current board 66 | Rows and borders are hard coded 67 | Feel free to reimplement them with for loops 68 | But for exercise purposes it suffices 69 | */ 70 | String row1 = "| ${board[0][0]} | ${board[0][1]} | ${board[0][2]} |"; 71 | String row2 = "| ${board[1][0]} | ${board[1][1]} | ${board[1][2]} |"; 72 | String row3 = "| ${board[2][0]} | ${board[2][1]} | ${board[2][2]} |"; 73 | String border = "\n --- --- ---\n"; 74 | 75 | print(border + row1 + border + row2 + border + row3 + border); 76 | } 77 | 78 | List> makeMove( 79 | List> board, int currentUser, List choice) { 80 | /* 81 | Takes an initial board and populates it 82 | either with X or with O depending on 83 | the currentUser 84 | */ 85 | var move; 86 | currentUser == 1 ? move = 'X' : move = 'O'; 87 | 88 | board[int.parse(choice[0])][int.parse(choice[1])] = move; 89 | return board; 90 | } 91 | 92 | bool rowCheck(List> board) { 93 | /* 94 | Accepts: list of lists of ints 95 | Does: checks if any row consists of the same values 96 | Returns: true if any, false otherwise 97 | */ 98 | for (List row in board) { 99 | if (row.toSet().length == 1 && row.any((e) => e != ' ')) { 100 | return true; 101 | } 102 | } 103 | return false; 104 | } 105 | 106 | List> transpose(List> board) { 107 | /* 108 | Accepts: list of lists of integers 109 | Does: transposes it so each row becomes a column 110 | Returns: the transposed list of lists 111 | */ 112 | return [ 113 | for (var i = 0; i < board.length; i++) [for (List r in board) r[i]] 114 | ]; 115 | } 116 | 117 | List> diagonals(List> board) { 118 | /* 119 | Accepts: list of list of integers 120 | Does: takes both diagonals and adds them to a new list 121 | Returns: new list of lists 122 | 123 | Left-to-right diagonal is fairly easy. 124 | To take the right-to-left diagonal, first we reverse the each row 125 | then take left-to-right diagonal one more time 126 | */ 127 | return [ 128 | [for (var i = 0; i < board.length; i++) board[i][i]], 129 | [for (var i = 0; i < board.length; i++) board[i].reversed.toList()[i]] 130 | ]; 131 | } 132 | 133 | int drawGame(List> board) { 134 | /* 135 | Counts the number of empty cells in the board 136 | If the count is 1 and game has not ended 137 | it means the game is a draw 138 | */ 139 | int count = 0; 140 | for (var row in board) { 141 | for (var e in row) { 142 | if (e == " ") { 143 | count += 1; 144 | } 145 | } 146 | } 147 | return count; 148 | } 149 | --------------------------------------------------------------------------------