Click here to Skip to main content
15,885,914 members
Articles / Mobile Apps

Windows Phone Crosswords

Rate me:
Please Sign up or sign in to vote.
5.00/5 (22 votes)
3 Jul 2012CPOL6 min read 62.4K   1.4K   42  
Learn how to create a Windows Phone crosswords game taking advantage of online internet resources
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Crosswords.Controls;
using System.Windows.Navigation;
using Crosswords.WebHelper;
using Crosswords.Core;
using System.Text;
using System.Text.RegularExpressions;
using Crosswords.Models;
using System.Collections.Specialized;
using Microsoft.Phone.Shell;
using Microsoft.Devices;

namespace Crosswords
{
    public partial class Board : PhoneApplicationPage
    {
        int selectedSize = 10;
        BoardViewModel boardViewModel;
        Point swipeDownPoint;
        Point swipeMovePoint;
        Point swipeUpPoint;
        private ApplicationBarIconButton btnRefresh;
        private ApplicationBarIconButton btnQuestion;
        private ApplicationBarIconButton btnCheck;
        private ApplicationBarIconButton btnWrite;

        public Board()
        {
            InitializeComponent();
            InitAppBar();
            customKeyboard.KeyPressed += new CustomKeyboard.CustomKeypressed(customKeyboard_KeyPressed);
        }

        void customKeyboard_KeyPressed(object sender, CustomKeyEventArgs customKeyEventArgs)
        {
            VibrateController vibrate = VibrateController.Default;
            vibrate.Start(TimeSpan.FromMilliseconds(25));
            boardViewModel.TypeLetter(customKeyEventArgs.Key);
            if (!boardViewModel.Squares.Where(s => s.IsSelected).Any())
            {
                ShowClues();
            }
        }

        private void InitAppBar()
        {
            var buttonNames = new string[] { "refresh", "write", "clues", "solve" };

            ApplicationBar appBar = new ApplicationBar();
            appBar.IsVisible = true;
            appBar.IsMenuEnabled = true;
            appBar.Opacity = 1.0;
            appBar.ForegroundColor = Colors.Black;
            appBar.BackgroundColor = Color.FromArgb(0xFF, 0xDD, 0xDD, 0xDD);
            foreach (var buttonName in buttonNames)
            {
                var button = new ApplicationBarIconButton(new Uri(string.Format("images/{0}.png", buttonName), UriKind.Relative));
                button.Click += new EventHandler(AppBarIconButton_Click);
                button.Text = buttonName;
                appBar.Buttons.Add(button);
            }

            btnRefresh = appBar.Buttons[0] as ApplicationBarIconButton;
            btnRefresh.IsEnabled = false;
            btnWrite = appBar.Buttons[1] as ApplicationBarIconButton;
            btnQuestion = appBar.Buttons[2] as ApplicationBarIconButton;
            btnQuestion.IsEnabled = false;
            btnCheck = appBar.Buttons[3] as ApplicationBarIconButton;

            ApplicationBar = appBar;
        }

        void AppBarIconButton_Click(object sender, EventArgs e)
        {
            var btn = (ApplicationBarIconButton)sender;
            switch (btn.Text)
            {
                case "refresh":
                    RefreshGrid();
                    break;
                case "write":
                    ShowKeyboard();
                    break;
                case "clues":
                    ShowClues();
                    break;
                case "solve":
                    SolvePuzzle();
                    break;
                default:
                    break;
            }
        }

        private void RefreshGrid()
        {
            foreach (var item in grdTileContainer.Children)
            {
                var tile = item as Tile;
                tile.txtLetter.Text = "";
                tile.txtLetter.Visibility = System.Windows.Visibility.Collapsed;
                tile.txtUserLetter.Visibility = System.Windows.Visibility.Collapsed;
                tile.txtUserLetter.Text = "";
            }
            boardViewModel.LoadGrid();
        }

