O'Reilly Forums: Save The Humans - 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

#1 User is offline   Megziflips 

  • New Member
  • Pip
  • Group: Members
  • Posts: 3
  • Joined: 14-January 14

Posted 14 January 2014 - 02:07 PM

Okay, I am fairly new to programming in general,so I made a fresh start with your book.
So far it seems great but i seem to have a bit of issue.

I did all tasks up until where I have to run the game. It ran perfectly fine, but after i click start button I get some error saying:
"An unhandled win32 exception occured in Save the Humans.exe[3412]

And says something about a break in debugger and outputs the following code:


#pragma checksum "C:\Users\Megzi\Documents\Visual Studio 2012\Projects\Head First C#\Save the Humans\Save the Humans\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "720CAD59FF1DA6AFEF7ECF17F5E0D6EE"
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------


namespace Save_the_Humans
{
#if !DISABLE_XAML_GENERATED_MAIN
    public static class Program
    {
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        static void Main(string[] args)
        {
            global::Windows.UI.Xaml.Application.Start((p) => new App());
        }
    }
#endif

    partial class App : global::Windows.UI.Xaml.Application
    {
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        private bool _contentLoaded;

        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 4.0.0.0")]
        [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
        public void InitializeComponent()
        {
            if (_contentLoaded)
                return;

            _contentLoaded = true;
#if DEBUG && !DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT
            DebugSettings.BindingFailed += (sender, args) =>
            {
                global::System.Diagnostics.Debug.WriteLine(args.Message);
            };
#endif
#if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION
            UnhandledException += (sender, e) =>
            {
                if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
            };
#endif
        }
    }
}



Particularly, it highlights this:
global::System.Diagnostics.Debugger.Break();

Here is my own original code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
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;

using Windows.UI.Xaml.Media.Animation;

// The Basic Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234237

namespace Save_the_Humans
{
    /// <summary>
    /// A basic page that provides characteristics common to most applications.
    /// </summary>
    public sealed partial class MainPage : Save_the_Humans.Common.LayoutAwarePage
    {
        Random random = new Random();

        public MainPage()
        {
            this.InitializeComponent();
        }

        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
        }

        /// <summary>
        /// Preserves state associated with this page in case the application is suspended or the
        /// page is discarded from the navigation cache.  Values must conform to the serialization
        /// requirements of <see cref="SuspensionManager.SessionState"/>.
        /// </summary>
        /// <param name="pageState">An empty dictionary to be populated with serializable state.</param>
        protected override void SaveState(Dictionary<String, Object> pageState)
        {
        }

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


        }

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

        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, propertyToAnimate);
            storyboard.Children.Add(animation);
            storyboard.Begin();
        }
    }
}



And my XAML code:

