Студопедия

КАТЕГОРИИ:


Архитектура-(3434)Астрономия-(809)Биология-(7483)Биотехнологии-(1457)Военное дело-(14632)Высокие технологии-(1363)География-(913)Геология-(1438)Государство-(451)Демография-(1065)Дом-(47672)Журналистика и СМИ-(912)Изобретательство-(14524)Иностранные языки-(4268)Информатика-(17799)Искусство-(1338)История-(13644)Компьютеры-(11121)Косметика-(55)Кулинария-(373)Культура-(8427)Лингвистика-(374)Литература-(1642)Маркетинг-(23702)Математика-(16968)Машиностроение-(1700)Медицина-(12668)Менеджмент-(24684)Механика-(15423)Науковедение-(506)Образование-(11852)Охрана труда-(3308)Педагогика-(5571)Полиграфия-(1312)Политика-(7869)Право-(5454)Приборостроение-(1369)Программирование-(2801)Производство-(97182)Промышленность-(8706)Психология-(18388)Религия-(3217)Связь-(10668)Сельское хозяйство-(299)Социология-(6455)Спорт-(42831)Строительство-(4793)Торговля-(5050)Транспорт-(2929)Туризм-(1568)Физика-(3942)Философия-(17015)Финансы-(26596)Химия-(22929)Экология-(12095)Экономика-(9961)Электроника-(8441)Электротехника-(4623)Энергетика-(12629)Юриспруденция-(1492)Ядерная техника-(1748)

Пояснювальна записка до кваліфікаційної роботи 10 страница




using System.IO;

using System.Linq;

using System.Runtime.InteropServices.WindowsRuntime;

using System.Xml.Linq;

using Windows.Foundation;

using Windows.Foundation.Collections;

using Windows.Storage;

using Windows.UI.Popups;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives;

using Windows.UI.Xaml.Data;

using Windows.UI.Xaml.Input;

using Windows.UI.Xaml.Media;

using Windows.UI.Xaml.Navigation;

 

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

 

namespace Quiz

{

/// <summary>

/// An empty page that can be used on its own or navigated to within a Frame.

/// </summary>

public sealed partial class Registration: Page

{

public Registration()

{

this.InitializeComponent();

}

 

Продовження дод. В

/// <summary>

/// Invoked when this page is about to be displayed in a Frame.

/// </summary>

/// <param name="e">Event data that describes how this page was reached.

/// This parameter is typically used to configure the page.</param>

protected override void OnNavigatedTo(NavigationEventArgs e)

{

}

 

private async void btnRegist_Click(object sender, RoutedEventArgs e)

{

Classes.User[] com;

 

Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("Users.xml");

string users_text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

 

XDocument xDoc = XDocument.Parse(users_text);

 

com = xDoc.Root.Elements("user").Select(p =>

{

return new Classes.User()

{

login = p.Element("login").Value,

pass = p.Element("pass").Value

};

}).ToArray();

 

foreach (var item in com)

{

if (item.login == txtLogin.Text && item.pass ==txtPass.Password)

{

MessageDialog md = new MessageDialog("Пользователья с таким именем уже существует!");

await md.ShowAsync();

}

return;

}

 

string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

 

 

string newText = text.Replace("</users>", "\n<user>"

+ "\n<login>"

+ txtLogin.Text

+ "</login>"

+ "\n<pass>"

+ txtPass.Password

+ "</pass>"

+ "\n</user>"

+ "\n</users>");

 

Продовження дод. В

 

StorageFile sampleFile2 = await storageFolder.CreateFileAsync("Users.xml", CreationCollisionOption.OpenIfExists);

await Windows.Storage.FileIO.WriteTextAsync(sampleFile2, newText);

 

System.Diagnostics.Debug.WriteLine(newText);

 

MessageDialog md1 = new MessageDialog("Пользователь успешно добавлен!");

await md1.ShowAsync();

Frame.GoBack();

}

 

private void btnBack_Click(object sender, RoutedEventArgs e)

{

Frame.GoBack();

}

}

}

 

Клас Records.xaml.cs

 

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Runtime.InteropServices.WindowsRuntime;

using System.Xml.Linq;

using Windows.Foundation;

using Windows.Foundation.Collections;

using Windows.Storage;

using Windows.UI.Popups;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives;

using Windows.UI.Xaml.Data;

