public void SetupPage() { //turn on the display of the board and models SharedGraphicsDeviceManager.Current.GraphicsDevice.SetSharingMode(true); //Run the detection separate from the update dispatcherTimer.Start(); // Create a timer for this page timer.Start(); //see if user was placed into check if ((GameStateManager.getInstance().getGameState().black.in_check&& GameStateManager.getInstance().getCurrentPlayer() == ChessPiece.Color.BLACK) || (GameStateManager.getInstance().getGameState().white.in_check&& GameStateManager.getInstance().getCurrentPlayer() == ChessPiece.Color.WHITE)) { handleError("You have been placed into check by your opponent."); } //if the state of the game has not yet been loaded, load it now before displaying board if (!stateHasBeenLoaded) { GameState.getInstance().loadState(GameStateManager.getInstance().getGameState()); stateHasBeenLoaded = true; } //Initialize the camera photoCamera = new PhotoCamera(); photoCamera.Initialized += new EventHandler <CameraOperationCompletedEventArgs>(photoCamera_Initialized); ViewFinderBrush.SetSource(photoCamera); setupFinished = true; }
private void KnightClick(object sender, RoutedEventArgs e) { GameState.getInstance().getSelectedPiece().setMasqueradesAs("knight"); hidePopup(); SetupPage(); alreadyCalledPromote = false; }
private void Detect() { //Here is where we try to detect the marker if (isDetecting || !isInitialized) { return; } isDetecting = true; try { // Update buffer size var pixelWidth = photoCamera.PreviewResolution.Width; var pixelHeight = photoCamera.PreviewResolution.Height; if (buffer == null || buffer.Length != pixelWidth * pixelHeight) { buffer = new byte[System.Convert.ToInt32(pixelWidth * pixelHeight)]; } // Grab snapshot for the marker detection photoCamera.GetPreviewBufferY(buffer); //Detect the markers arDetector.Threshold = 100; DetectionResults dr = arDetector.DetectAllMarkers(buffer, System.Convert.ToInt32(pixelWidth), System.Convert.ToInt32(pixelHeight)); GameState.getInstance().Detect(dr); } finally { isDetecting = false; } }
private void handleError(string error) { GameState.getInstance().resetTurn(); VibrateController vibrate = VibrateController.Default; //vibrate the phone for 2 seconds vibrate.Start(TimeSpan.FromMilliseconds(2000)); MessageBox.Show(error, "Error", MessageBoxButton.OK); }
void photoCamera_Initialized(object sender, CameraOperationCompletedEventArgs e) { // Initialize the Detector //This need to be done AFTER the camera is initialized arDetector = new GrayBufferMarkerDetector(); // Setup both markers Marker[] markers = GameState.getInstance().getMarkers(); arDetector.Initialize(System.Convert.ToInt32(photoCamera.PreviewResolution.Width), System.Convert.ToInt32(photoCamera.PreviewResolution.Height), 1, 4000, markers); isInitialized = true; }
private void waitForOpponent() { TeardownPage(); var bw = new BackgroundWorker(); bw.DoWork += (s, args) => { response = new NetworkTask().getGameState(); while (response.is_game_over == false && response.is_current_players_turn == false) { Thread.Sleep(10000); response = new NetworkTask().getGameState(); } }; bw.RunWorkerCompleted += (s, args) => { alreadyCalledWait = false; if (response.is_game_over == false) { GameStateManager.getInstance().setShouldWait(false); GameStateManager.getInstance().setGameState(response.game_state); stateHasBeenLoaded = false; SetupPage(); hidePopup(); } else { string myColor = GameState.getInstance().getMyColor() == ChessPiece.Color.BLACK ? "black" : "white"; if (response.winner == myColor) { Deployment.Current.Dispatcher.BeginInvoke(() => { NavigationService.Navigate(new Uri("/WonPage.xaml", UriKind.Relative)); }); } else { Deployment.Current.Dispatcher.BeginInvoke(() => { NavigationService.Navigate(new Uri("/LostPage.xaml", UriKind.Relative)); }); } } }; bw.RunWorkerAsync(); showPopup("Waiting"); }
private void CommitButton_Click(object sender, EventArgs e) { if (GameState.getInstance().inCheck(GameState.getInstance().getMyColor())) { // Self in check MessageBox.Show("You cannot leave your King open to attack.", "Please try another move.", MessageBoxButton.OK); // Reset Turn GameState.getInstance().resetTurn(); } else { // Self not in check - Proceed MessageBoxResult result = MessageBox.Show("Once done, this move cannot be undone.", "Are you sure?", MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { // Check is opponent is in check or checkmate ChessPiece.Color opponentColor = GameState.getInstance().getMyColor() == ChessPiece.Color.BLACK ? ChessPiece.Color.WHITE : ChessPiece.Color.BLACK; if (GameState.getInstance().inCheck(opponentColor)) { if (GameState.getInstance().checkmate(opponentColor)) { // Checkmate // Take King to signify End Game //MessageBox.Show("You have placed your opponent in checkmate.", "Winner! It works!!!", MessageBoxButton.OK); //pageToGo = "/WonPage.xaml"; } else { // Just Check // Set Check flag MessageBox.Show("But can you finish him off?", "You have placed your opponent in check.", MessageBoxButton.OK); } } // Opponent is at least in Check // Send result to server sendMove(); } else { // Reset Turn alreadyCalledPromote = false; GameState.getInstance().resetTurn(); } } }
private void sendMove() { //send the move to the central server so that it can be sent to the opponents phone var bw = new BackgroundWorker(); bw.DoWork += (s, args) => { new NetworkTask().sendGameState(GameState.getInstance().toCurrentGameState()); }; bw.RunWorkerCompleted += (s, args) => { GameStateManager.getInstance().setShouldWait(true); }; bw.RunWorkerAsync(); }
/// <summary> /// Allows the page to draw itself. /// </summary> private void OnDraw(object sender, GameTimerEventArgs e) { //Renders your Silverlight content uiRenderer.Render(); SharedGraphicsDeviceManager.Current.GraphicsDevice.Clear(Microsoft.Xna.Framework.Color.Black); //Draw your ui renderer onto a texture feed texture spriteBatch.Begin(); spriteBatch.Draw(uiRenderer.Texture, Vector2.Zero, Microsoft.Xna.Framework.Color.White); spriteBatch.End(); //Draw game try { GameState.getInstance().Draw(); bool doesAPawnNeedPromotion = false; string color = GameStateManager.getInstance().getCurrentPlayer().ToString().ToLower(); bool white_and_end = color == "white" && GameState.getInstance().getSelectedPiece() != null && GameState.getInstance().getSelectedPiece().getMasqueradeType() == "pawn" && GameState.getInstance().getSelectedPiece().getPosition().X == 7; bool black_and_end = color == "black" && GameState.getInstance().getSelectedPiece() != null && GameState.getInstance().getSelectedPiece().getMasqueradeType() == "pawn" && GameState.getInstance().getSelectedPiece().getPosition().X == 0; doesAPawnNeedPromotion = (white_and_end || black_and_end); //check to see if pawn promotion is needed if (doesAPawnNeedPromotion && !alreadyCalledPromote) { TeardownPage(); showPopup("Pawn Promote"); alreadyCalledPromote = true; } } catch (Exception ex) { handleError(ex.Message); } //we have made our move, now wait for the opponent to make theirs if (GameStateManager.getInstance().getShouldWait() && setupFinished && !alreadyCalledWait) { Deployment.Current.Dispatcher.BeginInvoke(() => { waitForOpponent(); }); alreadyCalledWait = true; } }
void _client_RecognizeSpeechCompleted(object sender, RecognizeSpeechCompletedEventArgs e) { hidePopup(); bool good = false; try { //attempt to process voice recognition VoiceCommandFuzzyProcessing.process(e.Result); //determine if there is a pawn that needs promotion bool doesAPawnNeedPromotion = false; string color = GameStateManager.getInstance().getCurrentPlayer().ToString().ToLower(); bool white_and_end = color == "white" && GameState.getInstance().getSelectedPiece() != null && GameState.getInstance().getSelectedPiece().getMasqueradeType() == "pawn" && GameState.getInstance().getChosenPosition().X == 7; bool black_and_end = color == "black" && GameState.getInstance().getSelectedPiece() != null && GameState.getInstance().getSelectedPiece().getMasqueradeType() == "pawn" && GameState.getInstance().getChosenPosition().X == 0; doesAPawnNeedPromotion = (white_and_end || black_and_end); //check to see if pawn promotion is needed if (doesAPawnNeedPromotion && !alreadyCalledPromote) { showPopup("Pawn Promote"); alreadyCalledPromote = true; } else { SetupPage(); } good = true; } catch (Exception ex) { handleError(ex.Message); } finally { if (!good) { SetupPage(); } } }
public GamePage() { InitializeComponent(); // Get the application's ContentManager content = (Application.Current as App).Content; timer = new GameTimer { UpdateInterval = TimeSpan.FromTicks(333333) }; timer.Update += OnUpdate; timer.Draw += OnDraw; dispatcherTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(50) }; dispatcherTimer.Tick += (sender, e1) => Detect(); if (GameState.getInstance(false) != null) { GameState.getInstance().resetTurn(); } //setup microphone and configure delegates that handle events microphone.BufferDuration = TimeSpan.FromSeconds(1); microphoneBuffer = new byte[microphone.GetSampleSizeInBytes(microphone.BufferDuration)]; BasicHttpBinding binding = new BasicHttpBinding() { MaxReceivedMessageSize = int.MaxValue, MaxBufferSize = int.MaxValue }; EndpointAddress address = new EndpointAddress(voiceRecognitionServerIP); speechRecognitionClient = new ARVRClient(binding, address); microphone.BufferReady += delegate { microphone.GetData(microphoneBuffer); microphoneMemoryStream.Write(microphoneBuffer, 0, microphoneBuffer.Length); }; speechRecognitionClient.RecognizeSpeechCompleted += new EventHandler <RecognizeSpeechCompletedEventArgs>(_client_RecognizeSpeechCompleted); }
/// <summary> /// Allows the page to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> private void OnUpdate(object sender, GameTimerEventArgs e) { GameState.getInstance().Update(); }
public static void process(string command) { Regex r1 = null, r2 = null, r3 = null; Match match1 = null, match2 = null, match3 = null; //grab only the parts of the commands that we care about if (command.ToLower().IndexOf("move") != -1) { //find space identity r3 = new Regex(@"space ([A-H1-8]) ([A-Za-z0-9\-]+)"); match3 = r3.Match(command); } else if (command.ToLower().IndexOf("select") != -1) { //find piece after select or select the r1 = new Regex(@"select ([A-Za-z0-9\-]+)"); r2 = new Regex(@"select the ([A-Za-z0-9\-]+)"); match1 = r1.Match(command); match2 = r2.Match(command); //find space identity r3 = new Regex(@"space ([A-H1-8]) ([A-Za-z0-9\-]+)"); match3 = r3.Match(command); } else { throw new Exception(command); } if (r1 != null && r2 != null) { GameState.getInstance().resetTurn(); ChessPiece.Piece chosenPiece; Vector2 chosenLocation; if (match2.Length == 0) { chosenPiece = processPiece(match1.Groups[1].Value); } else { chosenPiece = processPiece(match2.Groups[1].Value); } //convert A7 or whatever board space to X, Y coordinates chosenLocation = processLocation(match3.Groups[1].Value, match3.Groups[2].Value); //find the closest piece of the specified type to the specified board square Vector2 closestApproximation = findClosestPiece(chosenLocation, chosenPiece); GameState.getInstance().setSelected(closestApproximation); } else { //convert A7 or whatever board space to X, Y coordinates Vector2 chosenLocation = processLocation(match3.Groups[1].Value, match3.Groups[2].Value); GameState.getInstance().setSelected(chosenLocation); } }
private static Vector2 findClosestPiece(Vector2 chosenLocation, ChessPiece.Piece chosenPiece) { Dictionary <string, ChessPiece> chessPieces = GameState.getInstance().getPieces(); string color = GameStateManager.getInstance().getCurrentPlayer().ToString().ToLower() + "_"; Vector2 closestLocation = new Vector2(); for (int i = 1; i <= 8; ++i) { if (chessPieces[color + "pawn" + i].getMasqueradeType() == chosenPiece.ToString().ToLower()) { if (Vector2.Distance(chosenLocation, chessPieces[color + "pawn" + i].getPosition()) < Vector2.Distance(chosenLocation, closestLocation)) { closestLocation = chessPieces[color + "pawn" + i].getPosition(); } } } for (int i = 1; i <= 2; ++i) { if (chessPieces[color + "rook" + i].getMasqueradeType() == chosenPiece.ToString().ToLower()) { if (Vector2.Distance(chosenLocation, chessPieces[color + "rook" + i].getPosition()) < Vector2.Distance(chosenLocation, closestLocation)) { closestLocation = chessPieces[color + "rook" + i].getPosition(); } } } for (int i = 1; i <= 2; ++i) { if (chessPieces[color + "knight" + i].getMasqueradeType() == chosenPiece.ToString().ToLower()) { if (Vector2.Distance(chosenLocation, chessPieces[color + "knight" + i].getPosition()) < Vector2.Distance(chosenLocation, closestLocation)) { closestLocation = chessPieces[color + "knight" + i].getPosition(); } } } if (chessPieces[color + "king"].getMasqueradeType() == chosenPiece.ToString().ToLower()) { if (Vector2.Distance(chosenLocation, chessPieces[color + "king"].getPosition()) < Vector2.Distance(chosenLocation, closestLocation)) { closestLocation = chessPieces[color + "king"].getPosition(); } } if (chessPieces[color + "queen"].getMasqueradeType() == chosenPiece.ToString().ToLower()) { if (Vector2.Distance(chosenLocation, chessPieces[color + "queen"].getPosition()) < Vector2.Distance(chosenLocation, closestLocation)) { closestLocation = chessPieces[color + "queen"].getPosition(); } } for (int i = 1; i <= 2; ++i) { if (chessPieces[color + "bishop" + i].getMasqueradeType() == chosenPiece.ToString().ToLower()) { if (Vector2.Distance(chosenLocation, chessPieces[color + "bishop" + i].getPosition()) < Vector2.Distance(chosenLocation, closestLocation)) { closestLocation = chessPieces[color + "bishop" + i].getPosition(); } } } return(closestLocation); }
public void Draw() { if (mDetectionResult != null) { if ((mBoardMarker != null)) { Microsoft.Xna.Framework.Matrix boardMat = mBoardMarker.Transformation.ToXnaMatrix(), selectorMat = mDetectionResult.Transformation.ToXnaMatrix(), boardMat_inv; boardMat_inv = Microsoft.Xna.Framework.Matrix.Invert(boardMat); Vector3 position = new Vector3(0, 0, 0); Vector3 direction = new Vector3(0, -1, -1); position = Vector3.Transform(position, selectorMat * boardMat_inv); //direction = Vector3.Transform(direction, selectorMat * boardMat_inv); position = position / 31; //direction = direction / 31; //System.Diagnostics.Debug.WriteLine(position); Vector3 boardCoord = (position + direction * position.Z) + new Vector3(8.5f, 8.5f, 0); int x = (int)(boardCoord.X < 5 ? (4 - boardCoord.X) * -1 : boardCoord.X - 4), y = (int)(boardCoord.Y < 5 ? (4 - boardCoord.Y) * -1 : boardCoord.Y - 4); if ((x >= 0) && (x <= 7) && (y >= 0) && (y <= 7)) { // Selection is on board if (mPosition != new Vector2(x, y)) { // Selection has changed selectedSince = DateTime.Now; mPosition.X = x; mPosition.Y = y; mSelected = false; } else { // Selection has been held DateTime time = DateTime.Now; long elapsedTicks = time.Ticks - selectedSince.Ticks; TimeSpan elapsedSpan = new TimeSpan(elapsedTicks); if (elapsedSpan.TotalSeconds > 2.0) { // Selection has been held 1 second //mSelected = true; selectedSince = DateTime.Now; GameState state = GameState.getInstance(); state.setSelected(mPosition); } } } direction = direction * 15; ModelDrawer.DrawLine(mBoardMarker, position, position + direction); ModelDrawer.Draw(mBoardMarker, ModelSelector.getModel(ModelSelector.Pieces.RED_SQUARE), x, y, 0.2); } } }