        private void ShowKeyboard()
        {
            btnQuestion.IsEnabled = true;
            btnWrite.IsEnabled = false;
            customKeyboard.Visibility = System.Windows.Visibility.Visible;
            txtClue.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void ShowClues()
        {
            btnQuestion.IsEnabled = false;
            btnWrite.IsEnabled = true;
            customKeyboard.Visibility = System.Windows.Visibility.Collapsed;
            txtClue.Visibility = System.Windows.Visibility.Visible;
        }

        void Touch_FrameReported(object sender, TouchFrameEventArgs e)
        {
            try
            {
                var touchPoint = e.GetPrimaryTouchPoint(grdTileContainer);
                if (touchPoint.Action == TouchAction.Down)
                {
                    swipeDownPoint = touchPoint.Position;
                }
                else if (touchPoint.Action == TouchAction.Move)
                {
                    swipeMovePoint = touchPoint.Position;
                }
                else if (touchPoint.Action == TouchAction.Up)
                {
                    swipeUpPoint = touchPoint.Position;

                    if (swipeDownPoint != new Point(0, 0) &&
                        swipeMovePoint != new Point(0, 0))
                    {
                        boardViewModel.SelectSquaresByPosition(grdTileContainer.ActualWidth, grdTileContainer.ActualHeight, swipeDownPoint, swipeUpPoint);

                        swipeDownPoint =
                        swipeMovePoint =
                        swipeUpPoint = new Point(0, 0);

                        ShowClues();
                    }
                }
            }
            catch (ArgumentException ex)
            {
            }
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            AfterEnteredPage();
            Touch.FrameReported += new TouchFrameEventHandler(Touch_FrameReported);
        }

        private void AfterEnteredPage()
        {
            int startMode = (int)StartMode.ResumeGame;

            if (this.NavigationContext.QueryString["StartMode"] != null)
            {
                startMode = int.Parse(this.NavigationContext.QueryString["StartMode"]);
                selectedSize = int.Parse(this.NavigationContext.QueryString["Size"]);
            }
            else
            {
                selectedSize = int.Parse(this.NavigationContext.QueryString["Size"]);
            }

            boardViewModel = new BoardViewModel(this.Dispatcher, selectedSize, SquaresChanged);
            boardViewModel.HtmlLoaded += new EventHandler(boardViewModel_HtmlLoaded);
            this.DataContext = boardViewModel;

            for (var i = 0; i < selectedSize; i++)
            {
                grdTileContainer.ColumnDefinitions.Add(new ColumnDefinition());
                grdTileContainer.RowDefinitions.Add(new RowDefinition());
            }

            for (var row = 0; row < selectedSize; row++)
            {
                for (var col = 0; col < selectedSize; col++)
                {
                    var tile = new Tile();
                    grdTileContainer.Children.Add(tile);
                    tile.SetValue(Grid.RowProperty, row);
                    tile.SetValue(Grid.ColumnProperty, col);
                    var fontSize = 28;
                    switch (selectedSize)
                    {
                        case 4:
                            fontSize = 52;
                            break;
                        case 7:
                            fontSize = 40;
                            break;
                        case 10:
                            fontSize = 28;
                            break;
                    }
                    tile.FontSize = fontSize;
                }
            }

            boardViewModel.LoadGrid();
        }

        void boardViewModel_HtmlLoaded(object sender, EventArgs e)
        {
            btnRefresh.IsEnabled = true;
        }

        private void lstClues_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var wordId = ((Clue)(lstClues.SelectedItem)).WordId;
            boardViewModel.SelectSquaresByWordId(wordId);
        }

        private void SquaresChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            Dispatcher.BeginInvoke(delegate
            {
                if (e.NewItems != null)
                {
                    foreach (var item in e.NewItems)
                    {
                        var square = (Square)item;
                        var tile = (Tile)grdTileContainer.Children[square.Row * selectedSize + square.Column];
                        if (square.Letter != null)
                        {
                            tile.Text = square.Letter;
                            tile.UserText = square.UserLetter;
                            tile.IsSelected = square.IsSelected;
                        }
                    }
                }
            });
        }

        private static void ShowUnexpectedError()
        {
            MessageBox.Show(@"We're sorry, but an unexpected connection error occurred. Please try again later.", "Oops!", MessageBoxButton.OK);
        }

        private void SolvePuzzle()
        {
            foreach (var item in grdTileContainer.Children)
            {
                var tile = (Tile)item;
                tile.ShowCorrectLetter();
            }
        }

        private void btnKeyboard_Click(object sender, EventArgs e)
        {
            btnWrite.IsEnabled = false;
            btnQuestion.IsEnabled = true;
            txtClue.Visibility = System.Windows.Visibility.Collapsed;
            customKeyboard.Visibility = System.Windows.Visibility.Visible;
        }

        private void btnQuestion_Click(object sender, EventArgs e)
        {
            btnWrite.IsEnabled = true;
            btnQuestion.IsEnabled = false;
            txtClue.Visibility = System.Windows.Visibility.Visible;
            customKeyboard.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void btnCheck_Click(object sender, EventArgs e)
        {

        }
    }

    public enum StartMode
    {
        NewGame = 1,
        ResumeGame = 2
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Instructor / Trainer Alura Cursos Online
Brazil Brazil

Comments and Discussions