using Windows.UI.Xaml.Input;

using Windows.UI.Xaml.Media;

using Windows.UI.Xaml.Navigation;

 

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

 

namespace Quiz

{

/// <summary>

/// An empty page that can be used on its own or navigated to within a Frame.

/// </summary>

public sealed partial class Registration: Page

{

public Registration()

{

this.InitializeComponent();

}

 

Продовження дод. В

 

/// <summary>

/// Invoked when this page is about to be displayed in a Frame.

/// </summary>

/// <param name="e">Event data that describes how this page was reached.

/// This parameter is typically used to configure the page.</param>

protected override void OnNavigatedTo(NavigationEventArgs e)

{

}

 

private async void btnRegist_Click(object sender, RoutedEventArgs e)

{

Classes.User[] com;

 

Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("Users.xml");

string users_text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

 

XDocument xDoc = XDocument.Parse(users_text);

 

com = xDoc.Root.Elements("user").Select(p =>

{

return new Classes.User()

{

login = p.Element("login").Value,

pass = p.Element("pass").Value

};

}).ToArray();

 

foreach (var item in com)

{

if (item.login == txtLogin.Text && item.pass ==txtPass.Password)

{

MessageDialog md = new MessageDialog("Пользователья с таким именем уже существует!");

await md.ShowAsync();

}

return;

}

 

string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

 

 

string newText = text.Replace("</users>", "\n<user>"

+ "\n<login>"

+ txtLogin.Text

+ "</login>"

+ "\n<pass>"

+ txtPass.Password

+ "</pass>"

+ "\n</user>"

+ "\n</users>");

 

 

Продовження дод. В

 

StorageFile sampleFile2 = await storageFolder.CreateFileAsync("Users.xml", CreationCollisionOption.OpenIfExists);

await Windows.Storage.FileIO.WriteTextAsync(sampleFile2, newText);

 

System.Diagnostics.Debug.WriteLine(newText);

 

MessageDialog md1 = new MessageDialog("Пользователь успешно добавлен!");

await md1.ShowAsync();

Frame.GoBack();

}

 

private void btnBack_Click(object sender, RoutedEventArgs e)

{

Frame.GoBack();

}

}

}

 

Клас OnePlayer2.xaml.cs

 

using Newtonsoft.Json.Linq;

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net.Http;

using System.Runtime.InteropServices.WindowsRuntime;

using Windows.Foundation;

using Windows.Foundation.Collections;

using Windows.Storage;

using Windows.UI.Popups;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives;

using Windows.UI.Xaml.Data;

using Windows.UI.Xaml.Input;

using Windows.UI.Xaml.Media;

using Windows.UI.Xaml.Navigation;

 

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

 

namespace Quiz

