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
- Question about flags of all countries in the world
- Time Limit: 5 seconds per question
- Mode: Easy, Medium, Hard, Hardest
- Database: SQLit
- Score: Highest and lowest score based Medals
Prerequisite
- Flag Images
- Medals Images
- 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
- namespace FlagQuiz.Common {
- public class Common {
- public
- const int EASY_MODE_NUM = 30;
- public
- const int MEDIUM_MODE_NUM = 50;
- public
- const int HARD_MODE_NUM = 100;
- public
- const int HARDEST_MODE_NUM = 200;
- public enum MODE {
- EASY,
- MEDIUM,
- HARD,
- HARDEST
- }
- }
- }
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
- namespace FlagQuizGame.Model {
- public class Question {
- public int Id {
- get;
- set;
- }
- public string Image {
- get;
- set;
- }
- public string AnswerA {
- get;
- set;
- }
- public string AnswerB {
- get;
- set;
- }
- public string AnswerC {
- get;
- set;
- }
- public string AnswerD {
- get;
- set;
- }
- public string CorrectAnswer {
- get;
- set;
- }
- public Question(int Id, string Image, string AnswerA, string AnswerB, string AnswerC, string AnswerD, string CorrectAnswer) {
- this.Id = Id;
- this.Image = Image;
- this.AnswerA = AnswerA;
- this.AnswerB = AnswerB;
- this.AnswerC = AnswerC;
- this.AnswerD = AnswerD;
- this.CorrectAnswer = CorrectAnswer;
- }
- }
- }
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
- namespace FlagQuizGame.Model {
- public class Ranking {
- public int Id {
- get;
- set;
- }
- public double Score {
- get;
- set;
- }
- public Ranking(int Id, double Score) {
- this.Id = Id;
- this.Score = Score;
- }
- }
- }
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
- using Android.Content;
- using Android.Database;
- using Android.Database.Sqlite;
- using FlagQuizGame.Model;
- using System;
- using System.Collections.Generic;
- using System.IO;
- namespace FlagQuizGame.DbHelper {
- public class DbHelper: SQLiteOpenHelper {
- private static string DB_PATH = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
- private static string DB_NAME = "MyDB.db";
- private static int VERSION = 1;
- private Context context;
- public DbHelper(Context context): base(context, DB_NAME, null, VERSION) {
- this.context = context;
- }
- private string GetSQLitePath() {
- return Path.Combine(DB_PATH, DB_NAME);
- }
- public override SQLiteDatabase WritableDatabase {
- get {
- return CreateSQLiteDB();
- }
- }
- private SQLiteDatabase CreateSQLiteDB() {
- SQLiteDatabase sqliteDB = null;
- string path = GetSQLitePath();
- Stream streamSQLite = null;
- FileStream streamWriter = null;
- Boolean isSQLiteInit = false;
- try {
- if (File.Exists(path)) isSQLiteInit = true;
- else {
- streamSQLite = context.Resources.OpenRawResource(Resource.Raw.MyDB);
- streamWriter = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
- if (streamSQLite != null && streamWriter != null) {
- if (CopySQLiteDB(streamSQLite, streamWriter)) isSQLiteInit = true;
- }
- }
- if (isSQLiteInit) sqliteDB = SQLiteDatabase.OpenDatabase(path, null, DatabaseOpenFlags.OpenReadwrite);
- } catch {}
- return sqliteDB;
- }
- private bool CopySQLiteDB(Stream streamSQLite, FileStream streamWriter) {
- bool isSuccess = false;
- int length = 1024;
- Byte[] buffer = new Byte[length];
- try {
- int bytesRead = streamSQLite.Read(buffer, 0, length);
- while (bytesRead > 0) {
- streamWriter.Write(buffer, 0, bytesRead);
- bytesRead = streamSQLite.Read(buffer, 0, length);
- }
- isSuccess = true;
- } catch {} finally {
- streamWriter.Close();
- streamSQLite.Close();
- }
- return isSuccess;
- }
- public override void OnCreate(SQLiteDatabase db) {}
- public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {}
- public void InsertScore(double score) {
- String query = $ "INSERT INTO Ranking(Score) VALUES({score})";
- SQLiteDatabase db = this.WritableDatabase;
- db.ExecSQL(query);
- }
- public List < Ranking > GetRanking() {
- List < Ranking > lstRanking = new List < Ranking > ();
- SQLiteDatabase db = this.WritableDatabase;
- ICursor c;
- try {
- c = db.RawQuery($ "SELECT * FROM Ranking ORDER BY Score", null);
- if (c == null) {
- return null;
- } else {
- c.MoveToNext();
- }
- do {
- int Id = c.GetInt(c.GetColumnIndex("Id"));
- double Score = c.GetDouble(c.GetColumnIndex("Score"));
- Ranking ranking = new Ranking(Id, Score);
- lstRanking.Add(ranking);
- }
- while (c.MoveToNext());
- c.Close();
- } catch {}
- db.Close();
- return lstRanking;
- }
- public List < Question > GetQuestionMode(string mode) {
- List < Question > lstQuestion = new List < Question > ();
- SQLiteDatabase db = this.WritableDatabase;
- ICursor c;
- int limit = 0;
- if (mode.Equals(Common.Common.MODE.EASY.ToString())) limit = Common.Common.EASY_MODE_NUM;
- else if (mode.Equals(Common.Common.MODE.MEDIUM.ToString())) limit = Common.Common.MEDIUM_MODE_NUM;
- else if (mode.Equals(Common.Common.MODE.HARD.ToString())) limit = Common.Common.HARD_MODE_NUM;
- else limit = Common.Common.HARDEST_MODE_NUM;
- try {
- c = db.RawQuery($ "SELECT * FROM Question ORDER BY Random() LIMIT {limit}", null);
- if (c == null) return null;
- c.MoveToFirst();
- do {
- int Id = c.GetInt(c.GetColumnIndex("ID"));
- string Image = c.GetString(c.GetColumnIndex("Image"));
- string AnswerA = c.GetString(c.GetColumnIndex("AnswerA"));
- string AnswerB = c.GetString(c.GetColumnIndex("AnswerB"));
- string AnswerC = c.GetString(c.GetColumnIndex("AnswerC"));
- string AnswerD = c.GetString(c.GetColumnIndex("AnswerD"));
- string CorrectAnswer = c.GetString(c.GetColumnIndex("CorrectAnswer"));
- Question question = new Question(Id, Image, AnswerA, AnswerB, AnswerC, AnswerD, CorrectAnswer);
- lstQuestion.Add(question);
- }
- while (c.MoveToNext());
- c.Close();
- } catch {}
- return lstQuestion;
- }
-
- public int GetPlayCount(int Level) {
- int result = 0;
- SQLiteDatabase db = this.WritableDatabase;
- ICursor c;
- try {
- c = db.RawQuery($ "SELECT PlayCount FROM UserPlayCount WHERE Level={Level}", null);
- if (c == null) return 0;
- c.MoveToFirst();
- do {
- result = c.GetInt(c.GetColumnIndex("PlayCount"));
- } while (c.MoveToNext());
- c.Close();
- } catch (Exception e) {}
- return result;
- }
- public void UpdatePlayCount(int Level, int PlayCount) {
- string query = $ "UPDATE UserPlayCount SET PlayCount={PlayCount} WHERE Level={Level}";
- SQLiteDatabase db = this.WritableDatabase;
- db.ExecSQL(query);
- }
- }
- }
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
- <?xml version="1.0" encoding="utf-8" ?>
- <shape xmlns:android="http://schemas.android.com/apk/res/android">
- <solid android:color="#FFFFFF" />
- <strok android:width="1dip" android:color="#1e1e1e" />
- <corners android:radius="10dip" />
- <padding android:left="0dip" android:right="0dip" android:bottom="0dip" android:top="0dip" />
- </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
- <?xml version="1.0" encoding="utf-8" ?>
- <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
- <item android:bottom="-2dp" android:top="-2dp" android:right="-2dp" android:left="-2dp">
- <shape android:shape="rectangle">
- <strok android:width="1dp" android:color="#004d40" />
- <solid android:color="#00FFFFFF" /> </shape>
- </item>
- </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
- <?xml version="1.0" encoding="utf-8" ?>
- <resources>
- <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
- <item name="colorPrimary">#3F51B5</item><item name="colorPrimaryDark">#242E38</item><item name="colorAccent">#FF4081</item>
- </style>
- <style name="MyButton" parent="Theme.AppCompat.Light">
- <item name="colorControlHighlight">#1CB3BC</item>
- </style>
- </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
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="#242E38" android:layout_width="match_parent" android:layout_height="match_parent">
- <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" />
- <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">
- <LinearLayout android:orientation="vertical" android:id="@+id/btnGroup" android:paddingTop="10dp" android:layout_width="match_parent" android:layout_height="wrap_content">
- <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" />
- <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>
- <LinearLayout android:layout_below="@+id/btnGroup" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="wrap_content">
- <SeekBar android:id="@+id/seekBar" android:max="3" android:layout_width="300dp" android:layout_height="wrap_content" />
- <TextView android:id="@+id/txtMode" android:layout_gravity="center" android:text="EASY" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
- </RelativeLayout>
- </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
- using Android.App;
- using Android.Widget;
- using Android.OS;
- using static Android.Widget.SeekBar;
- using Android.Content;
- using Android.Database.Sqlite;
- using System;
- namespace FlagQuizGame {
- [Activity(Label = "Flag Quiz Game", MainLauncher = true, Theme = "@style/Theme.AppCompat.Light.NoActionBar")]
- public class MainActivity: Activity, IOnSeekBarChangeListener {
- SeekBar seekBar;
- TextView txtMode;
- Button btnPlay, btnScore;
- DbHelper.DbHelper db;
- SQLiteDatabase sqLiteDB;
- protected override void OnCreate(Bundle savedInstanceState) {
- base.OnCreate(savedInstanceState);
-
- SetContentView(Resource.Layout.Main);
- db = new DbHelper.DbHelper(this);
- sqLiteDB = db.WritableDatabase;
- seekBar = FindViewById < SeekBar > (Resource.Id.seekBar);
- txtMode = FindViewById < TextView > (Resource.Id.txtMode);
- btnPlay = FindViewById < Button > (Resource.Id.btnPlay);
- btnScore = FindViewById < Button > (Resource.Id.btnScore);
- btnPlay.Click += delegate {
- Intent intent = new Intent(this, typeof(Playing));
- intent.PutExtra("MODE", getPlayMode());
- StartActivity(intent);
- Finish();
- };
- seekBar.SetOnSeekBarChangeListener(this);
- btnScore.Click += delegate {
- Intent intent = new Intent(this, typeof(Score));
- StartActivity(intent);
- Finish();
- };
- }
- private String getPlayMode() {
- if (seekBar.Progress == 0) return Common.Common.MODE.EASY.ToString();
- else if (seekBar.Progress == 1) return Common.Common.MODE.MEDIUM.ToString();
- else if (seekBar.Progress == 2) return Common.Common.MODE.HARD.ToString();
- else return Common.Common.MODE.HARDEST.ToString();
- }
- public void OnProgressChanged(SeekBar seekBar, int progress, bool fromUser) {
- txtMode.Text = getPlayMode().ToUpper();
- }
- public void OnStartTrackingTouch(SeekBar seekBar) {}
- public void OnStopTrackingTouch(SeekBar seekBar) {}
- }
- }
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
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="#242E38" android:layout_width="match_parent" android:layout_height="match_parent">
- <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" />
- <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">
- <LinearLayout android:orientation="vertical" android:id="@+id/btnGroup" android:paddingTop="10dp" android:layout_width="match_parent" android:layout_height="wrap_content">
- <LinearLayout android:weightSum="2" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content">
- <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" />
- <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>
- <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" />
- <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" />
- <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" />
- <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" />
- <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>
- </RelativeLayout>
- </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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Runtime;
- using Android.Views;
- using Android.Widget;
- using FlagQuizGame.Model;
- using static Android.Views.View;
- namespace FlagQuizGame {
- [Activity(Label = "Playing", Theme = "@style/Theme.AppCompat.Light.NoActionBar")]
- public class Playing: Activity, IOnClickListener {
- const long INTERVAL = 1000;
- const long TIMEOUT = 6000;
- public int progressValue = 0;
- static CountDown mCountDown;
- List < Question > questionPlay = new List < Question > ();
- DbHelper.DbHelper db;
- static int index, score, thisQuestion, totalQuestion, correctAnswer;
- String mode = String.Empty;
-
- public ProgressBar progressBar;
- TextView txtScore, txtQuestion;
- Button btnA, btnB, btnC, btnD;
- ImageView imageView;
- protected override void OnCreate(Bundle savedInstanceState) {
- base.OnCreate(savedInstanceState);
- SetContentView(Resource.Layout.Playing);
-
- Bundle extra = Intent.Extras;
- if (extra != null) mode = extra.GetString("MODE");
- db = new DbHelper.DbHelper(this);
- txtScore = FindViewById < TextView > (Resource.Id.txtScore);
- txtQuestion = FindViewById < TextView > (Resource.Id.txtQuestion);
- progressBar = FindViewById < ProgressBar > (Resource.Id.progressBar);
- imageView = FindViewById < ImageView > (Resource.Id.question_flag);
- btnA = FindViewById < Button > (Resource.Id.btnAnswerA);
- btnB = FindViewById < Button > (Resource.Id.btnAnswerB);
- btnC = FindViewById < Button > (Resource.Id.btnAnswerC);
- btnD = FindViewById < Button > (Resource.Id.btnAnswerD);
- btnA.SetOnClickListener(this);
- btnB.SetOnClickListener(this);
- btnC.SetOnClickListener(this);
- btnD.SetOnClickListener(this);
- }
- public void OnClick(View v) {
- mCountDown.Cancel();
- if (index < totalQuestion) {
- Button btnClicked = (Button) v;
- if (btnClicked.Text.Equals(questionPlay[index].CorrectAnswer)) {
- score += 10;
- correctAnswer++;
- ShowQuestion(++index);
- } else ShowQuestion(++index);
- }
- txtScore.Text = $ "{score}";
- }
- public void ShowQuestion(int index) {
- if (index < totalQuestion) {
- thisQuestion++;
- txtQuestion.Text = $ "{thisQuestion}/{totalQuestion}";
- progressBar.Progress = progressValue = 0;
- int ImageID = this.Resources.GetIdentifier(questionPlay[index].Image.ToLower(), "drawable", PackageName);
- imageView.SetBackgroundResource(ImageID);
- btnA.Text = questionPlay[index].AnswerA;
- btnB.Text = questionPlay[index].AnswerB;
- btnC.Text = questionPlay[index].AnswerC;
- btnD.Text = questionPlay[index].AnswerD;
- mCountDown.Start();
- } else {
- Intent intent = new Intent(this, typeof(Done));
- Bundle dataSend = new Bundle();
- dataSend.PutInt("SCORE", score);
- dataSend.PutInt("TOTAL", totalQuestion);
- dataSend.PutInt("CORRECT", correctAnswer);
- intent.PutExtras(dataSend);
- StartActivity(intent);
- Finish();
- }
- }
- protected override void OnResume() {
- base.OnResume();
- questionPlay = db.GetQuestionMode(mode);
- totalQuestion = questionPlay.Count;
- mCountDown = new CountDown(this, TIMEOUT, INTERVAL);
- ShowQuestion(index);
- }
- class CountDown: CountDownTimer {
- Playing playing;
- public CountDown(Playing playing, long totalTime, long intervel): base(totalTime, intervel) {
- this.playing = playing;
- }
- public override void OnFinish() {
- Cancel();
- playing.ShowQuestion(++index);
- }
- public override void OnTick(long millisUntilFinished) {
- playing.progressValue++;
- playing.progressBar.Progress = playing.progressValue;
- }
- }
- }
- }
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
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="#242E38" android:layout_width="match_parent" android:layout_height="match_parent">
- <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">
- <LinearLayout android:orientation="vertical" android:id="@+id/btnGroup" android:paddingTop="10dp" android:layout_width="match_parent" android:layout_height="wrap_content">
- <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" />
- <TextView android:id="@+id/txtTotalQuestion" android:gravity="center" android:text="" android:textSize="30sp" android:layout_width="match_parent" android:layout_height="wrap_content" />
- <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" />
- <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>
- </RelativeLayout>
- </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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Runtime;
- using Android.Views;
- using Android.Widget;
- namespace FlagQuizGame {
- [Activity(Label = "Done", Theme = "@style/Theme.AppCompat.Light.NoActionBar")]
- public class Done: Activity {
- Button btnTryAgain;
- TextView txtTotalQuestion, txtTotalScore;
- ProgressBar progressBarResult;
- protected override void OnCreate(Bundle savedInstanceState) {
- base.OnCreate(savedInstanceState);
- SetContentView(Resource.Layout.Done);
- DbHelper.DbHelper db = new DbHelper.DbHelper(this);
- btnTryAgain = FindViewById < Button > (Resource.Id.btnTryAgain);
- txtTotalQuestion = FindViewById < TextView > (Resource.Id.txtTotalQuestion);
- txtTotalScore = FindViewById < TextView > (Resource.Id.txtTotalScore);
- progressBarResult = FindViewById < ProgressBar > (Resource.Id.progressBardone);
- btnTryAgain.Click += delegate {
- Intent intent = new Intent(this, typeof(MainActivity));
- StartActivity(intent);
- Finish();
- };
-
- Bundle bundle = Intent.Extras;
- if (bundle != null) {
- int score = bundle.GetInt("SCORE");
- int totalQuestion = bundle.GetInt("TOTAL");
- int coreectAnswer = bundle.GetInt("CORRECT");
-
- int playCount = 0;
- if (totalQuestion == 30)
- {
- playCount = db.GetPlayCount(0);
- playCount++;
- db.UpdatePlayCount(0, playCount);
- } else
- if (totalQuestion == 50)
- {
- playCount = db.GetPlayCount(1);
- playCount++;
- db.UpdatePlayCount(1, playCount);
- } else
- if (totalQuestion == 100)
- {
- playCount = db.GetPlayCount(2);
- playCount++;
- db.UpdatePlayCount(2, playCount);
- } else
- if (totalQuestion == 200)
- {
- playCount = db.GetPlayCount(3);
- playCount++;
- db.UpdatePlayCount(3, playCount);
- }
- double minus = ((5.0 / (float) score) * 100) * (playCount - 1);
- double finalScore = score - minus;
-
- txtTotalScore.Text = $ "SCORE :{ finalScore.ToString("
- 0.00 ")} (-{ 5 * (playCount - 1)}%) ";
- txtTotalQuestion.Text = $ "PASSED : {coreectAnswer}/{totalQuestion}";
- progressBarResult.Max = totalQuestion;
- progressBarResult.Progress = coreectAnswer;
-
- db.InsertScore(score);
- }
- }
- }
- }
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
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:background="#242E38" android:layout_width="match_parent" android:layout_height="match_parent">
- <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">
- <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" />
- <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>
- </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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Runtime;
- using Android.Views;
- using Android.Widget;
- using FlagQuizGame.Model;
- using FlagQuizGame.Common;
- namespace FlagQuizGame {
- [Activity(Label = "Score", Theme = "@style/AppTheme")]
- public class Score: Activity {
- ListView listView;
- protected override void OnCreate(Bundle savedInstanceState) {
- base.OnCreate(savedInstanceState);
- SetContentView(Resource.Layout.Score);
- listView = FindViewById < ListView > (Resource.Id.lstView);
- DbHelper.DbHelper db = new DbHelper.DbHelper(this);
- List < Ranking > lstRanking = db.GetRanking();
- if (lstRanking.Count > 0) {
- CustomAdapter adapter = new CustomAdapter(this, lstRanking);
- listView.Adapter = adapter;
- }
- }
- }
- }
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
- <?xml version="1.0" encoding="UTF-8"?>
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent">
- <LinearLayout android:padding="10dp" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent">
- <ImageView android:id="@+id/imgTop" android:background="@drawable/top1" android:layout_width="50dp" android:layout_height="50dp" />
- <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" />
- </LinearLayout>
- </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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Runtime;
- using Android.Views;
- using Android.Widget;
- using FlagQuizGame.Model;
- using Java.Lang;
- namespace FlagQuizGame.Common {
- class CustomAdapter: BaseAdapter {
- private Context context;
- private List < Ranking > lstRanking;
- public CustomAdapter(Context context, List < Ranking > lstRanking) {
- this.context = context;
- this.lstRanking = lstRanking;
- }
- public override int Count {
- get {
- return lstRanking.Count;
- }
- }
- public override Java.Lang.Object GetItem(int position) {
- return position;
- }
- public override long GetItemId(int position) {
- return position;
- }
- public override View GetView(int position, View convertView, ViewGroup parent) {
- LayoutInflater inflater = (LayoutInflater) context.GetSystemService(Context.LayoutInflaterService);
- View view = inflater.Inflate(Resource.Layout.row, null);
- TextView txtTop = view.FindViewById < TextView > (Resource.Id.txtTop);
- ImageView imageTop = view.FindViewById < ImageView > (Resource.Id.imgTop);
- if (position == 0) imageTop.SetBackgroundResource(Resource.Drawable.top1);
- else if (position == 1) imageTop.SetBackgroundResource(Resource.Drawable.top2);
- else imageTop.SetBackgroundResource(Resource.Drawable.top3);
- txtTop.Text = $ "{lstRanking[position].Score.ToString("
- 0.00 ")}";
- return view;
- }
- }
- }
Finally, we have done our flag quiz game. Just rebuild and run the project. You will have a result like below.
Output