O'Reilly Forums: Save The Humans Help - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Save The Humans Help Works perfectly except...

#1 User is offline   Kiki G 

  • New Member
  • Pip
  • Group: Members
  • Posts: 1
  • Joined: 06-June 14
  • Gender:Female

Posted 06 June 2014 - 07:12 AM

Brand new to programming. Working with C# 3rd edition and Visual Studio Express 2013, I used the PDF to create the Save the Humans game. Everything seems to work perfectly except that I don't need to actually have the human to reset the timer. Sad day! What did I miss?

Here is my coding:

<Window x:Class="Save_the_Humans.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="700" Width="1000">
    <Window.Resources>
        <ControlTemplate x:Key="EnemyTemplate" TargetType="{x:Type ContentControl}">
            <Grid>
                <Ellipse Fill="Gray" Height="100" Stroke="Black" Width="75"/>
                <Ellipse Fill="Black" HorizontalAlignment="Center" Height="35" Margin="40,20,70,-1" Stroke="Black" VerticalAlignment="Top" Width="25" RenderTransformOrigin="0.5,0.5">
                    <Ellipse.RenderTransform>
                        <TransformGroup>
                            <ScaleTransform/>
                            <SkewTransform AngleX="10"/>
                            <RotateTransform/>
                            <TranslateTransform/>
                        </TransformGroup>
                    </Ellipse.RenderTransform>
                </Ellipse>
                <Ellipse Fill="Black" HorizontalAlignment="Center" Height="35" Margin="70,20,40,0" Stroke="Black" VerticalAlignment="Top" Width="25" RenderTransformOrigin="0.5,0.5">
                    <Ellipse.RenderTransform>
                        <TransformGroup>
                            <ScaleTransform/>
                            <SkewTransform AngleX="-10"/>
                            <RotateTransform/>
                            <TranslateTransform/>
                        </TransformGroup>
                    </Ellipse.RenderTransform>
                </Ellipse>
            </Grid>
        </ControlTemplate>
    </Window.Resources>
    <Grid x:Name="grid" Background="Black">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="140"/>
            <ColumnDefinition/>
            <ColumnDefinition Width="160"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="150"/>
        </Grid.RowDefinitions>
        <Button x:Name="startButton" Content="Start!" HorizontalAlignment="Center" Grid.Row="1" VerticalAlignment="Center" Click="startButton_Click"/>
        <StackPanel Grid.Column="2" Orientation="Vertical" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center">
            <TextBlock TextWrapping="Wrap" Text="Avoid These" FontSize="18" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White"/>
            <ContentControl Content="ContentControl" Template="{DynamicResource EnemyTemplate}"/>
        </StackPanel>
        <ProgressBar x:Name="progressBar" Grid.Column="1" Grid.Row="1" Height="20"/>
        <Canvas x:Name="playArea" Grid.ColumnSpan="3" MouseMove="playArea_MouseMove" MouseLeave="playArea_MouseLeave">
            <Canvas.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black" Offset="0.247"/>
                    <GradientStop Color="#FFA640EE" Offset="0.793"/>
                </LinearGradientBrush>
            </Canvas.Background>
            <StackPanel x:Name="human" Orientation="Vertical" MouseDown="human_MouseDown">
                <Ellipse Fill="#FFC79753" Height="10" Width="10"/>
                <Rectangle Fill="#FFC79753" Height="25" Width="10"/>
            </StackPanel>
            <TextBlock x:Name="gameOverText" Canvas.Left="225" TextWrapping="Wrap" Text="Game Over" Canvas.Top="205" FontFamily="Arial" FontSize="100" FontWeight="Bold" FontStyle="Italic" Width="555"/>
            <Rectangle x:Name="target" Height="50" Canvas.Left="600" Stroke="Black" Canvas.Top="370" Width="50" RenderTransformOrigin="0.5,0.5" MouseEnter="target_MouseEnter">
                <Rectangle.RenderTransform>
                    <TransformGroup>
                        <ScaleTransform/>
                        <SkewTransform/>
                        <RotateTransform Angle="45"/>
                        <TranslateTransform/>
                    </TransformGroup>
                </Rectangle.RenderTransform>
                <Rectangle.Fill>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="Black" Offset="0"/>
                        <GradientStop Color="White" Offset="1"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Canvas>
    </Grid>