{

/// <summary>

/// An empty page that can be used on its own or navigated to within a Frame.

/// </summary>

public sealed partial class OnePlayer2: Page

{

List<Classes.Items> items;

int randNumb;

int countTrueUnsver = 0;

string category;

Продовження дод. В

 

public OnePlayer2()

{

this.InitializeComponent();

}

 

/// <summary>

/// Invoked when this page is about to be displayed in a Frame.

/// </summary>

/// <param name="e">Event data that describes how this page was reached.

/// This parameter is typically used to configure the page.</param>

protected override void OnNavigatedTo(NavigationEventArgs e)

{

category = e.Parameter.ToString();

 

}

 

private void Gen_Quest()

{

Random rand = new Random();

randNumb = rand.Next(0, items.Count);

 

txtQuestion.Text = items[randNumb].question;

}

 

private async void Page_Loaded(object sender, RoutedEventArgs e)

{

using (HttpClient httpClient = new HttpClient())

{

HttpRequestMessage request = new HttpRequestMessage();

httpClient.BaseAddress = new Uri("https://api.parse.com/1/classes/" + category);

request.Method = new HttpMethod("GET");

request.Headers.Add("X-Parse-Application-Id", "q8r9XYoXbEw1kXsWIXbyCNQm9ylcWfAS0fqlWWNx");

request.Headers.Add("X-Parse-REST-API-Key", "2nke5LSbXQmTiA9FaVytlBihjOOz4fPcoxjEHlee");

 

var response = await httpClient.SendAsync(request);

var text = await response.Content.ReadAsStringAsync();

 

System.Diagnostics.Debug.WriteLine(text);

 

JObject results = JObject.Parse(text);

items = new List<Classes.Items>();

foreach (var result in results["results"])

{

items.Add(new Classes.Items() { question = (string)result["Question"], trueUnsver = (string)result["trueUnsver"] });

}

 

Gen_Quest();

}

}

 

private async void Button_Click(object sender, RoutedEventArgs e)

Продовження дод. В

{

if (string.Equals(txtBox.Text, items[randNumb].trueUnsver, StringComparison.CurrentCultureIgnoreCase))

{

MessageDialog md1 = new MessageDialog("Это был правильный ответ!");

await md1.ShowAsync();

 

txtBox.Text = "";

countTrueUnsver++;

txtScore.Text = countTrueUnsver.ToString();

Gen_Quest();

}

else

{

MessageDialog md1 = new MessageDialog("Вы отетили не верно! Правильный ответ: " + items[randNumb].trueUnsver);

await md1.ShowAsync();

 

MessageDialog md = new MessageDialog("Игра окночена! Сохранить результат в рекордах?");

UICommand cancelBtn = new UICommand("Нет");

cancelBtn.Invoked = cancelBtn_CLick;

UICommand yesBtn = new UICommand("Да");

yesBtn.Invoked = yesBtn_CLick;

 

md.Commands.Add(cancelBtn);

md.Commands.Add(yesBtn);

 

await md.ShowAsync();

}

}

 

private async void yesBtn_CLick(IUICommand command)

{

HttpClient httpClient = new HttpClient();

HttpRequestMessage request = new HttpRequestMessage();

httpClient.BaseAddress = new Uri("https://api.parse.com/1/classes/Record");

httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

 

string data = "{\"Name\":\"" + ApplicationData.Current.LocalSettings.Values["UserName"].ToString() + "\",\"Score\":" + countTrueUnsver + ",\"Mode\":\"MyUnsver\"}";

 

request.Headers.Add("X-Parse-Application-Id", "q8r9XYoXbEw1kXsWIXbyCNQm9ylcWfAS0fqlWWNx");

request.Headers.Add("X-Parse-REST-API-Key", "2nke5LSbXQmTiA9FaVytlBihjOOz4fPcoxjEHlee");

 

request.Method = new HttpMethod("POST");

 

// var response = await httpClient.PostAsync(request, new StringContent(data, System.Text.Encoding.UTF8, "application/json"));

request.Content = new StringContent(data, System.Text.Encoding.UTF8, "application/json");

await httpClient.SendAsync(request);

Продовження дод. В

//Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

//Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("Records.xml");

//string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

 

 

//string newText = text.Replace("</records>", "\n<record>"

// + "\n<name>"

// + ApplicationData.Current.LocalSettings.Values["UserName"].ToString()

// + "</name>"

// + "\n<score>"

// + countTrueUnsver

// + "</score>"

// + "\n</record>"

// + "\n</records>");

 

 

//StorageFile sampleFile2 = await storageFolder.CreateFileAsync("Records.xml", CreationCollisionOption.OpenIfExists);

//await Windows.Storage.FileIO.WriteTextAsync(sampleFile2, newText);

 

//System.Diagnostics.Debug.WriteLine(newText);

 

MessageDialog md = new MessageDialog("Рекорд успешно сохранен!");

await md.ShowAsync();

Frame.GoBack();

}

 

private void cancelBtn_CLick(IUICommand command)

{

Frame.GoBack();

}

}

}

 

Клас OnePlayer.xaml.cs

 

using Newtonsoft.Json.Linq;

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net.Http;

using System.Runtime.InteropServices.WindowsRuntime;

using Windows.Foundation;

using Windows.Foundation.Collections;

using Windows.Storage;

using Windows.UI.Popups;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives;

using Windows.UI.Xaml.Data;

using Windows.UI.Xaml.Input;

Продовження дод. В

using Windows.UI.Xaml.Media;

using Windows.UI.Xaml.Navigation;

 

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

 

namespace Quiz

