Xamarin.Android - Flags Quiz Game App - Part Two

Introduction

In this game, you will be able to recognize the flags of countries like Switzerland, South Korea, Panama, The Netherlands, Portugal and India.

Game Features

  1. Question about flags of all countries in the world
  2. Time Limit: 5 seconds per question
  3. Mode: Easy, Medium, Hard, Hardest
  4. Database: SQLit
  5. Score: Highest and lowest score based Medals

Prerequisite

  1. Flag Images
  2. Medals Images
  3. SQLite DB file
Project Folder Structure

 

Create Xamarin Android Application

Step 1

You can create a new Xamarin.Android app by going to File ->>Visual C#-> Android-> Blank app. Give it a name like, FlagQuiz.
 
 

Step 2

Open Solution Explorer-> Project Name -> Resources Right click add a new folder give it a name like, Raw and paste your database file in to it.

(FolderName: Raw)

(FileName: MyDB)

 

Step 3

Open Solution Explorer -> Project Name -> Resources-> Drawable. All countries' flag images and medal images paste into drawable folder.

 

Step 4

Next, go to Solution Explorer-> Project Name and right-click. Select Add -> New Item-> Class. Give it a name like, Common.cs and write the following code.

C# Code

  1. namespace FlagQuiz.Common {  
  2.     public class Common {  
  3.         public  
  4.         const int EASY_MODE_NUM = 30;  
  5.         public  
  6.         const int MEDIUM_MODE_NUM = 50;  
  7.         public  
  8.         const int HARD_MODE_NUM = 100;  
  9.         public  
  10.         const int HARDEST_MODE_NUM = 200;  
  11.         public enum MODE {  
  12.             EASY,  
  13.             MEDIUM,  
  14.             HARD,  
  15.             HARDEST  
  16.         }  
  17.     }  
  18. }  

Step 5

Next, add a Question class, go to Solution Explorer-> Project Name and right-click. Select Add -> New Item-> Class. Give it a name like, Question.cs and write the following code.