<common:LayoutAwarePage
    x:Name="pageRoot"
    x:Class="Save_the_Humans.MainPage"
    DataContext="{Binding DefaultViewModel, RelativeSource={RelativeSource Self}}"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Save_the_Humans"
    xmlns:common="using:Save_the_Humans.Common"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Page.Resources>

        <!-- TODO: Delete this line if the key AppName is declared in App.xaml -->
        <x:String x:Key="AppName">Save the Humans</x:String>
        <ControlTemplate x:Key="EnemyTemplate" TargetType="ContentControl">
            <Grid>
                <Ellipse Fill="#FFF70404" Height="100" Stroke="Black" Width="100"/>
            </Grid>
        </ControlTemplate>
    </Page.Resources>

    <!--
        This grid acts as a root panel for the page that defines two rows:
        * Row 0 contains the back button and page title
        * Row 1 contains the rest of the page layout
    -->
    <Grid Style="{StaticResource LayoutRootStyle}">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="160"/>
            <ColumnDefinition/>
            <ColumnDefinition Width="160"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="140"/>
            <RowDefinition/>
            <RowDefinition Height="160"/>
        </Grid.RowDefinitions>

        <VisualStateManager.VisualStateGroups>
            <!-- Visual states reflect the application's view state -->
            <VisualStateGroup x:Name="ApplicationViewStates">
                <VisualState x:Name="FullScreenLandscape"/>
                <VisualState x:Name="Filled"/>
                <!-- The entire page respects the narrower 100-pixel margin convention for portrait -->
                <VisualState x:Name="FullScreenPortrait">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Style" Storyboard.TargetName="backButton">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource PortraitBackButtonStyle}"/>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
                <!-- The back button and title have different styles when snapped -->
                <VisualState x:Name="Snapped">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Style" Storyboard.TargetName="backButton">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource SnappedBackButtonStyle}"/>
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetProperty="Style" Storyboard.TargetName="pageTitle">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{StaticResource SnappedPageHeaderTextStyle}"/>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
        <!-- Back button and page title -->
        <Grid Grid.ColumnSpan="3">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>
            <Button x:Name="backButton" Click="GoBack" IsEnabled="{Binding Frame.CanGoBack, ElementName=pageRoot}" Style="{StaticResource BackButtonStyle}"/>
            <TextBlock x:Name="pageTitle" Grid.Column="1" 
				Text="{StaticResource AppName}" 
				Style="{StaticResource PageHeaderTextStyle}"/>
        </Grid>
        <Button x:Name="startButton" Content="Start!" 
			HorizontalAlignment="Center" Grid.Row="2" 
			VerticalAlignment="Center" Click="startButton_Click"/>
        <StackPanel Grid.Column="2" Orientation="Vertical" Grid.Row="2" VerticalAlignment="Center" HorizontalAlignment="Center">
            <TextBlock 
        		TextWrapping="Wrap" 
        		Text="Avoid These" 
        		Style="{StaticResource SubheaderTextStyle}" VerticalAlignment="Center" HorizontalAlignment="Center"/>
            <ContentControl Content="ContentControl" HorizontalAlignment="Center" VerticalAlignment="Center" Template="{StaticResource EnemyTemplate}"/>
        </StackPanel>
        <ProgressBar Grid.Column="1" Grid.Row="2" Height="20"/>
        <Canvas x:Name="playArea" Grid.Row="1" Grid.ColumnSpan="3">
            <Canvas.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="Black" Offset="0"/>
                    <GradientStop Color="#FF4A2283" Offset="1"/>
                </LinearGradientBrush>
            </Canvas.Background>
            <StackPanel x:Name="human" Orientation="Vertical">
                <Ellipse Fill="White" Height="10" Stroke="Black" Width="10"/>
                <Rectangle Fill="White" Height="25" Stroke="Black" Width="10"/>
            </StackPanel>
            <TextBlock x:Name="gameOverText" Canvas.Left="475" TextWrapping="Wrap" Text="Game Over" Canvas.Top="200" FontFamily="Arial Black" FontSize="100" FontWeight="Bold" FontStyle="Italic"/>
            <Rectangle x:Name="target" Height="50" Canvas.Left="305" Stroke="Black" Canvas.Top="310" Width="50" RenderTransformOrigin="0.5,0.5">
                <Rectangle.RenderTransform>
                    <CompositeTransform Rotation="45"/>
                </Rectangle.RenderTransform>
                <Rectangle.Fill>
                    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                        <GradientStop Color="Black" Offset="0"/>
                        <GradientStop Color="#FF098D15" Offset="0.875"/>
                    </LinearGradientBrush>
                </Rectangle.Fill>
            </Rectangle>
        </Canvas>

    </Grid>
</common:LayoutAwarePage>


Any help would be greatly appreciated.
And by the way, thanks for writing this book. So far seems great!!
0

#2 User is offline   AndrewStellman 

  • Andrew Stellman
  • PipPipPipPipPipPipPipPipPipPipPip
  • Group: O'Reilly Author
  • Posts: 756
  • 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 14 January 2014 - 05:54 PM

Nice job! You did great, just a very small typo:

AnimateEnemy(enemy, random.Next((int)playArea.ActualHeight - 100),
random
.Next((int)playArea.ActualHeight - 100), "(canvas.Top)");

The "c" in "(canvas.Top)" should be upper case. Once you fix that, your code should work just fine.

Andrew
Andrew Stellman
Author, Head First C#
Building Better Software -- http://www.stellman-greene.com
0

#3 User is offline   Megziflips 

  • New Member
  • Pip
  • Group: Members
  • Posts: 3
  • Joined: 14-January 14

Posted 15 January 2014 - 06:52 AM

WOW!
What a silly mistake on my path.
But you looked at all that long code and could easily tell where the error was. That seems almost all spiritual to me.
Hope to be able to do so with time.

But even more than a programmer, looking at how well laid out your book seems so far, you and Jennifer are a geniuses!
And you have made another fan out of me!

I sure would be looking at some of your books later on.

I'm still only in the starting stages and not the most trustworthy opinion but damn!
So far this book has been a gem!

Thanks loads!
Would get back to the forums when done with your book.
0

#4 User is offline   AndrewStellman 

  • Andrew Stellman
  • PipPipPipPipPipPipPipPipPipPipPip
  • Group: O'Reilly Author
  • Posts: 756
  • 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 16 January 2014 - 12:45 PM

Thank you -- that's really nice to hear!

As you write more code, you get better and better at reading code and seeing problems. I've talked to many different people who have found that as they progressed through the book they found that they got better and better at spotting missing parentheses and semicolons, capitalization problems, etc. Also, every good developer has horror stories about spending hours tracking down problems like this (my record is over eight hours for a misplaced comma).

I hope you enjoy the rest of the book!

Andrew


Andrew Stellman
Author, Head First C#
Building Better Software -- http://www.stellman-greene.com
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