{

/// <summary>

/// An empty page that can be used on its own or navigated to within a Frame.

/// </summary>

public sealed partial class OnePlayer: Page

{

List<Classes.Items> items;

int randNumb;

int countTrueUnsver = 0;

string category;

 

public OnePlayer()

{

this.InitializeComponent();

}

 

/// <summary>

/// Invoked when this page is about to be displayed in a Frame.

/// </summary>

/// <param name="e">Event data that describes how this page was reached.

/// This parameter is typically used to configure the page.</param>

protected override void OnNavigatedTo(NavigationEventArgs e)

{

category = e.Parameter.ToString();

}

 

private void Gen_Quest()

{

Random rand = new Random();

randNumb = rand.Next(0, items.Count);

 

txtQuestion.Text = items[randNumb].question;

btnUnsver1Text.Text = items[randNumb].unsver1;

btnUnsver2Text.Text = items[randNumb].unsver2;

btnUnsver3Text.Text = items[randNumb].unsver3;

btnUnsver4Text.Text = items[randNumb].unsver4;

}

 

private async void Page_Loaded(object sender, RoutedEventArgs e)

{

using (HttpClient httpClient = new HttpClient())

{

HttpRequestMessage request = new HttpRequestMessage();

httpClient.BaseAddress = new Uri("https://api.parse.com/1/classes/" + category);

request.Method = new HttpMethod("GET");

request.Headers.Add("X-Parse-Application-Id", "q8r9XYoXbEw1kXsWIXbyCNQm9ylcWfAS0fqlWWNx");

 

Продовження дод. В

request.Headers.Add("X-Parse-REST-API-Key", "2nke5LSbXQmTiA9FaVytlBihjOOz4fPcoxjEHlee");

 

var response = await httpClient.SendAsync(request);

var text = await response.Content.ReadAsStringAsync();

 

System.Diagnostics.Debug.WriteLine(text);

 

JObject results = JObject.Parse(text);

items = new List<Classes.Items>();

foreach (var result in results["results"])

{

items.Add(new Classes.Items() { question = (string)result["Question"], unsver1 = (string)result["unsver1"], unsver2 = (string)result["unsver2"], unsver3 = (string)result["unsver3"], unsver4 = (string)result["unsver4"], trueUnsver = (string)result["trueUnsver"] });

//item.Add(new Item() { driveId = (string)result["parentReference"]["driveId"], id = (string)result["parentReference"]["id"], path = (string)result["parentReference"]["path"] });

}

 

Gen_Quest();

}

}

 

private async void btnUnsverText_Tapped(object sender, TappedRoutedEventArgs e)

{

string unsver = (sender as TextBlock).Text.ToString();

 

if (unsver == items[randNumb].trueUnsver)

{

MessageDialog md1 = new MessageDialog("Это был правильный ответ!");

await md1.ShowAsync();

 

countTrueUnsver++;

txtScore.Text = countTrueUnsver.ToString();

Gen_Quest();

}

else

{

MessageDialog md1 = new MessageDialog("Вы отетили не верно! Правильный ответ: " + items[randNumb].trueUnsver);

await md1.ShowAsync();

 

MessageDialog md = new MessageDialog("Игра окночена! Сохранить результат в рекордах?");

UICommand cancelBtn = new UICommand("Нет");

cancelBtn.Invoked = cancelBtn_CLick;

UICommand yesBtn = new UICommand("Да");

yesBtn.Invoked = yesBtn_CLick;

 

md.Commands.Add(cancelBtn);

md.Commands.Add(yesBtn);

 

await md.ShowAsync();

Продовження дод. В

}

}

 

private async void yesBtn_CLick(IUICommand command)

{

 

HttpClient httpClient = new HttpClient();

HttpRequestMessage request = new HttpRequestMessage();

httpClient.BaseAddress = new Uri("https://api.parse.com/1/classes/Record");

httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

 

string data = "{\"Name\":\"" + ApplicationData.Current.LocalSettings.Values["UserName"].ToString() + "\",\"Score\":" + countTrueUnsver + ",\"Mode\":\"4btn\"}";

 

request.Headers.Add("X-Parse-Application-Id", "q8r9XYoXbEw1kXsWIXbyCNQm9ylcWfAS0fqlWWNx");

request.Headers.Add("X-Parse-REST-API-Key", "2nke5LSbXQmTiA9FaVytlBihjOOz4fPcoxjEHlee");

 

request.Method = new HttpMethod("POST");

 

// var response = await httpClient.PostAsync(request, new StringContent(data, System.Text.Encoding.UTF8, "application/json"));

request.Content = new StringContent(data, System.Text.Encoding.UTF8, "application/json");

await httpClient.SendAsync(request);

 

//var text = await response.Content.ReadAsStringAsync();

 

//Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;

//Windows.Storage.StorageFile sampleFile = await storageFolder.GetFileAsync("Records.xml");

//string text = await Windows.Storage.FileIO.ReadTextAsync(sampleFile);

 

 

//string newText = text.Replace("</records>", "\n<record>"

// + "\n<name>"

// + ApplicationData.Current.LocalSettings.Values["UserName"].ToString()

// + "</name>"

// + "\n<score>"

// + countTrueUnsver

// + "</score>"

// + "\n</record>"

// + "\n</records>");

 

 

//StorageFile sampleFile2 = await storageFolder.CreateFileAsync("Records.xml", CreationCollisionOption.OpenIfExists);

//await Windows.Storage.FileIO.WriteTextAsync(sampleFile2, newText);

 

//System.Diagnostics.Debug.WriteLine(newText);

 

MessageDialog md = new MessageDialog("Рекорд успешно сохранен!");

Продовження дод. В

await md.ShowAsync();

Frame.GoBack();

}

 

private void cancelBtn_CLick(IUICommand command)

{

Frame.GoBack();

}

}

}

 