</Window>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace Save_the_Humans
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Random random = new Random();
        DispatcherTimer enemyTimer = new DispatcherTimer();
        DispatcherTimer targetTimer = new DispatcherTimer();
        bool humanCaptured = false;

        public MainWindow()
        {
            InitializeComponent();

            enemyTimer.Tick += enemyTimer_Tick;
            enemyTimer.Interval = TimeSpan.FromSeconds(2);

            targetTimer.Tick += targetTimer_Tick;
            targetTimer.Interval = TimeSpan.FromSeconds(1);
        }

        void targetTimer_Tick(object sender, object e)
        {
            progressBar.Value += 1;
            if (progressBar.Value >= progressBar.Maximum)
                EndTheGame();
        }

        private void EndTheGame()
        {
            enemyTimer.Stop();
            targetTimer.Stop();
            humanCaptured = false;
            startButton.Visibility = Visibility.Visible;
            playArea.Children.Add(gameOverText);
        }   	
        
        void enemyTimer_Tick(object sender, EventArgs e)
        {
            AddEnemy();
        }

        private void startButton_Click(object sender, RoutedEventArgs e)
        {
            StartGame();
        }

        private void StartGame()
        {
            human.IsHitTestVisible = true;
            humanCaptured = false;
            progressBar.Value = 0;
            startButton.Visibility = Visibility.Collapsed;
            playArea.Children.Clear();
            playArea.Children.Add(target);
            playArea.Children.Add(human);
            enemyTimer.Start();
            targetTimer.Start();
        }

        private void AddEnemy()
        {
            ContentControl enemy = new ContentControl();
            enemy.Template = Resources["EnemyTemplate"] as ControlTemplate;
            AnimateEnemy(enemy, 0, playArea.ActualWidth - 100, "(Canvas.Left)");
            AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 100),
                random.Next((int)playArea.ActualHeight - 100), "(Canvas.Top)");
            playArea.Children.Add(enemy);

            enemy.MouseEnter += enemy_MouseEnter;

        }

        void enemy_MouseEnter(object sender, MouseEventArgs e)
        {
            if (humanCaptured)
                EndTheGame();
        }

        private void AnimateEnemy(ContentControl enemy, double from, double to, string propertyToAnimate)
        {
            Storyboard storyboard = new Storyboard() { AutoReverse = true, RepeatBehavior = RepeatBehavior.Forever };
            DoubleAnimation animation = new DoubleAnimation()
            {
                From = from,
                To = to,
                Duration = new Duration(TimeSpan.FromSeconds(random.Next(4, 6))),
            };
            Storyboard.SetTarget(animation, enemy);
            Storyboard.SetTargetProperty(animation, new PropertyPath(propertyToAnimate));
            storyboard.Children.Add(animation);
            storyboard.Begin();
        }

        private void human_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if (enemyTimer.IsEnabled)
            {
                humanCaptured = true;
                human.IsHitTestVisible = false;
            }
        }

        private void target_MouseEnter(object sender, MouseEventArgs e)
        {
            progressBar.Value = 0;
            Canvas.SetLeft(target, random.Next(100, (int)playArea.ActualWidth - 100));
            Canvas.SetTop(target, random.Next(100, (int)playArea.ActualHeight - 100));
            Canvas.SetLeft(human, random.Next(100, (int)playArea.ActualWidth - 100));
            Canvas.SetTop(human, random.Next(100, (int)playArea.ActualHeight - 100));
            humanCaptured = false;
            human.IsHitTestVisible = true;
        }

        private void playArea_MouseMove(object sender, MouseEventArgs e)
        {
            if (humanCaptured)
            {
                Point pointerPosition = e.GetPosition(null);
                Point relativePosition = grid.TransformToVisual(playArea).Transform(pointerPosition);
                if ((Math.Abs(relativePosition.X - Canvas.GetLeft(human)) > human.ActualWidth * 3)
                    || (Math.Abs(relativePosition.Y - Canvas.GetTop(human)) > human.ActualHeight * 3))
                {
                    humanCaptured = false;
                    human.IsHitTestVisible = true;
                }
                {
                    Canvas.SetLeft(human, relativePosition.X - human.ActualWidth / 2);
                    Canvas.SetTop(human, relativePosition.Y - human.ActualHeight / 2);
                }
            }
        }

        private void playArea_MouseLeave(object sender, MouseEventArgs e)
        {
            if (humanCaptured)
                EndTheGame();
        }
    }
}

This post has been edited by Kiki G: 06 June 2014 - 08:55 AM

0

#2 User is offline   AndrewStellman 

  • Andrew Stellman
  • PipPipPipPipPipPipPipPipPipPipPip
  • Group: O'Reilly Author
  • Posts: 806
  • Joined: 08-October 08
  • Gender:Male
  • Location:Brooklyn, NY
  • Interests:Author of: "Head First C#", "Beautiful Teams", "Head First PMP", "Applied Software Project Management"

Posted 07 June 2014 - 06:55 AM

I pasted your code into Visual Studio, and it works perfectly for me! :) When I drag the human onto the target, the timer resets for me, and the game ends when I drag a human onto an alien or out of bounds, or when the timer elapses. I think you got this all correct. What are you expecting that isn't happening?
Andrew Stellman
Author, Head First C#
Building Better Software -- http://www.stellman-greene.com
0

#3 User is offline   GroovySu 

  • New Member
  • Pip
  • Group: Members
  • Posts: 1
  • Joined: 11-June 14

Posted 11 June 2014 - 11:54 AM

View PostAndrewStellman, on 07 June 2014 - 06:55 AM, said:

...
What are you expecting that isn't happening?


I'm wondering if you're making the same mistake I did: I didn't notice the human I'd coded for AGES because it's a tiny blop in the top left corner, to begin with. Took me a while to realise that's what I was looking at!
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users