Ce diaporama a bien été signalé.
Nous utilisons votre profil LinkedIn et vos données d’activité pour vous proposer des publicités personnalisées et pertinentes. Vous pouvez changer vos préférences de publicités à tout moment.

Ics4u dayplans

Daily Lesson plans for Grade 12 Computer Science

  • Identifiez-vous pour voir les commentaires

  • Soyez le premier à aimer ceci

Ics4u dayplans

  1. 1. ICS4U (2011-2012) COMPUTER PROGRAMMING/COMPUTER SCIENCE1.PROGRAMMING IN C# a) Introduction to C# - Using Visual Studio Express Edition 2008 E-Learning Unit 2 Activity 1,2 - intro to environment - using sample illustrate - opening/running/viewing code (design mode/code mode) - solution explorer window/design window/toolbox b) Intro to C# coding (optional) -Console App – ch03 (Welcome1/Welcome2) - includes ReadLine()/ discuss ConsoleWriteline()/Console.Write(); - Windows App – ch02 (ASimpleProgram) - includes labels/picturebox (no regular image control like vb) c) Creating You First Apps – Designing a User Interface (1) Labels, Textboxes, Buttons and Pictureboxes (use local resource) - coding simple events (use SaveAll) - chapter1 – VisualHelloWorld - note: F7 opens code window - include Console.Beep()/MessageBox.Show()/Exit Button -> this.close(); or Application.Exit - attaching different events to controls (click on lightening bolt) MouseHover - A detailed look at the Explorer Window in a windows app - Form1.cs -> Form1.Designer.cs/ Program.cs (contains main() ) - right click form1.cs in explorer window and rename (automatically changes prop name) - may need to modify contents when debugging due to adding rogue control and code - error occurs if code removed while control still there (2) More User Interface and Events - suggested C# prefixes for naming objects (see sheet) - more buttons(FormFun)–note form width/height/backcolor/demo setting background image prop (optional) - radionbuttons - using a groupbox (use hellod example from VB) - note: need to use Form1_Activated then init Rdo.Checked=false/Pic.Visible=false - adding images to a picturebox (diff betw local and proj resource-image stored in res dir .resx ) - take a look at folder contents of a solution including bin=>Radio Button Problem (optional)= > Extra Help Videos (01-csharp/02-csharp discusses tab order /03-csharp creating regions #region x #endregion) + See Intro Notes (cshtp2_02.pdf/csharpkidspart1) csharp_04 Creating a user interface/csharp_05 Handling events/csharp_06 setting properties (3) Scroll Bars and NumericUpDown E-Learning Unit 2 Activity 2,3 -Demo using scrollbars: note use of Convert.ToString(); - rgbColors (numeric up down) note: use of casting (int) nudRed.Value (4) Menus - Using a menu strip - do simple example with students changing colors (this.BackColor=Color.Red) - size -> this.WindowState=FormWindowState.Maximized (5) Working with multiple forms ( A brief intro – See Multiform) - adding new forms - right click project – add new item – windows form - .show/.close() - FrmTwo Two = new FrmTwo(); /Two.Show(); / this.Close(); - set opacity property of form (semi-transparent) - change the startup form (need to modify Program.cs -> Application.Run(new FrmOne()) Then demo BeforeAndAfterStartup d) Entering and Outputtin g Data (1) The Concept of Computer Storage - variables/data types (int/long/double/string/bool)/declaring a constant -> const double PI=3.14 - assignment statements (we do problem1/2) - using comments
  2. 2. - simple program -> int counter=3; MessageBox.Show(counter.ToString()); - scope of variables (local/public)=> videos (04csharp/csharp_07)=>QUIZ (short answer + practical) E-Learning Unit 2 Activity 3 (2) Mathematical Applications - arithmetic operators (Math.pow(x,2)/ % modulus/integer arithmetic (17/3) - casting (double) 5/2 vs (double) (5/2) - Examples (Win Apps) - savings ( note use of Convert.ToInt32) long-> Convert.ToInt64 - can also use int.Parse()/double.Parse() - average ( note use of vb style inputbox -> add reference to Microsoft.VisualBasic) ->in .NET - may not work on network run from c: - also note use of n t and casting (due to integer arithmetic) - Examples (Console) optional - simpleaddition - carpetexample - ageincrementer (note use of int.Parse()/double.Parse() ) - squareinput=> E-Learning Activity 3 Assignment #1 (Hand-in to drop box for practice)=> Mathematical Applications Problems (1-7) (Do first one with students)=> Case Problems 1=> Take up average prog + discuss drop box - Simple quotient – remainder example (recall feet and inches problem from grade 10) - include n t for output - Sample Application (pricequote) –Venus Motor Sales (do with students) - converting numbers to formatted strings x.ToString(“c”) currency x.ToString(“n2”) two decimal places RECORDED LESSON custom formatting x.ToString(“###.##”) - tab order (view) e) Selection-Repetition E-Learning Unit 2 Activity 4 (1) Selective Processing Intro - GuessNumber (also note: != doesn’t equal / = = /&& ||) - redo ticket example from grade 10 - SeeSharpQuiz - ProvincePicker (switch example) - Math applications (determine whether a number is even or odd) - selective processing problem #4 (ccf) - another example (InvoiceTotal) - decimal is a fixed pt variable type (takes up more memory 98 bits but no rounding error) - double is a floating pt variable type(store big range of numbers,smaller mem 64 bits rounding errors) Sample Applications - includes use of checkboxes and radiobuttons - sandwich - tictactoe (note use of textboxes from black lines and click event with offscreen btnMark.PerformClick() )=> E-Learning H.W. Assignment (Use Dropbox) Problems 1,2,3 (Problem sheet #5,6)
  3. 3. (2) User Defined Dialogs E-Learning Unit 2 Activity 5 - SimpleDialog - messageboxes (DialogResult r = MessageBox.Show() / if (r==DialogResult.No) - OpeningandClosingWindows (optional) * CustomDialogs - using class properties ** get { return TxtBox.Text;} in public string UserName - setting DialogResult to OK/Cancel for button (also set Form prop AcceptButton/CancelButton - using the ShowDialog method instead of Show - form is displayed modally - user clicks OK/Cancel and form closes immediately without having to write and code FrmDialog nameDialog = new FrmDialog if (nameDialog.ShowDialog()== DialogResult.OK) RECORDED LESSON vs DialogResult r = nameDialog.ShowDialog() If (r==DialogResult.OK) - Monitoring keystrokes using the Keypress event - KeypressDemo  Mainform/Patient Info Form + include keystroke monitoring (PatientInfo)=> Recap/Extension (NewPatientInfo) *** set {TxtBox.Text=value;}=> Minor Assignment (program allows user to enter name + 4 marks in dialog and calculate average) E-Learning Unit 2 Activity 6 (3) Repetitive Processing Counter controlled repetition (while) - these are console apps - add Console.ReadLine() to last line so display remains on screen - counter (experiment with different combinations – decrement/increment --/++/+=/-= - accumulator User Controlled repetition (while/do while) - UserControlledRepetition For loops - for (experiment with different combinations) - nestedloop Sample applications (RepApps) *** - area of circle (note Math.PI) - conversion (while) -> f=c*9/5+32 (note use of Environment.NewLine instead of n) - sum(for) - combo (for) EvenOdd User controlled repetition Revisited (with custom dialog) / AgeHeight - note: (int) e.KeyChar==8 Combo Boxes and List Boxes - ComboBoxDemo (Items property – collections) + SelectedIndex property - Demo use of List box to display large lists - ListBoxExample (optional)=> Problems=> Possible Enrichment **** payment problem ********* f) Problem Solving Techniques E-Learning Unit 2 Activity 7,8,9
  4. 4. (1) The five steps in creating programs - define problem - design solution (user interface/form settings/flowcharts of events usingSmartdw) - go through Activity 7/8 content + Activity 8 Assign #2 (Flowchart Drag and Drop) - code solution - error handling and debugging - types of errors (syntax/run-time/logic) - debugging tools and techniques (run from c: drive -> use UserControlledRep) - in Rep folder - stepping (F11) then float cursor over var to determine current values - setting brkpts / Debug – Windows - Local - make need to run from c: drive - if you get error -> source does not belong to project begin debugged - delete bin and obj directories/restart C#/rebuild - documentation (variable dictionaries/program comments)-> demo by adding to Sandwich prg (in Sel-Rep) (2) Methods Intro - all subprograms, functions or procedures are called methods in C# - Event handler methods vs user defined methods - Why use -> songmethod (demo + then students use this version to create method ) - Using refactoring (right click highlighted code and extract method) Flowcharting methods Types of methods (private/public) - void type - type return - with parameters Examples - simplemethods (windows app) - counter (console app – note use of static) - Extension (Optional) - Having an event execute a method - click lightning bolt in properties, find event you are interested in then type in method name - C# generates a method with name you specify - it is possible to have one event handler respond to the same event on many different controls - Simple Example - 3 buttons all using the same method - Demo (RegForm) - look at checkbox event CheckedChanged and RadioButtons event Click - both point to ComputeCost_Changed - The Sender Concept - The list parameter pssed to any event handler is an object called sender - This is actually the control that fired the event. - By casting it to the appropriate object type you can interact with it just as you would any other control - Demo (RadioButtons)=> Methods Assignment (User defined methods) do first question with students (group assignment)
  5. 5. => Review (Quiz) then MathGame (3) Simple file concepts (Reading and Writing a Text File) E-Learning Unit 2 Activity 10 - NewSimpleTextFileDemo - note: need to add using System.IO - note: when using Application.StartupPath + @ “ filename” -> file should be in Debug folder - CreditCardAppAssignment: Demo several new controls/APIs unique to C# *** E-Learning Unit 2 Activity 11 - linklabels - tabcontrol possible ideas - datetimepicker - treeview - Examples - MoreControlsDemo - Speech API (SpeechDemo) – you add a reference to MS speech library (COM reference) ** to add more controls to the toolbar -> right click the General Area at the bottom and choose items) ** WORK PERIOD + REVIEW PERIOD REVIEW AND EXTENSION TEST=> AgeHeight (in Repetition folder) * focus on dummyproofing and error handling=> Show and Tell g) Handling Exceptions E-Learning Unit 3 Activity 1 (1) What is an Exception - DivisionProblem (step through prg) - note error when a string is entered “Format Exception was unhandled” (2) Exception Handling - try/catch/finally - DivisionFix - uses FormatException - StructuredExceptionHandling - DivideByZeroException - IOException - exception handling text files - FileNotFoundException/IOException (3) The Error Provider Control (optional) - note the use of validating and validated events - can’t exit until proper number is entered=> VideoTutorial (Csharp20 –Handling Exceptions) First 7 minutes=> Work on New Controls Assignment=> Prep for Array Lessons – watch video csharp15 Arrays (First 9 minutes)
  6. 6. => Show and Tell h) Arrays E-Learning Unit 4 Activity 1,2,3 (1) One Dimensional Arrays Intro Concepts - students watch video csharp15 – Arrays – first 9 minutes - SimpleArrayIntro - demos declaring, storing calculating and displaying arrays - also features methods with array parameters Examples - ArrayLengthProperty - ArrayUsingForEach - ForEachCalc/MultiLineTextBox (optional) Applications - SimpleArrayIntermediate -> ArrayIntermediate (see comments in program) - Note use of array and variable passing by ref - Further discussion of passing by ref and value -> passarray Advanced Applications - Array counters (ArrayCounter) -> do pre-amble here to highlight importance and efficiency of array counters - Review (StudentPoll) (optional) Reading de-limited text files using the split command - intro string f = “Ed Koop”; string [ ] n =f.split (‘ ‘); string fn = n[0]; - File application (DelimitedTextFileReading)=> Problem OneDimensionalArray Exercise Sheet/OneDimensionalArray Problem (Marks)/1D Array Review Sheet ***=> Show and Tell/Take up Review Sheet (selected problems) (2) Two dimensional arrays E-Learning Unit 4 Activity 4 - Intro/Example case - Example (TwoDIntro) - declaring - storing - displaying - calculating Application (SimpleQuizScore/QuizScore) - incorporates titles in 1 d array - uses 1d array counters=> Problem - Supermarket (optional) (3) Advanced Array Applications E-Learning Unit 4 Activity 5 - Survey Analysis (2d array counters - DataAnalysis) - questionnaire problem RECORDED LESSON - census problem=> Assignment – Sales Analysis Problem Note: Data File Format (Use DelimitedTextFileReading program) WORK PERIOD (4) Three Dimensional Arrays E-Learning Unit 4 Activity 6 - introduction RECORDED LESSON - parkingticketproblem - note the use of BtnDisplay.PerformClick()  this re-executes (simulates you pressing) the Display Button Multidimensional Array Test i) MATHEMATICAL PROGRAMMING E-Learning Unit 5 Activity 1 (1) Intro RECORDED LESSON
  7. 7. - BuiltInMathFunctions - Simple Application - AverageDiff (note: ave=total/(score.Length-1) (2) The hidden pitfalls of computer arithmetic - ComputerMathPitfalls - the tolerance expression (abs() function)=> Problems (do #1 with students + collaborate on tolerance expressions for remaining problems)=> Take up problems (3) GCD - greatest common divisor E-Learning Unit 5 Activity 2 - definition - the Euclidean algorithm RECORDED LESSON - program development (GCD)=> Assignment (Problems 1,2) WORK PERIOD
  8. 8. 15) j) Probabilistic Simulations E-Learning Unit 6 Activity 1 (1) Intro (Generating Random Numbers sheet) RECORDED LESSON - using the Random class - Random r = new Random() - Random r = new (Random(seed)) where seed = DateTime.Now.Millisecond - three formats i. Next(7) 0-6 ii. Next(1,7) 1-6 iii. Next(6)+1 iv. NextDouble() a random double between 0-1 - Demo (RandomNumberIntro) - Your Turn #1 - Programming Problems 1,2,3 (optional) (2) Review-Extension (Computer Simulations Sheet) - MoreRandomNumbers - coin toss problem - dice simulation - dice counter - Sample games - GuessNumber - MathGame - CardWars (optional) - Gambler Problem (do with students) (3) Sample applications - pinball=> Shooting gallery problem (shootgallery) + Dart Game Problem=> Take up problems (shooting gallery) - More Simulations E-Learning Unit 6 Activity 2 - Driving school problem=> Assignment- Tennis Problem (4) Random selection without duplication E-Learning Unit 6 Activity 3 - intro -> awarding prizes (note) - NFL helmets problem (helmets)=> Casino problem (5) Building a discrete random distribution - intro example (ballsinabag) E-Learning Unit 6 Activity 4 - Extension (dartboard) - creating a random number generator using a static class - does not need to be instantiated PROBABLISTIC SIMULATIONS TEST
  9. 9. k) Object Oriented Programming E-Learning Unit 7 Activity 1 (1) Intro -terminology (class/objects) What is a class/object **** - a description of a kind of object - act a templates from which similar objects called instances are created - when you want to create an object the new operator is used with the class name or constructor (which have the same name as the class) - creating an object is called instantiation/ every object is an instance of a class - inheritance - a way of incorporating all the methods and fields from one class into another - eg. part time employee class (inherits from employee class) - then adds new fields to extend the employee class - Simple example -> buttons are objects of the button class in the toolbox (2) Creating your own class and using it (see car class in csharpoop.pdf) - FirstOOPdemo - Class (right click project in explorer window/add new item/class) note: addition of System.Windows.Form needed to use MessageBox.Show - Fields (private) - Properties (get/set) public - Methods - Constructors (3) Examples - Windows app (calculator) -BoxExample (work through with students) **=> video 06csharp1 + Lesson 11 worksheet (oopactivity1.pdf) (4) Intermediate OOP’s E-Learning Unit 7 Activity 2 - use FirstOPPdemo + new demos to illustrate concepts RECORDED LESSON - Encapsulation - hiding details of an object from other parts of a program. The object can be used only through its access methods, which are written to keep the object consistent and secure. - try to access c.make and note error then modify and add code to FrmTester (see below) - EncapsulationDemo - Static methods in classes - don’t need to make instance of class to use - NewPatientInfoRevisited (illustrates how to create a “global” variable using a static class) - GlobalClass.cs - Method overloading - two methods of a class have the same name but diff par list - MethodOverLoad - Inheritance (MINIVAN class – see video below) - IntermediateOPPdemo - also see subclassing - Example - carpet (optional)video (06csharp2 ) + Lesson 12 worksheet (including exercise to create class) oopactivity2.pdfwatch video for solutionpublic int Year{set { if (value > 2010) { year =2010;} else { year=value;} }}=> Take up Worksheet=> Recap Commission (optional)
  10. 10. (5) Using Structures E-Learning Unit 7 Activity 3 - a set of values that can be referenced collectively - differ from an array in that elements of the structure can be of different types - similar to classes in that they represent data structures - Example - CarInventory (note use of Image.FromFile()) - use trackbar control with Minimum set to 1Minor Assignment => create a team profile program mirroring the CarInventory example and incorporating structures. WORK PERIOD/REVIEW=> OOP Quiz (last 30 minutes)
  11. 11. l) Working with Strings E-Learning Unit 8 Activity 1,2 (1) Some properties and methods of the string class - .length - Convert.ToString() /.ToString() RECORDED LESSON - .StartsWith() - .EndsWith() - .IndexOf(‘c’) - . Substring( - )/ Substring( - , - ) - .ToUpper / .ToLower / .Trim( ) / Replace ( - , -) - char ch = (char) 65 - int code = (int) ‘B’ Examples - StringIntro - Substring - Indexof - Replace (2) Sample applications - Letter and word counting (LetterCount) (3) String accumulators using Concatentation - StringAccumulators - We do Problems 2,3 (4) Number Problems - example (NumberProblems) - problem 4=> Problems 5,6 (MoreNumberProblems) (5) Code Validations E-Learning Unit 8 Activity 3 -SIN (SINProblem) RECORDED LESSON=> credit cardp roblem=> Product codeAdditional resources: www.highprogrammer.com/alan/numbers (6) Other Applications - ISBN (ISBNProblem) E-Learning Unit 8 Activity 4 - Note: use of Convert.ToChar for string/char comparison (7) Searching and Substring Extracting - Problem 1 (SubstringExtracting)=> Problem 2,3 (8) Cryptography E-Learning Unit 8 Activity 5 - Caesar Code (CaesarCode)= Problem 1,2 (shifted Caesar) STRING TEST
  12. 12. m) Recursion E-Learning Unit 9 Activity 1 (1) Intro (RecursionIntroNote) RECORDED LESSON - definition - the 3 criteria - Factorial example /Trace using telephone call analogy (emphasize returning from call) (2) Your Turn - TriangleNumberProblem (3) The Euclidean Algorithm - GCD=> Intro Recursion Problems (Do with students using Factorial Problem as base) + slideshows (Java-Recursion/WrightRecursion) (5) Non-Linear Recursion E-Learning Unit 9 Activity 2 - Intro Problems - PathLength RECORDED LESSON - FloodFill - CountingShapes (optional) - FillBlob (optional) -WordPuzzle - Solving Mazes using Backtracking techniques - Navigate + trace - Practical Application (CheaptestPath)=> Assignment (RecursiveMaze Problem) WORK PERIOD
  13. 13. n) SORTING TECHNIQUES (1) Review and Extension - Intro (SortingIntroduction) E-Learning Unit 10 Activity 1 - sorting 2/3 numbers without arrays RECORDED LESSON - sorting with arrays using the replacement technique - The Bubble Sort - description ( math.hws.edu/TMCM/java/labs/xSortLabLab.html) - program development/program - Other Sorting Techniques (IntermediateSortingA) - sorting strings (note use of CompareTo() ) - using a swap method - modified bubble sort - exchange sort - The Shell Sort - intro - Other Sorting Techniques using Classes (IntermediateSortingB) - The Selection Sort=> Assignment (Median Problem->Median WORK PERIOD=Extension: (Quicksort) - intro with XsortLab E-Learning Unit 10 Activity 2 - quicksort_anim.exe/qsort_anim.exe - using the sort methods from the Array class (Array.Sort(w)) RECORDED LESSON (2) Pointer Sorting - introduction (PointerSort) - sorting multi-field records without pointers - pointer sort method - using exchange/Shell sort - exercise (ageheight.) - multi-field sorts (using 2d arrays ->TwoDSort) (3) Sorting using Struct definitions or a class (using an array of objects) - StructSort (note use of split command and different delimiters) - ArrayOfObjects=>Assignment (Snowfall problem -> Snowfall.) WORK PERIOD o) SEARCHING TECHNIQUES (1) Sequential search E-Learning Unit 10 Activity 3 - Application (album lending program - Albums) must run from c: drive RECORDED LESSON - incorporate a Search class (uses static methods) - when reading in data use split command for a comma delimited file - when writing back to disk use: w.Write(field); w.Write(“,”); w.WriteLine(lastfield); - display album status on a second form – use properties with set {TxtDisplay.Text=value;} (2) Binary search (Albums) - intro - visual demo (binary.exe) - program development - Extension (recursive binary search)=>Binary Search Quiz (3) Applications E-Learning Unit 10 Activity 4 - Table lookup (inventory) - www.countrycallingcodes.comAssignment => Distance Table problem WORK PERIOD p) ADVANCED FILE HANDLING E-Learning Unit 11 Activity 1 (1) Updating Sequential Files - changes/deletions/additions (unordered lists ->albumsupdating)
  14. 14. - Extension – using a Data Structure - ArrayLists (note .RemoveAt(rec#) /.Count ) -ArrayLIstExamples - note use of -> foreach/.Contains(r)/.Remove(r) - StackIntro (just do base conversion) => Read through “Arrays and Collections” (Chapter 5) in Data Structures folder (optional enrichment) (2) Extension of Sequential files - Using Common Dialogs - CommonDialogIntro/CommonDialogsExample - if (openFileDialog1.ShowDialog() ==DialogResult.OK) OR DialogResult x = openFileDialog1.ShowDialog() if (x==DialogResult.OK) - may be a problem at school when creating programs on H: - security issue with certain file access actions - may need to create files on C: drive - setting the filter for the openDialog box - DisplayPictures (note use of FilterIndex 1-2)/ HowToCommonDialogs (optional) - AlbumsUpdatingWithCommonDialogs (uses open and save dialogs) (3) Sample Applications E-Learning Unit 11 Activity 2 - albumslistviewfinal - has user-defined tool strip with new file button/status strip - incorporates error handling (try/catch and basic flags) - highlight use of Listview (view property set to DETAILS)Assignment => - possible topics -> library lending/sports uniforms (each team diff file) - incorporates searching /updates/error handling/common dialogs/ possibly incorporate tab control/trackbar - Demo student solutions (4) Creating a Relational Database Using SQL Server Express and Manipulating it using C# (OPTONAL see Unit 4-SQL) - Intro - sql/access vs text files (simultaneous access) - flat file vs relational db - Contacts (Head First Chapter 1 pg 18-40 single table) E-Learning Unit 11 Activity 3 - .NET Visual Objects (Form objects) RECORDED LESSON - Data Storage ( data stored in a table in a SQL Server Express DB) - Visual Studio can generate code to connect a form to a DB but you need to have the DB in place before generating that code - note: nvarchar is Unicode variable length character string - Next you diagram your data (this describes your tables and is used to auto-generatecode to work with your DB - .NET Database Objects (a separate data layer that interacts with DB) - connecting your form to your DB objects with a datasource - now you can add DB driven controls to your form=> You do Absolute Beginner Series Videos SQL (introduces RDB – prep for next lesson) - Car Tracker (Build a Program Now Chapter 8 multi-table) RECORDED LESSON - add multiple tables with primary keys then create relationships between tables using db diagram - databinding - creating a dataset (in data source window add new data source selecting all the tables) - make sure form is active - in data source window select Listing node and choice Details view (drag onto form) - if not in view activate from data menu - data bind with domain tables - select table from datasource and drag onto form surface over combo box intell data bind - combo box is now populated with all the values from the table not simply one row - look at smart tag - adding queries using Dataset Designer then query builder (in data source rght click dataset then req table adapter - binding new queries to controls on form or whole form (click smart tag in adapter)=> You do Absolute Beginners Series Videos Databinding - Workers (Free C# Tutorials – demo only ) - hand coding db and C# interactions - making connections/datasets and data adapters/displaying and navigating through data/updating WORK PERIOD WORK PERIOD
  15. 15. q) Drawing Graphics and Building Games (1) Introduction to the Graphics Class E-Learning Unit 12 Activity 1 - graphics coordinates RECORDED LESSON Work thru simple example FIRST with students before going thru demos - Using the Form Paint Method (GraphicsClassIntro1) instantiating a graphics object (Graphics g =e.Graphics / Graphics g = this.CreateGraphics() ) - Font - SolidBrush/Brushes - DrawString - Pen - DrawLine/this.Width/this.Height/ ClientSize.Width/ClientSize.Height/ClientRectangle - DrawRectangle/FillRectangle - DrawEllipse - FillEllipse - Loading images from a file (Image.FromFile)/DrawImage - StartUpPath not necessary if all images are in Debug folder (this is the default path) - Dispose - Using a Panel Control (GraphicsClassIntro2) - panel1.CreateGraphic()/this.CreateGrahics() if using a form - using panel.Clear(); - pens.Color (1 pixel wide pens) - using Color.FromArgb(alpha,r,g,b) + demo (RGBColors) alpha 0 invisible 255 solid - using width/height/visibility (can create multiple panels and access simulatenously also layer ) - Scroll Panels (Scrolling) - panel control with autoscroll true and then picturebox control added to panel - set sizemode to autosize to activate scrollbars - Dice vs DiceRoll Problem note StartupPath can use "Dice or @"Dice - Review (ComboBoxGraphics) (optional) (2) Bar Charts - scaling concept - Examples (Barchart)=> Review (Csharp2-graphics.ppt)=> Minor Assignment (Checkerboard Problem)-> CheckerBoard (think of this problem in terms of (x,y) for loops not rows,cols )=> ClassGraphics (uses classes for graphical images) (3) Mouse Events (Grade 11 Review) E-Learning Unit 12 Activity 2 - Intro Examples RECORDED LESSON - MouseMoveIntro1(change g.DrawEllipse(mypen,e.X-7,e.Y-7,15,15) - MouseMoveIntro2 - includes MouseEnter/MouseLeave/MouseMove (e.X,e.Y)/MouseDown (e.Button) - SimpleHouse (note the use of the Point class and FillPolygon) - Csharp-Draw -> note use of ArrayList - Simple Application - MouseMove (simulated dragging) - includes Rectange class (which is used within FillRectangle) - MouseUp - .Top/.Left properties of a control - discuss adjustment -> e.y-pic.Height/2 and e.x-pic.Width/2 - MouseProblem - Sample Application - blackboard - comment out xLast/yLast lines in MouseMove and observe effects - updatedBlackboard - has option to set pen width - uses up/down and add option (combo) to set background color of blackboard - Drag and Drop (text/graphics) (New Grade 12 material) - DragDropIntro - AllowDragDrop can be set for the form and text boxes right in the properties - AllowDragDrop must be set in code for pictureboxesH.W. Assignment => Design a small program to demonstrate a drag drop application (4) Animation - Timers - intro (TimersIntro)
  16. 16. - Array of Images (using the Image class) - intro (ArrayOfImagesDemo) -> placing images to animate on form - large arrays (LogoAnimator) -> loading images from files to animate in Form_Load - illustrate extracting frames of an animated GIF using Animation Shop - Loading animated GIF’s automatically into a picturebox (optional) - The downside to this method is that you as the programmer have no control over the FPS (frames per second) of the animation or in the way in which it loops. - Drawing your own animations - FlipBook - EyeAnimation (note forward and reverse animation) - Sample Applications - DiceRollApplication/ SlotMachine Using Threads - FadingForm Animation Basics - using .Top/.Left (MovingFlipBook) - note use of 2 timers and wall checking conditions (this.Width) - experiment with vertical /diagonal movement - check for left/right and top/bottom wall hit (could use ClientSize.Height but image bounding prob) - disappearance/reappearance (PicPlayer.Left = -PicPlayer.Width) - bouncing off the wall (use dir=10/dir =-dir and PicPlayer+=dir) in declarations section .left/.top - RocketRace - using DrawImage() - intro (DrawImageAnimationIntro) - make sure to set picturebox sizemode to autosize - change background to green and observe problem - make image transparent using GIFCON (gif only)/Fireworks - note key to animation -> g.Clear(panel1.BackColor) comment out and observe results - Again experiment with - vertical, horizontal movement - border checking/ border disappearance (scroll effect) - bouncing (Bouncing) - Image Erasure Technique (ImageErasure) - Why ? g.Clear(panel1.BackColor) vs FillRectange() - reduce the size of the FillRectangle and observe results RECORDED LESSON=> Problem - Modify MovingFlipBook so that it animates using the ImageErasure technique - you will need to convert images to transparent GIFs E-Learning Unit 12 Activity 3 - solution (DrawImageMovingFlipBook) Collision Detection and Keyboard Events RECORDED LESSON - looking at the 4 requirements for collision - demo (CollisionDetectionDemo) KeyBoard Events - control must have focus to receive a keyboard event (panel cannot have focus must set focus on form in Frm_Load ) - to detect keyboard events you need to set the forms KeyPreview to true (in properties) - The KeyDown Event of Form (KeyBoardDetectionDemo) - the property e.Keycode is used to determine which key is press down - Keys.Right/Keys.Left - FullyAnimatedKeyBoardDetection/FullAnimKeyBrdDetGrapBkg - no pictureboxes used, everything is an image object, also using multi-colored bkg Sound Effects - playing sounds - SoundDemo1 - need -> using System.Media/ add the Windows Media Player Control (COMcomponent) - right click General/Items - Load() stalls code until all audio loaded into mem/LoadAsync() loads on another thread - SoundDemo2 (uses OpenFileDialog) Sample Game (BeachBalls)/BeachBallsImageArray/BeachBallsImageArrayBkg (only fully explain lastexample)
  17. 17. 16) (5) Advanced Graphics and Animation E-Learning Unit 12, Activity 4 - DoubleBuffering RECORDED LESSON - Intro - using SetStyle to double buffer (note placement in public Frm_) - drawing is performed in a temporary off screen image - after it completes the result is output to the screen - double buffering reduces flicker caused by redrawing of controls - only works for Paint event on component specified - can work on a Panel also – but need to create a new class (see DynaGraphics) - Examples - Basic Animations - Animation1 (remove double buffering lines and observe effect) - note use of Using System.Drawing.Drawing2D - note use of Invalidate() – forces a repaint (comment out observe) - note this.CreateGraphics does not work here use e.Graphic - Animation2 (multi-frame animation) - Animation3 (keyboard movement + sound) - Scrolling - note use of this.DoubleBuffered=true Form is 300 x 300 (each squareis one tile image of 100 x 100) Colored area is all you see(0-300x0-300) but off screen goes from –100 to 300 The program actually draws a larger image For (int i=-100; i<400;I+=100) For (int j=-100;j<400;j+=100) g.DrawImage(background, x + i, y+j); - stretch out form to get a peek behind the scenes - comment if statements in DrawStuff() and observe results - Mouse Movement - Mouse - note use of : this.DoubleBuffered=true; (New with VC#2005) - note: use of timer for MouseDown (explosion) -also note use of clientSize.Width and Height - DynaGraphics - double buffering on a panel - Game Development - The Basic Game Loop E-Learning Unit 12 Activity 5 - While (game is running) Check for input (key/mouse) Update all objects in the game (position) Draw all the objects in the game Refresh the screen (force a paint -> this.Invalidate()) - Sample Games (note use of Environment.TickCount) - BabyGameKybrdVersion1/BabyGameKybrdVersion2/BabyGameMouseVersion - SpaceShooterGame (note: use of ClientSize.Width/ClientSize.Height)
  18. 18. (6) Using XNA 3.1 Game Studio Express To Create 2D Games E-Learning Unit 12 Activity 6 RECORDED LESSON - Intro (Using XNA101 Lesson 3) work through examples similar to Lessons 3-6 - starting XNA - creating a new project (note: ContentManager(Services,"Content") ) - can be used to pt to content folder in solution explorer - in XNA 3.1 content folder automatically created now - create graphics , sound (put actual wav in there) and font folders - loading assets into solution explorer (Add Existing Item ...use a transparent png) - XNA content pipeline does not support .gif - if using a transparent gif must convert to png (trim then use FW PNG8) - Declare SpriteBatch and Texture2D objects (spriteBatch and spriteTexture) - In LoadGraphicsContent() spriteBatch = new SpriteBatch(this.graphics.GraphicsDevice); spriteTexture = content.Load<Texture2D>("graphicsimage"); - in XNA 3.1 (@"graphicsimage") - in the Draw() method - spriteBatch.Begin(); spriteBatch.Draw(spriteTexture,new Vector2(0f,0f),ColorWhite); spriteBatch.End(); - Lesson 3 (static img)/Lesson 4 (2 static img)/Lesson 5 (1 moving img)/Lesson 6 (bouncing) - add sound to Lesson 6 (note: for sound you must use the XACT tool) - see MS Beginners Guide to XNA (Build a 3d game - Section 8) - in XNA 3.1 no need for tool , use SoundEffect and Song Class - Drawing Text (adding a Sprite Font/Using DrawString)=> XNA101 (2d Lessons 3-15) - BigGreenHeadDemos (Case Study) RECORDED LESSON - a progression of programs from static images to animated objects - note in BigGreenHead8 sprite scaling (adding a bkg using Rectangle obj in Draw) - note in BigGreenHead9 Color(r,g,b,opacity) (version 10 missing sound –copy from V11) - note in BigGreenHead11 use of arry of objects and foreach=> Continue going through XNA101 Lessons=> Review/Extension (KickingBaby1) – an array of Texture2D/also note Update() problem and use ofgameTime.ElapsedTime.TotalMilliSeconds - demo how to convert sound code to XNA 3.1 SoundEffect class. Not possible for Song class – must be pure XNA 3.1 - More About Sprites - creating a 2D sprite (CreatingA2DSprite) -> in SimpleSprites folder -introduces keyboard input checking and new format SpriteBatch.Draw() - used for extracting images from a sprite strip - MouseXNA/ Fading technique (Fading) (in SimpleSprites folder) Optional - Creating a Simple Game - MyFirstGameUpdated (XNA version of SpaceShooterGame) - note use of Rectangle collision technique/setting of Window Title - In XNA 3.1 you add bkg music using Song class and MediaPlayer (use mp3)=> MS Beg Guide to XNA (DVD)=> Recap/Extension (changing window size/full screen mode/scrolling – ScrollingA2Dbackground/other scrolling techniques) - Creating a 2D Shooter Game (WindowGame1) -> in ccdemos-> WindowsGame2dShooter folder - Intro (Based on MS Beg Guide to XNA) - creating a game object for cannon - changing rotation angle with input/calling SpriteBatch.Draw with rotation - Shoot cannonballs - expand game object class/create and fill game object arm - update arry to move ball/ input to fire cannon balls- contain cannonball/ drawcannonballs - Add enemies- crt fill game obj arry/ upd arry move enemy / crt rand respawn condition/drwenemies - Create collision check in update - Draw Score - add FontDescriptor to solution/ keep score variable, tie to collision/ usingDrawString() - Distributing your game (Build/Publish) (See Other Demos/Sample Games/GameStateManagement) RECORDED LESSON Major Game Assignment WORK PERIOD WORK PERIOD WORK PERIOD
  19. 19. WORK PERIOD2. FLASH CS4– ACTIONSCRIPTING AS3 E-Learning Unit 13 Activity 1 (a) Review (1) Introduction (New CS4 Windows->WorkSpace->choose Essentials or Classic) (2) Drawing Basics - anything you draw eats away at everything else/use groups to avoid (3) Text Basics (three types static/input/dynamic) *CS4 Apply a Filter (prop panel/click folder to add filter) (4) Layers (5) Symbols and Instances (F11 library) - types (movie/button) - importing images/importing images to library (6) Animation Basics - timeline/keyframe F6 /blank keyframe F7 /frame F5  - Frame by Frame (keyframetext.fla/faceframebyframe.fla) – scrubbing/onion skinning - importing successive gif’s (animated GIF folder) - Sound (must be added to a keyframe/some sounds in common library/some sounds in Bttns folder)=>brushmodes.mov/morepen.mov (7) Tweening - Motion vs Shape Tweening (handout) E-Learning Unit 13 Activity 2 - Motion tweening RECORDED LESSON - CS4 Classic/ right click on start obj then choose tween and move object to new location) - Intro Example - skateboarder.fla - use imported image (take from library) - uses a second layer - note use of adding Frame (F5) to bkg layer to main persistence - motion tweening text - demo explodefinal.fla then do with students - type student name in text box - modify -> break apart -> distribute to layers (Timeline) - convert each letter to a symbol (allows you to execute more effects) - set keyframes at 20 & 40 at 40 have letters off screen rotatedscaled,alpha 0 - set motion tween – auto rotate - Shape tweening - basic intro (shapecircle.fla) - xboardfinal.fla (demo this) and do similar ex with students – need to use onion skinning - students then use xboard.fla to perform simple text tween - only need to break apart once - ** note ** to break apart a group of letters - must first break apart into text block and then - break apart again into shapes - Other Demos - eyeTween.fla - Animating Gradients (animatedGradientFinal from HOT folder) - demo then do with students using animatedGradient.fla) - note broken apart text (can only apply gradient to a shape) - use paint bucket tool with grey sphere gradient (8) Advanced Animation using Layers - motion guide layers (CS4 classic motion guide/basic guide now standard as part of Tween) - see www.kirupa.com/developer - See Motion Tweens in Flash CS4 - bouncingball.fla (make ball a symbol/add motion guide layer/motion tween ball) - right click current ball layer – new second layer made automatically - other examples (just demo) - motionguide.fla/multipleguides.fla/orientguide.fla - note use of orient to path in motion tween in orientguide.fla - orient_to_path_finished.fla (in AS3-FlashCS4 MissingCD) - mask layers - ccspottext.fla -> set masked layer - add mask layer above (rght click) uses motion tween for mask - tweenedshape.fla (uses shape tween for masking)=> Window view Problem
  20. 20. => Review/Extension – Using Motion presets (adjacent to properties/just choose obj to apply to) (9) Movie Clips E-Learning Unit 13 Activity 3 - Animating using movie clips (rotatingwheel.fla) - first make instance of wheel, this puts shape into library - then make movie instance of same wheel and name it rotatingwheel - this now puts symbol into library we can now motion tween - double click to edit (motion tween in new timeline) - tweening within tweens (tween.fla) - CS4 rotating movieclips in 3D space - in tools panel (AS3) - import graphic -> convert to MC - click on 3d rotation tool – try different rotations - bridge.fla (AS3-FlashCS4MissingCD) - CS4 (Bone Draw Tool) - each part of bone structure must be a movie clip/click bone tool to activ then back to pter to move - chain_links_finished.fla/robot_begin.fla (AS3-FlashCS4MissingCD) (10) Buttons E-Learning Unit 13 Activity 4 - Buttons basics RECORDED LESSON - intro (newsimplebutton) – note: text popup and sound - animated buttons (animatedhome.fla) - use movie clip symbol technique (from previous lesson) for over state - add rotation - just demo surprisebutton.fla - image maps (invisible buttons) - see www.cbtcafe.com for good demo - use two layers – button layer has no up button (do simple example) - drag to over temporarily - inside button also uses two layers where 2nd layer adds hit state - drag from over - sample application (invisiblebuttonfinal.fla)=> flash-creations.com + www.webwasp.co.uk/tutorials.index.php (b) The Next Step ActionScripting AS3 E-Learning Unit 14Activity 1 (1) Intro - CS4 AS3 can only be placed in two places – Timeline/External AS Text File - keyframes - list of cmds that are executed as soon as the keyfrm is reached or a func - Actionscript 2 migration see: - www.senocular.com/flash/tutorials/as3withflashcs3 (2) Frame Actions (Timeline) - put frame actions on separate layer - Using actionscript to create non-linear movies (gotoAndPlay) - make action that loops part of movie (BeforeNonLinearMovie.fla/NonLinearMovie.fla) - Using a frame label as the destination of a goto (NonLinearMovieUsingFrameLabel) (3) Using Event Listeners with Buttons - adding buttons to your animation to stop and continue playback RECORDED LESSON - NewActionscriptPlayButtonAS3.fla - note use of separate layer for frame actions - note use of instance names - name_btn (using this convention gives code hints use _mc formclips) - name_btn.addEventListener(MouseEvent.CLICK,startit); - note two types of functions function say(e:MouseEvent):void { } function add(n1:Number,n2:Number):Number{return n1+n2} - click_to_play_as3.fla - navigationAS3.fla (uses gotoAndStop) - button_component_finished.fla (note difference between stop() and maps.stop() ) - label_finished.fla/tabbed_folders_finished.fla (uses mclips as btns) - uses MOUSE_OVER/MOUSE_OUT/and currentLabel - frame_labels_01.fla - External Linking (url.fla/ActionScriptLinkButtonAS3.fla) - make sure animated text initially added to btn is static text - uses navigateToURL(new URLRequest(“http://www.yahoo.com”));
  21. 21. => Minor Assignment (Four Box Problem) (4) Putting it altogether E-Learning Unit 13 Activity 5 - (Brief Overview and demo) Not redone in AS3 - multiple scenes (add a new scene -> Window->Other Panels->Other Panels -> Scene) - multiplescenes.fla - note use of : gotoAndPlay(1,“scene 2”)) ** parameters reversed in AS3 - frame action (stop) must be on a keyframe - Targeting scenes RECORDED LESSON - duplicating scenes - Examples (targetingscenes.fla/ gotoSceneFinal) (5) Using Event Listeners with Movie Clips E-Learning Unit 14 Activity 2 - Intro - NewMovieClipactionsAS3.fla (place another instance of eye on stage to compare) - uses MouseEvent.MOUSE_DOWN andMouseEvent.MOUSE_UP/OVER/OUT - note naming convention: name_mc (use target in AS screen to chooseobjects) - NewMovieClipActionsInstanceNameAS3.fla (work thru similar example with students) - instancename.method -> eyeball_mc.play()/eyeball_mc.stop() - note: (frame 1) eyeball_mc.stop() stops rotation/stop() stops movement across - changingimages.fla (note: use of mclip.gotoAndPlay(“frame”); (just demo ) in AS2 folder - mcMouseOver.fla (see details below) - note use of mclip.buttonMode=true (makes cursor switch tofinger) - properties (no longer begin with underscore now box.x not box_.x) - object property syntax -> object.property (theclip._alpha) - where theclip is the instance name of the object - some properties .x (x pos), .y (y pos), .alpha (current alpha 0-1 ), .rotation (curr clip rot) .width, .height, .mouseX,.mouseY, .scaleX, .scaleY ** .x,.y -> relate to registration pt of object left,top like in C# graphics - only instances of button, clip and dynamic or input text can be changed during run - Example - propertiesAS3.fla - eg. theclip.scaleX= -theclip.scaleX (performs horiz flip) - note: +ve clockwise/-ve counter clockwise when using .rotation - Nested Instances (paths to objects) - Intro - nestedAS3.fla (movie clip inside a movie clip- use double mc techn forrectangle) - then create circle symbol inside rect - blue_mc.red_mc.x++; - Practical Application - NestedInstancesActionsAS3 (name front/back tires on main)=> Minor Assignment (NestedInstancesProblem) also demo old version in AS2 folderAdditional Notes: (see mcMouseOver.fla above)Basically illustrates how it is possible to use the same function for all movieclips passed to it by implementinge.currentTargetCircle_mc.addEventListener(MouseEvent.CLICK,fname);Function fname(e:MouseEvent):void{ e.currentTarget.alpha=.5;
  22. 22. }recognizes movieclip that was passed (6) Basic Actionscript Concepts - variables (start off with simple example with students) -using dynamic text and input text - show border and use naming convention –>mytext_txt *** New in CS4 can only use instance names (note use of .text property/parseInt( )/String( ) *** - Examples - must declare variables before use: var num:int / var num:Number (like double) - math application ( NewestMathInputAS3.fla/ calculator-as3.fla ) - introduces .ToString() method just like C# - .toFixed(2) formats to 2 decimal places - incrementing a variable ( NewestVariables2AS3.fla) - initialize counter outside of function for global scope - LinkButtonAS3withVar.fla (optional) - Dynamic Text (just demo) - dynamicTxtAS3.fla/scrollingdynamicTxtAS3.fla - note use of multi-line for dynamic text field - illustrates loading external data - uses URLLoader class - Decisions E-Learning Unit 14 Activity 3 - intro ( NewestIf1AS3.fla) (note use of ==/ &&/||) - Practical Application (cointoss) - Math.random() -> 0-1/ (hi-lo+1)*Math.random() (7) Advanced Actionscript Programming E-Learning Unit 15 Activity 1 RECORDED LESSON - dragging a movie using startDrag()/stopDrag() - true parameter causes shape to be picked up from its center - drag1AS3.fla - note use of e.target.startDrag() - this allows function to be called from multiple objects as later illustrated below - dragging and dropping - dragdrop1AS3.fla - note use of e.target.dropTarget!=null && e.target.dropTarget.parent=mclip - practical application - dragdrop_complete.fla - see draganddropAS3.pdf for detailed instructions - note target mclips on main stage have alpha set to 0 - they actually are the exact shape of holes - note naming convention of mclips and targets - note use of .removeEventListener=> Traffic Signs Problem (due: day of practical test)
  23. 23. - Using Enter_Frame EventListeners E-Learning Unit 15 Activity 2 - hightlight concept of registration point when creating a mclip (default to top left) - mc.addEventListener(Event.ENTER_FRAME,f)/function f (e:Event):void - car1AS3.fla - now .x, .y positions are located at the top,left position of an object like C# - note the use of stage.stageWidth for wall detection - car2AS3.fla - note rotation calculation using inverse tangent - randommovementAS3.fla - if object moves away to quickly change fps or Math.random() >.9 - MouseInput.fla (tracks mouse movement using Event.ENTER_FRAME ) - mouseinputAS3.fla (mouseX/mouseY) - note mouse positions are now top/left by default in reg - do simple example to illustrate then discuss modification to have illusion of movement control from center - fox_mc.width/2 - frame_events.fla (note movie inside movie – wheel inside cycle) - note difference between MOUSE_UP and MOUSE_OVER - clock.fla (introduces getTimer() ) - customcursor.fla RECORDED LESSON - note use of Mouse.hide() -point_at_mouse.fla (note: math calc and functions/centre of rotation and reg point) - Timer EventListeners - intro var myTimer:Timer = new Timer(10); myTimer.addEventListener(TimerEvent.TIMER,f); myTimer.start(); /myTimer.stop(); / function f (e:TimerEvent) - car3AS3.fla/ timer_events.fla / stop_go_finished.fla (note use of Timer (400,1) ) delay,repeat - Collision Detection - hittestAS3.fla - introduces hitTestObject(mclip) method to test for collisions - discuss use of hitflag - CollisionDetection.fla actual shape - illustrates difference between hitTestObject and hitTestPoint(x,y,true) - bouncingball.fla - bouncing off mclip walls /note use of myTime.running - Accepting keyboard input (attach EventListener to the stage) - keyboardinput1AS3.fla (keyboard movement using KeyboardEvent.KEY_DOWN) - function f (e:KeyboardEvent) - keyboardinput2AS3.fla (incorporates ENTER_FRAME for smoother animation) - Using the Sound Object (in Object Function folder) RECORDED LESSON - triggering a sound from the library (soundAS3.fla) not on the timeline - make sure to set its symbol linkage properties (right click in library) - Export for AS and put name in class - note use of SoundChannel class to stop sounds - bounceAS3.fla - uses multiple instances of mclip with embedded actionsHint: create a chasing game incorporating ideas from randommovementAS3.fla/clock.fla/hittestAS3.fla/keyboardinput2AS3.fla - Recap Example (in EnterFrame folder) - events.fla - red box mclip has frame by frame animation embedded in it, also draggable - the wheel has an embedded motion tween rotation - the green box mclip is also draggable / the red oval is a button rotates the red box - pressing keydown activates embedded red box frame by frame animation and tire - a basic ENTER_FRAME move bike and TimerEvent rotates wheelWORK PERIOD/REVIEW PERIOD=> Practical Test