C# Code

  1. namespace FlagQuizGame.Model {  
  2.     public class Question {  
  3.         public int Id {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         public string Image {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public string AnswerA {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string AnswerB {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         public string AnswerC {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         public string AnswerD {  
  24.             get;  
  25.             set;  
  26.         }  
  27.         public string CorrectAnswer {  
  28.             get;  
  29.             set;  
  30.         }  
  31.         public Question(int Id, string Image, string AnswerA, string AnswerB, string AnswerC, string AnswerD, string CorrectAnswer) {  
  32.             this.Id = Id;  
  33.             this.Image = Image;  
  34.             this.AnswerA = AnswerA;  
  35.             this.AnswerB = AnswerB;  
  36.             this.AnswerC = AnswerC;  
  37.             this.AnswerD = AnswerD;  
  38.             this.CorrectAnswer = CorrectAnswer;  
  39.         }  
  40.     }  
  41. }  

Step 6

Next, add a Ranking class, go to Solution Explorer-> Project Name and right-click. Select Add -> New Item-> Class. Give it a name like, Ranking.cs and write the following code.

C# Code

  1. namespace FlagQuizGame.Model {  
  2.     public class Ranking {  
  3.         public int Id {  
  4.             get;  
  5.             set;  
  6.         }  
  7.         public double Score {  
  8.             get;  
  9.             set;  
  10.         }  
  11.         public Ranking(int Id, double Score) {  
  12.             this.Id = Id;  
  13.             this.Score = Score;  
  14.         }  
  15.     }  
  16. }  

Step 7

Similarly, create a new class, go to Solution Explorer-> Project Name and right-click. Select Add -> New Item-> Class. Give it a name like, DbHelper.cs and write the following code with appropriate namespaces.

C# Code

  1. using Android.Content;  
  2. using Android.Database;  
  3. using Android.Database.Sqlite;  
  4. using FlagQuizGame.Model;  
  5. using System;  
  6. using System.Collections.Generic;  
  7. using System.IO;  
  8. namespace FlagQuizGame.DbHelper {  
  9.     public class DbHelper: SQLiteOpenHelper {  
  10.         private static string DB_PATH = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);  
  11.         private static string DB_NAME = "MyDB.db";  
  12.         private static int VERSION = 1;  
  13.         private Context context;  
  14.         public DbHelper(Context context): base(context, DB_NAME, null, VERSION) {  
  15.             this.context = context;  
  16.         }  
  17.         private string GetSQLitePath() {  
  18.             return Path.Combine(DB_PATH, DB_NAME);  
  19.         }  
  20.         public override SQLiteDatabase WritableDatabase {  
  21.             get {  
  22.                 return CreateSQLiteDB();  
  23.             }  
  24.         }  
  25.         private SQLiteDatabase CreateSQLiteDB() {  
  26.             SQLiteDatabase sqliteDB = null;  
  27.             string path = GetSQLitePath();  
  28.             Stream streamSQLite = null;  
  29.             FileStream streamWriter = null;  
  30.             Boolean isSQLiteInit = false;  
  31.             try {  
  32.                 if (File.Exists(path)) isSQLiteInit = true;  
  33.                 else {  
  34.                     streamSQLite = context.Resources.OpenRawResource(Resource.Raw.MyDB);  
  35.                     streamWriter = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);  
  36.                     if (streamSQLite != null && streamWriter != null) {  
  37.                         if (CopySQLiteDB(streamSQLite, streamWriter)) isSQLiteInit = true;  
  38.                     }  
  39.                 }  
  40.                 if (isSQLiteInit) sqliteDB = SQLiteDatabase.OpenDatabase(path, null, DatabaseOpenFlags.OpenReadwrite);  
  41.             } catch {}  
  42.             return sqliteDB;  
  43.         }  
  44.         private bool CopySQLiteDB(Stream streamSQLite, FileStream streamWriter) {  
  45.             bool isSuccess = false;  
  46.             int length = 1024;  
  47.             Byte[] buffer = new Byte[length];  
  48.             try {  
  49.                 int bytesRead = streamSQLite.Read(buffer, 0, length);  
  50.                 while (bytesRead > 0) {  
  51.                     streamWriter.Write(buffer, 0, bytesRead);  
  52.                     bytesRead = streamSQLite.Read(buffer, 0, length);  
  53.                 }  
  54.                 isSuccess = true;  
  55.             } catch {} finally {  
  56.                 streamWriter.Close();  
  57.                 streamSQLite.Close();  
  58.             }  
  59.             return isSuccess;  
  60.         }  
  61.         public override void OnCreate(SQLiteDatabase db) {}  
  62.         public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}  
  63.         public void InsertScore(double score) {  
  64.             String query = $ "INSERT INTO Ranking(Score) VALUES({score})";  
  65.             SQLiteDatabase db = this.WritableDatabase;  
  66.             db.ExecSQL(query);  
  67.         }  
  68.         public List < Ranking > GetRanking() {  
  69.             List < Ranking > lstRanking = new List < Ranking > ();  
  70.             SQLiteDatabase db = this.WritableDatabase;  
  71.             ICursor c;  
  72.             try {  
  73.                 c = db.RawQuery($ "SELECT * FROM Ranking ORDER BY Score"null);  
  74.                 if (c == null) {  
  75.                     return null;  
  76.                 } else {  
  77.                     c.MoveToNext();  
  78.                 }  
  79.                 do {  
  80.                     int Id = c.GetInt(c.GetColumnIndex("Id"));  
  81.                     double Score = c.GetDouble(c.GetColumnIndex("Score"));  
  82.                     Ranking ranking = new Ranking(Id, Score);  
  83.                     lstRanking.Add(ranking);  
  84.                 }  
  85.                 while (c.MoveToNext());  
  86.                 c.Close();  
  87.             } catch {}  
  88.             db.Close();  
  89.             return lstRanking;  
  90.         }  
  91.         public List < Question > GetQuestionMode(string mode) {  
  92.             List < Question > lstQuestion = new List < Question > ();  
  93.             SQLiteDatabase db = this.WritableDatabase;  
  94.             ICursor c;  
  95.             int limit = 0;  
  96.             if (mode.Equals(Common.Common.MODE.EASY.ToString())) limit = Common.Common.EASY_MODE_NUM;  
  97.             else if (mode.Equals(Common.Common.MODE.MEDIUM.ToString())) limit = Common.Common.MEDIUM_MODE_NUM;  
  98.             else if (mode.Equals(Common.Common.MODE.HARD.ToString())) limit = Common.Common.HARD_MODE_NUM;  
  99.             else limit = Common.Common.HARDEST_MODE_NUM;  
  100.             try {  
  101.                 c = db.RawQuery($ "SELECT * FROM Question ORDER BY Random() LIMIT {limit}"null);  
  102.                 if (c == nullreturn null;  
  103.                 c.MoveToFirst();  
  104.                 do {  
  105.                     int Id = c.GetInt(c.GetColumnIndex("ID"));  
  106.                     string Image = c.GetString(c.GetColumnIndex("Image"));  
  107.                     string AnswerA = c.GetString(c.GetColumnIndex("AnswerA"));  
  108.                     string AnswerB = c.GetString(c.GetColumnIndex("AnswerB"));  
  109.                     string AnswerC = c.GetString(c.GetColumnIndex("AnswerC"));  
  110.                     string AnswerD = c.GetString(c.GetColumnIndex("AnswerD"));  
  111.                     string CorrectAnswer = c.GetString(c.GetColumnIndex("CorrectAnswer"));  
  112.                     Question question = new Question(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);  
  113.                     lstQuestion.Add(question);  
  114.                 }  
  115.                 while (c.MoveToNext());  
  116.                 c.Close();  
  117.             } catch {}  
  118.             return lstQuestion;  
  119.         }  
  120.         //Updata 2.0  
  121.         public int GetPlayCount(int Level) {  
  122.             int result = 0;  
  123.             SQLiteDatabase db = this.WritableDatabase;  
  124.             ICursor c;  
  125.             try {  
  126.                 c = db.RawQuery($ "SELECT PlayCount FROM UserPlayCount WHERE Level={Level}"null);  
  127.                 if (c == nullreturn 0;  
  128.                 c.MoveToFirst();  
  129.                 do {  
  130.                     result = c.GetInt(c.GetColumnIndex("PlayCount"));  
  131.                 } while (c.MoveToNext());  
  132.                 c.Close();  
  133.             } catch (Exception e) {}  
  134.             return result;  
  135.         }  
  136.         public void UpdatePlayCount(int Level, int PlayCount) {  
  137.             string query = $ "UPDATE UserPlayCount SET PlayCount={PlayCount} WHERE Level={Level}";  
  138.             SQLiteDatabase db = this.WritableDatabase;  
  139.             db.ExecSQL(query);  
  140.         }  
  141.     }  
  142. }  

Step 8

Now, add a new xml file in drawable, open Solution Explorer-> Project Name-> Resources-> Drawable-> Right click to add a new Item give it a name like, round_corner.xml and add the following code.

(File Name: round_corner.xml)

(Folder Name: Drawable)

XML Code

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <shape xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <solid android:color="#FFFFFF" />  
  4.     <strok android:width="1dip" android:color="#1e1e1e" />  
  5.     <corners android:radius="10dip" />  
  6.     <padding android:left="0dip" android:right="0dip" android:bottom="0dip" android:top="0dip" />  
  7. </shape>  

Step 9

Next, add another xml file, open Solution Explorer-> Project Name-> Resources-> Drawable-> Right click to add a new Item give it a name like, button_border.xml and add the following code.

(File Name: button_border.xml )

(Folder Name: Drawable)

XML Code

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <layer-list xmlns:android="http://schemas.android.com/apk/res/android">  
  3.     <item android:bottom="-2dp" android:top="-2dp" android:right="-2dp" android:left="-2dp">  
  4.         <shape android:shape="rectangle">  
  5.             <strok android:width="1dp" android:color="#004d40" />  
  6.             <solid android:color="#00FFFFFF" /> </shape>  
  7.     </item>  
  8. </layer-list>  

Step 10

Next, add a xml file in values folder, open Solution Explorer-> Project Name-> Resources-> values-> Right click to add a new Item give it a name like, Styles.xml and add the following code.

(File Name: Styles.xml)

(Folder Name: values)

XML Code

  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <resources>  
  3.     <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">  
  4.         <item name="colorPrimary">#3F51B5</item><item name="colorPrimaryDark">#242E38</item><item name="colorAccent">#FF4081</item>  
  5.     </style>  
  6.     <style name="MyButton" parent="Theme.AppCompat.Light">  
  7.         <item name="colorControlHighlight">#1CB3BC</item>  
  8.     </style>  
  9. </resources>  

Step 11

Now, we need to add Android Support Library that is used for user Interface. Open Solution Explorer and go to Components -> Get More Components. In this way, you can move on Xamarin Components Store, then search for AppCompat and click "Add to App".

 
 
 

Step 12

Go to Solution Explorer-> Project Name-> Resources-> Layout-> Main.axml open main.axml file and add the following code.

The layout will have a ImageView in order to display the preview of flag image. I also added two buttons to check score and play game.

(FileName: Main.axml)

XAML Code

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="#242E38" android:layout_width="match_parent" android:layout_height="match_parent">  
  3.     <ImageView android:id="@+id/flag" android:layout_width="300dp" android:layout_height="200dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="25dp" android:background="@drawable/pakistan" android:gravity="center" />  
  4.     <RelativeLayout android:layout_below="@+id/flag" android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:layout_marginTop="30dp" android:padding="20dp" android:elevation="4dp" android:background="@drawable/round_corner" android:layout_width="match_parent" android:layout_height="wrap_content">  
  5.         <LinearLayout android:orientation="vertical" android:id="@+id/btnGroup" android:paddingTop="10dp" android:layout_width="match_parent" android:layout_height="wrap_content">  
  6.             <Button android:id="@+id/btnPlay" style="@style/Widget.AppCompat.Button.Borderless" android:layout_margin="8dp" android:background="#20B2AA" android:foreground="?android:attr/selectableItemBackground" android:text="Play" android:textColor="#FFFFFF" android:textStyle="bold" android:theme="@style/MyButton" android:layout_width="match_parent" android:layout_height="wrap_content" />  
  7.             <Button android:id="@+id/btnScore" style="@style/Widget.AppCompat.Button.Borderless" android:layout_margin="8dp" android:background="#228B22" android:foreground="?android:attr/selectableItemBackground" android:text="SCORE" android:textColor="#FFFFFF" android:textStyle="bold" android:theme="@style/MyButton" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>  
  8.         <LinearLayout android:layout_below="@+id/btnGroup" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content">  
  9.             <SeekBar android:id="@+id/seekBar" android:max="3" android:layout_width="300dp" android:layout_height="wrap_content" />  
  10.             <TextView android:id="@+id/txtMode" android:layout_gravity="center" android:text="EASY" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>  
  11.     </RelativeLayout>  
  12. </RelativeLayout>  
  

Step 13

Go to Solution Explorer-> Project Name-> MainActivity and add the following code to main activity and use appropriate namespaces.

(FileName: MainActivity)

C# Code

  1. using Android.App;  
  2. using Android.Widget;  
  3. using Android.OS;  
  4. using static Android.Widget.SeekBar;  
  5. using Android.Content;  
  6. using Android.Database.Sqlite;  
  7. using System;  
  8. namespace FlagQuizGame {  
  9.     [Activity(Label = "Flag Quiz Game", MainLauncher = true, Theme = "@style/Theme.AppCompat.Light.NoActionBar")]  
  10.     public class MainActivity: Activity, IOnSeekBarChangeListener {  
  11.         SeekBar seekBar;  
  12.         TextView txtMode;  
  13.         Button btnPlay, btnScore;  
  14.         DbHelper.DbHelper db;  
  15.         SQLiteDatabase sqLiteDB;  
  16.         protected override void OnCreate(Bundle savedInstanceState) {  
  17.             base.OnCreate(savedInstanceState);  
  18.             // Set our view from the "main" layout resource  
  19.             SetContentView(Resource.Layout.Main);  
  20.             db = new DbHelper.DbHelper(this);  
  21.             sqLiteDB = db.WritableDatabase;  
  22.             seekBar = FindViewById < SeekBar > (Resource.Id.seekBar);  
  23.             txtMode = FindViewById < TextView > (Resource.Id.txtMode);  
  24.             btnPlay = FindViewById < Button > (Resource.Id.btnPlay);  
  25.             btnScore = FindViewById < Button > (Resource.Id.btnScore);  
  26.             btnPlay.Click += delegate {  
  27.                 Intent intent = new Intent(thistypeof(Playing));  
  28.                 intent.PutExtra("MODE", getPlayMode());  
  29.                 StartActivity(intent);  
  30.                 Finish();  
  31.             };  
  32.             seekBar.SetOnSeekBarChangeListener(this);  
  33.             btnScore.Click += delegate {  
  34.                 Intent intent = new Intent(thistypeof(Score));  
  35.                 StartActivity(intent);  
  36.                 Finish();  
  37.             };  
  38.         }  
  39.         private String getPlayMode() {  
  40.             if (seekBar.Progress == 0) return Common.Common.MODE.EASY.ToString();  
  41.             else if (seekBar.Progress == 1) return Common.Common.MODE.MEDIUM.ToString();  
  42.             else if (seekBar.Progress == 2) return Common.Common.MODE.HARD.ToString();  
  43.             else return Common.Common.MODE.HARDEST.ToString();  
  44.         }  
  45.         public void OnProgressChanged(SeekBar seekBar, int progress, bool fromUser) {  
  46.             txtMode.Text = getPlayMode().ToUpper();  
  47.         }  
  48.         public void OnStartTrackingTouch(SeekBar seekBar) {}  
  49.         public void OnStopTrackingTouch(SeekBar seekBar) {}  
  50.     }  
  51. }  

Step 14

Similarly, add a new Layout, open Solution Explorer-> Project Name-> Resources-> Layout-> Right click add new item select Layout give it a name like, Playing.axml and add the following code.

The layout will have a ImageView in order to display the preview of flag image. I also added four buttons to select correct answer.

(FileName: Playing.axml)

XAML Code

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="#242E38" android:layout_width="match_parent" android:layout_height="match_parent">  
  3.     <ImageView android:id="@+id/question_flag" android:layout_width="300dp" android:layout_height="200dp" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="20dp" android:background="@drawable/pakistan" android:gravity="center" />  
  4.     <RelativeLayout android:layout_below="@+id/question_flag" android:layout_alignParentBottom="true" android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:layout_marginTop="20dp" android:elevation="4dp" android:background="@drawable/round_corner" android:layout_width="match_parent" android:layout_height="wrap_content">  
  5.         <LinearLayout android:orientation="vertical" android:id="@+id/btnGroup" android:paddingTop="10dp" android:layout_width="match_parent" android:layout_height="wrap_content">  
  6.             <LinearLayout android:weightSum="2" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content">  
  7.                 <TextView android:id="@+id/txtScore" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:background="@drawable/button_border" android:text="0" android:textSize="36sp" android:gravity="center" />  
  8.                 <TextView android:id="@+id/txtQuestion" android:layout_weight="1" android:layout_width="0dp" android:layout_height="wrap_content" android:background="@drawable/button_border" android:text=" 1/30" android:textSize="36sp" android:gravity="center" /> </LinearLayout>  
  9.             <ProgressBar style="@style/Widget.AppCompat.ProgressBar.Horizontal" android:id="@+id/progressBar" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:max="5" android:layout_width="match_parent" android:layout_height="wrap_content" />  
  10.             <Button android:id="@+id/btnAnswerA" style="@style/Widget.AppCompat.Button.Borderless" android:layout_margin="4dp" android:background="#228B22" android:foreground="?android:attr/selectableItemBackground" android:text="Answer" android:textColor="#FFFFFF" android:textStyle="bold" android:theme="@style/MyButton" android:layout_width="match_parent" android:layout_height="wrap_content" />  
  11.             <Button android:id="@+id/btnAnswerB" style="@style/Widget.AppCompat.Button.Borderless" android:layout_margin="4dp" android:background="#228B22" android:foreground="?android:attr/selectableItemBackground" android:text="Answer" android:textColor="#FFFFFF" android:textStyle="bold" android:theme="@style/MyButton" android:layout_width="match_parent" android:layout_height="wrap_content" />  
  12.             <Button android:id="@+id/btnAnswerC" style="@style/Widget.AppCompat.Button.Borderless" android:layout_margin="4dp" android:background="#228B22" android:foreground="?android:attr/selectableItemBackground" android:text="Answer" android:textColor="#FFFFFF" android:textStyle="bold" android:theme="@style/MyButton" android:layout_width="match_parent" android:layout_height="wrap_content" />  
  13.             <Button android:id="@+id/btnAnswerD" style="@style/Widget.AppCompat.Button.Borderless" android:layout_margin="4dp" android:background="#228B22" android:foreground="?android:attr/selectableItemBackground" android:text="Answer" android:textColor="#FFFFFF" android:textStyle="bold" android:theme="@style/MyButton" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>  
  14.     </RelativeLayout>  
  15. </RelativeLayout>  
     

Step 15

Add a new Activity, open Solution Explorer-> Project Name-> right click to add a new item select Activity give it a name like Playing and add the following code with appropriate namespaces.

(FileName: Playing)

C# Code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Android.App;  
  6. using Android.Content;  
  7. using Android.OS;  
  8. using Android.Runtime;  
  9. using Android.Views;  
  10. using Android.Widget;  
  11. using FlagQuizGame.Model;  
  12. using static Android.Views.View;  
  13. namespace FlagQuizGame {  
  14.     [Activity(Label = "Playing", Theme = "@style/Theme.AppCompat.Light.NoActionBar")]  
  15.     public class Playing: Activity, IOnClickListener {  
  16.         const long INTERVAL = 1000;  
  17.         const long TIMEOUT = 6000;  
  18.         public int progressValue = 0;  
  19.         static CountDown mCountDown;  
  20.         List < Question > questionPlay = new List < Question > ();  
  21.         DbHelper.DbHelper db;  
  22.         static int index, score, thisQuestion, totalQuestion, correctAnswer;  
  23.         String mode = String.Empty;  
  24.         //Control  
  25.         public ProgressBar progressBar;  
  26.         TextView txtScore, txtQuestion;  
  27.         Button btnA, btnB, btnC, btnD;  
  28.         ImageView imageView;  
  29.         protected override void OnCreate(Bundle savedInstanceState) {  
  30.             base.OnCreate(savedInstanceState);  
  31.             SetContentView(Resource.Layout.Playing);  
  32.             //Get data from Main Activity  
  33.             Bundle extra = Intent.Extras;  
  34.             if (extra != null) mode = extra.GetString("MODE");  
  35.             db = new DbHelper.DbHelper(this);  
  36.             txtScore = FindViewById < TextView > (Resource.Id.txtScore);  
  37.             txtQuestion = FindViewById < TextView > (Resource.Id.txtQuestion);  
  38.             progressBar = FindViewById < ProgressBar > (Resource.Id.progressBar);  
  39.             imageView = FindViewById < ImageView > (Resource.Id.question_flag);  
  40.             btnA = FindViewById < Button > (Resource.Id.btnAnswerA);  
  41.             btnB = FindViewById < Button > (Resource.Id.btnAnswerB);  
  42.             btnC = FindViewById < Button > (Resource.Id.btnAnswerC);  
  43.             btnD = FindViewById < Button > (Resource.Id.btnAnswerD);  
  44.             btnA.SetOnClickListener(this);  
  45.             btnB.SetOnClickListener(this);  
  46.             btnC.SetOnClickListener(this);  
  47.             btnD.SetOnClickListener(this);  
  48.         }  
  49.         public void OnClick(View v) {  
  50.             mCountDown.Cancel();  
  51.             if (index < totalQuestion) {  
  52.                 Button btnClicked = (Button) v;  
  53.                 if (btnClicked.Text.Equals(questionPlay[index].CorrectAnswer)) {  
  54.                     score += 10;  
  55.                     correctAnswer++;  
  56.                     ShowQuestion(++index);  
  57.                 } else ShowQuestion(++index);  
  58.             }  
  59.             txtScore.Text = $ "{score}";  
  60.         }  
  61.         public void ShowQuestion(int index) {  
  62.             if (index < totalQuestion) {  
  63.                 thisQuestion++;  
  64.                 txtQuestion.Text = $ "{thisQuestion}/{totalQuestion}";  
  65.                 progressBar.Progress = progressValue = 0;  
  66.                 int ImageID = this.Resources.GetIdentifier(questionPlay[index].Image.ToLower(), "drawable", PackageName);  
  67.                 imageView.SetBackgroundResource(ImageID);  
  68.                 btnA.Text = questionPlay[index].AnswerA;  
  69.                 btnB.Text = questionPlay[index].AnswerB;  
  70.                 btnC.Text = questionPlay[index].AnswerC;  
  71.                 btnD.Text = questionPlay[index].AnswerD;  
  72.                 mCountDown.Start();  
  73.             } else {  
  74.                 Intent intent = new Intent(thistypeof(Done));  
  75.                 Bundle dataSend = new Bundle();  
  76.                 dataSend.PutInt("SCORE", score);  
  77.                 dataSend.PutInt("TOTAL", totalQuestion);  
  78.                 dataSend.PutInt("CORRECT", correctAnswer);  
  79.                 intent.PutExtras(dataSend);  
  80.                 StartActivity(intent);  
  81.                 Finish();  
  82.             }  
  83.         }  
  84.         protected override void OnResume() {  
  85.             base.OnResume();  
  86.             questionPlay = db.GetQuestionMode(mode);  
  87.             totalQuestion = questionPlay.Count;  
  88.             mCountDown = new CountDown(this, TIMEOUT, INTERVAL);  
  89.             ShowQuestion(index);  
  90.         }  
  91.         class CountDown: CountDownTimer {  
  92.             Playing playing;  
  93.             public CountDown(Playing playing, long totalTime, long intervel): base(totalTime, intervel) {  
  94.                 this.playing = playing;  
  95.             }  
  96.             public override void OnFinish() {  
  97.                 Cancel();  
  98.                 playing.ShowQuestion(++index);  
  99.             }  
  100.             public override void OnTick(long millisUntilFinished) {  
  101.                 playing.progressValue++;  
  102.                 playing.progressBar.Progress = playing.progressValue;  
  103.             }  
  104.         }  
  105.     }  
  106. }  

Step 16

Again, add a new Layout, open Solution Explorer-> Project Name-> Resources-> Layout-> Right click add new item select Layout give it a name like, Done.axml and add the following code.

(FileName: Done.axml)

XAML Code

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="#242E38" android:layout_width="match_parent" android:layout_height="match_parent">  
  3.     <RelativeLayout android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:layout_marginTop="30dp" android:padding="20dp" android:elevation="4dp" android:background="@drawable/round_corner" android:layout_width="match_parent" android:layout_height="wrap_content">  
  4.         <LinearLayout android:orientation="vertical" android:id="@+id/btnGroup" android:paddingTop="10dp" android:layout_width="match_parent" android:layout_height="wrap_content">  
  5.             <TextView android:id="@+id/txtTotalScore" android:gravity="center" android:text="SCORE : 0" android:textSize="30sp" android:layout_width="match_parent" android:layout_height="wrap_content" />  
  6.             <TextView android:id="@+id/txtTotalQuestion" android:gravity="center" android:text="" android:textSize="30sp" android:layout_width="match_parent" android:layout_height="wrap_content" />  
  7.             <ProgressBar style="@style/Widget.AppCompat.ProgressBar.Horizontal" android:id="@+id/progressBardone" android:layout_marginLeft="8dp" android:layout_marginRight="8dp" android:layout_width="match_parent" android:layout_height="wrap_content" />  
  8.             <Button android:id="@+id/btnTryAgain" android:layout_margin="8dp" android:background="#AD1457" android:foreground="?android:attr/selectableItemBackground" android:text="TRY AGAIN" android:textColor="#FFFFFF" android:textStyle="bold" android:theme="@style/MyButton" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout>  
  9.     </RelativeLayout>  
  10. </RelativeLayout>  
    

Step 17

Again, add another Activity, go to Solution Explorer-> Project Name-> right click to add a new item select Activity give it a name like, Done and add the following code with appropriate namespaces.

(FileName: Done)

C# Code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Android.App;  
  6. using Android.Content;  
  7. using Android.OS;  
  8. using Android.Runtime;  
  9. using Android.Views;  
  10. using Android.Widget;  
  11. namespace FlagQuizGame {  
  12.     [Activity(Label = "Done", Theme = "@style/Theme.AppCompat.Light.NoActionBar")]  
  13.     public class Done: Activity {  
  14.         Button btnTryAgain;  
  15.         TextView txtTotalQuestion, txtTotalScore;  
  16.         ProgressBar progressBarResult;  
  17.         protected override void OnCreate(Bundle savedInstanceState) {  
  18.             base.OnCreate(savedInstanceState);  
  19.             SetContentView(Resource.Layout.Done);  
  20.             DbHelper.DbHelper db = new DbHelper.DbHelper(this);  
  21.             btnTryAgain = FindViewById < Button > (Resource.Id.btnTryAgain);  
  22.             txtTotalQuestion = FindViewById < TextView > (Resource.Id.txtTotalQuestion);  
  23.             txtTotalScore = FindViewById < TextView > (Resource.Id.txtTotalScore);  
  24.             progressBarResult = FindViewById < ProgressBar > (Resource.Id.progressBardone);  
  25.             btnTryAgain.Click += delegate {  
  26.                 Intent intent = new Intent(thistypeof(MainActivity));  
  27.                 StartActivity(intent);  
  28.                 Finish();  
  29.             };  
  30.             //Get Data  
  31.             Bundle bundle = Intent.Extras;  
  32.             if (bundle != null) {  
  33.                 int score = bundle.GetInt("SCORE");  
  34.                 int totalQuestion = bundle.GetInt("TOTAL");  
  35.                 int coreectAnswer = bundle.GetInt("CORRECT");  
  36.                 //Update 2.0  
  37.                 int playCount = 0;  
  38.                 if (totalQuestion == 30) // Easy Mode  
  39.                 {  
  40.                     playCount = db.GetPlayCount(0);  
  41.                     playCount++;  
  42.                     db.UpdatePlayCount(0, playCount);  
  43.                 } else  
  44.                 if (totalQuestion == 50) // Medium Mode  
  45.                 {  
  46.                     playCount = db.GetPlayCount(1);  
  47.                     playCount++;  
  48.                     db.UpdatePlayCount(1, playCount);  
  49.                 } else  
  50.                 if (totalQuestion == 100) // Hard Mode  
  51.                 {  
  52.                     playCount = db.GetPlayCount(2);  
  53.                     playCount++;  
  54.                     db.UpdatePlayCount(2, playCount);  
  55.                 } else  
  56.                 if (totalQuestion == 200) // Hardest Mode  
  57.                 {  
  58.                     playCount = db.GetPlayCount(3);  
  59.                     playCount++;  
  60.                     db.UpdatePlayCount(3, playCount);  
  61.                 }  
  62.                 double minus = ((5.0 / (float) score) * 100) * (playCount - 1);  
  63.                 double finalScore = score - minus;  
  64.                 //  
  65.                 txtTotalScore.Text = $ "SCORE :{ finalScore.ToString("  
  66.                 0.00 ")} (-{ 5 * (playCount - 1)}%) ";  
  67.                 txtTotalQuestion.Text = $ "PASSED : {coreectAnswer}/{totalQuestion}";  
  68.                 progressBarResult.Max = totalQuestion;  
  69.                 progressBarResult.Progress = coreectAnswer;  
  70.                 //Save Score  
  71.                 db.InsertScore(score);  
  72.             }  
  73.         }  
  74.     }  
  75. }  

Step 18

Similarly, add a new Layout, open Solution Explorer-> Project Name-> Resources-> Layout-> Right click add new item select Layout give it a name like, Score.axml and add the following code.

(FileName: Score.axml)

XAML Code

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="#242E38" android:layout_width="match_parent" android:layout_height="match_parent">  
  3.     <RelativeLayout android:layout_marginLeft="30dp" android:layout_marginRight="30dp" android:layout_marginTop="30dp" android:padding="20dp" android:elevation="4dp" android:background="@drawable/round_corner" android:layout_width="match_parent" android:layout_height="wrap_content">  
  4.         <TextView android:id="@+id/txtTitle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:gravity="center" android:text="BEST SCORE" android:textStyle="bold" android:textSize="30sp" />  
  5.         <ListView android:id="@+id/lstView" android:layout_below="@id/txtTitle" android:layout_marginTop="10dp" android:layout_width="match_parent" android:layout_height="wrap_content" /> </RelativeLayout>  
  6. </RelativeLayout>  
   

Step 19

Add a new Activity, open Solution Explorer-> Project Name-> right click to add a new item select Activity give it a name like Score and add the following code with appropriate namespaces.

(FileName: Score)

C# Code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Android.App;  
  6. using Android.Content;  
  7. using Android.OS;  
  8. using Android.Runtime;  
  9. using Android.Views;  
  10. using Android.Widget;  
  11. using FlagQuizGame.Model;  
  12. using FlagQuizGame.Common;  
  13. namespace FlagQuizGame {  
  14.     [Activity(Label = "Score", Theme = "@style/AppTheme")]  
  15.     public class Score: Activity {  
  16.         ListView listView;  
  17.         protected override void OnCreate(Bundle savedInstanceState) {  
  18.             base.OnCreate(savedInstanceState);  
  19.             SetContentView(Resource.Layout.Score);  
  20.             listView = FindViewById < ListView > (Resource.Id.lstView);  
  21.             DbHelper.DbHelper db = new DbHelper.DbHelper(this);  
  22.             List < Ranking > lstRanking = db.GetRanking();  
  23.             if (lstRanking.Count > 0) {  
  24.                 CustomAdapter adapter = new CustomAdapter(this, lstRanking);  
  25.                 listView.Adapter = adapter;  
  26.             }  
  27.         }  
  28.     }  
  29. }  

Step 20

Add a new Layout, open Solution Explorer-> Project Name-> Resources-> Layout-> Right click add new item select Layout give it a name like, row.axml and add the following code.

(FileName: row.axml)

XAML Code

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">  
  3.    <LinearLayout android:padding="10dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent">  
  4.       <ImageView android:id="@+id/imgTop" android:background="@drawable/top1" android:layout_width="50dp" android:layout_height="50dp" />  
  5.       <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/txtTop" android:gravity="center" android:layout_marginLeft="10dp" android:textSize="30sp" android:textStyle="bold" />  
  6.    </LinearLayout>  
  7. </LinearLayout>  

Step 21

Next, add a new class, go to Solution Explorer-> Project Name and right-click Add -> New Item-> Class. Give it a name like, CustomAdapter.cs and write the following code.

(FileName: CustomAdapter)

C# Code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Android.App;  
  6. using Android.Content;  
  7. using Android.OS;  
  8. using Android.Runtime;  
  9. using Android.Views;  
  10. using Android.Widget;  
  11. using FlagQuizGame.Model;  
  12. using Java.Lang;  
  13. namespace FlagQuizGame.Common {  
  14.     class CustomAdapter: BaseAdapter {  
  15.         private Context context;  
  16.         private List < Ranking > lstRanking;  
  17.         public CustomAdapter(Context context, List < Ranking > lstRanking) {  
  18.             this.context = context;  
  19.             this.lstRanking = lstRanking;  
  20.         }  
  21.         public override int Count {  
  22.             get {  
  23.                 return lstRanking.Count;  
  24.             }  
  25.         }  
  26.         public override Java.Lang.Object GetItem(int position) {  
  27.             return position;  
  28.         }  
  29.         public override long GetItemId(int position) {  
  30.             return position;  
  31.         }  
  32.         public override View GetView(int position, View convertView, ViewGroup parent) {  
  33.             LayoutInflater inflater = (LayoutInflater) context.GetSystemService(Context.LayoutInflaterService);  
  34.             View view = inflater.Inflate(Resource.Layout.row, null);  
  35.             TextView txtTop = view.FindViewById < TextView > (Resource.Id.txtTop);  
  36.             ImageView imageTop = view.FindViewById < ImageView > (Resource.Id.imgTop);  
  37.             if (position == 0) imageTop.SetBackgroundResource(Resource.Drawable.top1);  
  38.             else if (position == 1) imageTop.SetBackgroundResource(Resource.Drawable.top2);  
  39.             else imageTop.SetBackgroundResource(Resource.Drawable.top3);  
  40.             txtTop.Text = $ "{lstRanking[position].Score.ToString("  
  41.             0.00 ")}";  
  42.             return view;  
  43.         }  
  44.     }  
  45. }  

Finally, we have done our flag quiz game. Just rebuild and run the project. You will have a result like below.

Output

 


Similar Articles