Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Документация_Оригинал / Пояснювальна_записка_Диплом_Оригинал_1

.pdf
Скачиваний:
7
Добавлен:
11.06.2015
Размер:
1.13 Mб
Скачать

75

//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;

76

// 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();

77

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();

78

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();

}

}

79

}

Клас 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();

}

80

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("Пожалуйста, выберите категорию!");

81

md.ShowAsync();

}

}

private async void btnTwoPlayer_Click(object sender, TappedRoutedEventArgs e)

{

try

{

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

{

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

}

}

catch

{

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

}

}

private void cmbBoxTime_SelectionChanged(object sender, SelectionChangedEventArgs e)

{

switch(((ComboBoxItem)comboBox.SelectedItem).Content.ToString())

{

case "Спорт": category = "Sport"; break;

case "Животные": category = "Animals"; break;

}

}

}

}

Клас MainPage.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.Phone.UI.Input;

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=391641

82

namespace Quiz

{

///<summary>

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

///</summary>

public sealed partial class MainPage : Page

{

Classes.User[] com;

public MainPage()

{

this.InitializeComponent();

this.NavigationCacheMode = NavigationCacheMode.Required;

HardwareButtons.BackPressed += HardwareButtons_BackPressed; hideStatusBar();

}

async void hideStatusBar()

{

await Windows.UI.ViewManagement.StatusBar.GetForCurrentView().HideAsync();

}

void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)

{

if (Frame.CanGoBack)

{

e.Handled = true; Frame.GoBack();

}

else

Application.Current.Exit();

}

///<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)

{

//TODO: Prepare page for display here.

//TODO: If your application contains multiple pages, ensure that you are

//handling the hardware Back button by registering for the

//Windows.Phone.UI.Input.HardwareButtons.BackPressed event.

//If you are using the NavigationHelper provided by some templates,

//this event is handled for you.

}

private async void Page_Loaded(object sender, RoutedEventArgs e)

{

try

{

83

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

StorageFile sampleFile2 = await folder.CreateFileAsync("Users.xml", CreationCollisionOption.FailIfExists);

string text = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"

+"\n<users>"

+"\n</users>";

await Windows.Storage.FileIO.WriteTextAsync(sampleFile2, text.ToString());

}

catch

{

}

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();

}

private void btnRegist_Click(object sender, RoutedEventArgs e)

{

Frame.Navigate(typeof(Registration));

}

private async void btnAouth_Click(object sender, RoutedEventArgs e)

{

MessageDialog md;

if (string.IsNullOrWhiteSpace(txtLogin.Text) || string.IsNullOrWhiteSpace(txtPass.Password))

{

md = new MessageDialog("Пожалуйста заполните все поля!"); await md.ShowAsync();

return;

}

for (int i = 0; i < com.Length; i++)

{

84

if (string.Equals(txtLogin.Text, com[i].login, StringComparison.CurrentCultureIgnoreCase) && string.Equals(txtPass.Password, com[i].pass, StringComparison.CurrentCultureIgnoreCase))

{

ApplicationData.Current.LocalSettings.Values["UserName"] =

com[i].login;

Frame.Navigate(typeof(Menu)); return;

}

}

md = new MessageDialog("Неправильный логин или пароль!"); await md.ShowAsync();

}

}

}

Клас Items.cs

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace Quiz.Classes

{

public class Items

{

public string question { get; set; } public string unsver1 { get; set; } public string unsver2 { get; set; } public string unsver3 { get; set; } public string unsver4 { get; set; } public string trueUnsver { get; set; }

}

}

Клас Record.cs

using System;

using System.Collections.Generic; using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace Quiz.Classes

{

public class Record

{

public string name { get; set; } public string score { get; set; } public string mode { get; set; }