Клас Menu.xaml.cs

 

using Newtonsoft.Json.Linq;

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net.Http;

using System.Runtime.InteropServices.WindowsRuntime;

using Windows.Foundation;

using Windows.Foundation.Collections;

using Windows.Storage;

using Windows.UI.Popups;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives;

using Windows.UI.Xaml.Data;

using Windows.UI.Xaml.Input;

using Windows.UI.Xaml.Media;

using Windows.UI.Xaml.Navigation;

 

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

 

namespace Quiz

{

/// <summary>

/// An empty page that can be used on its own or navigated to within a Frame.

/// </summary>

public sealed partial class Menu: Page

{

List<Classes.Items> items;

bool playerAdverPanelStatus = false;

string category = null;

 

public Menu()

{

this.InitializeComponent();

}

 

/// <summary>

/// Invoked when this page is about to be displayed in a Frame.

/// </summary>

Продовження дод. В

/// <param name="e">Event data that describes how this page was reached.

/// This parameter is typically used to configure the page.</param>

protected override void OnNavigatedTo(NavigationEventArgs e)

{

 

}

 

private void goBack_click(object sender, TappedRoutedEventArgs e)

{

Frame.GoBack();

}

 

private void Page_Loaded(object sender, RoutedEventArgs e)

{

txtPlayerName.Text = ApplicationData.Current.LocalSettings.Values["UserName"].ToString();

comboBox.SelectedItem = "sda";

}

 

private void btnOnePlayer_Click(object sender, TappedRoutedEventArgs e)

{

if (playerAdverPanelStatus == false)

{

advencedPanelForOnePlayer.Visibility = Windows.UI.Xaml.Visibility.Visible;

playerAdverPanelStatus = true;

}

else

{

advencedPanelForOnePlayer.Visibility = Windows.UI.Xaml.Visibility.Collapsed;

playerAdverPanelStatus = false;

}

}

 

 

private async void btnChooseUnsver_Click(object sender, TappedRoutedEventArgs e)

{

try

{

if (!string.IsNullOrEmpty(comboBox.SelectedItem.ToString()))

{

Frame.Navigate(typeof(OnePlayer), category);

}

}

catch

{

MessageDialog md = new MessageDialog("Пожалуйста, выберите категорию!");

md.ShowAsync();

}

}

 

private void btnRecord_Click(object sender, TappedRoutedEventArgs e)

{

Frame.Navigate(typeof(Records));

}

Продовження дод. В

private async void btnYourUnsver_Click(object sender, TappedRoutedEventArgs e)

{

try

{

if (!string.IsNullOrEmpty(comboBox.SelectedItem.ToString()))

{

Frame.Navigate(typeof(OnePlayer2), category);

}

}

catch

{

MessageDialog md = new MessageDialog("Пожалуйста, выберите категорию!");




Поделиться с друзьями:


Дата добавления: 2015-06-30; Просмотров: 309; Нарушение авторских прав?; Мы поможем в написании вашей работы!


Нам важно ваше мнение! Был ли полезен опубликованный материал? Да | Нет



studopedia.su - Студопедия (2013 - 2024) год. Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав! Последнее добавление




Генерация страницы за: 0.302 сек.