CS3505/5020 Software Practice II Game loops C# CS 3505 L02 - 1 - - PowerPoint PPT Presentation

cs3505 5020 software practice ii
SMART_READER_LITE
LIVE PREVIEW

CS3505/5020 Software Practice II Game loops C# CS 3505 L02 - 1 - - PowerPoint PPT Presentation

CS3505/5020 Software Practice II Game loops C# CS 3505 L02 - 1 HW 1 Game Loop How do games work? Sprites move across screen Fast enough so you dont see flicker Game loop controls this It can either draw the sprites


slide-1
SLIDE 1

CS3505/5020 Software Practice II

Game loops C#

CS 3505 L02 - 1

slide-2
SLIDE 2

HW 1 – Game Loop

How do games work?

– Sprites move across screen – Fast enough so you don’t see flicker

Game loop controls this

– It can either draw the sprites as fast as it can – Or it draws them on a set period of time (like once every 1/60th of a second)

Advantages and disadvantages of both Mapping into a C# form is tricky

– Three solutions: timer, thread, invalidate paint method – You can choose any of them

CS 3505 L02 - 2

slide-3
SLIDE 3

Contrast Timed vs. Infinite

Timed is periodic, Infinite is ‘as fast as you can’ If you want to move something from point a to point

b, how do you do it in either one?

– What else do you need to know?

What if you just have a velocity?

– What is velocity defined as?

Understanding this is a key insight for this

assignment

CS 3505 L02 - 3

slide-4
SLIDE 4

Key steps in this assignment

Choose your visual representations, set up the form Respond to user events (enable appropriate form

elements)

Create ball class, set up objects Implement game loop Add physics / motion Incremental development is paramount

CS 3505 L02 - 4

slide-5
SLIDE 5

CS 3505 L02 - 5

The C# Language

Brief overview of key concepts and differences with

Java and C++

Some cool new features

slide-6
SLIDE 6

CS 3505 L02 - 6

Design Goals of C#

The Big Ideas

Component-orientation

– Events, methods, properties

Everything is an object

– Yes, this is different from Java and C++ and is POWERFUL

Robust and durable software Preserving your investment

– Easy to integrate with lots of “stuff”

slide-7
SLIDE 7

CS 3505 L02 - 7

Design Goals of C#

Component-Orientation

C# is the first “Component-Oriented” language in

the C/C++ family

What is a component?

– An independent module of reuse and deployment – Coarser-grained than objects (objects are language-level constructs) – Includes multiple classes – Often language-independent – In general, component writer and user don’t know each

  • ther, don’t work for the same company, and don’t use the

same language

slide-8
SLIDE 8

CS 3505 L02 - 8

Design Goals of C#

Component-Orientation

Component concepts are first class

– Properties, methods, events – Design-time and run-time attributes – Integrated documentation using XML

Enables “one-stop programming”

– In some languages, header files or IDL are used to describe component interfaces – In C#, this is built in

Thus, no .h/.cpp split

– No forward declarations required

Also, no globals. (Yay)

slide-9
SLIDE 9

CS 3505 L02 - 9

Design Goals of C#

Everything is an Object

Traditional views

– C++, Java™: Primitive types are “magic” and do not interoperate with objects (but perform better – no heap allocation) – Smalltalk, Lisp: Primitive types are objects, but at some performance cost

C# unifies with minimal performance cost

– Deep simplicity throughout system

Improved extensibility and reusability

– New primitive types: Decimal, … – Collections, etc., work for all types

slide-10
SLIDE 10

CS 3505 L02 - 10

Design Goals of C#

Robust and Durable Software

Garbage collection

– No memory leaks and stray pointers

Exceptions Type-safety

– No uninitialized variables, no unsafe casts

Versioning addressed Avoid common errors

– E.g. if (x = y) ...

One-stop programming

– Fewer moving parts – See version 3.0 features!!

slide-11
SLIDE 11

CS 3505 L02 - 11

Design Goals of C#

Preserving Your Investment

C++ Heritage

– Namespaces, pointers (in unsafe code), unsigned types, etc. – Some changes, but no unnecessary sacrifices – Feels more like C++ than Java in terms of language, but feels more like Java in terms of environment

Interoperability

– What software is increasingly about – C# talks to XML, SOAP, COM, DLLs, and any .NET Framework language

Increased productivity

– Short learning curve – Millions of lines of C# code in .NET

slide-12
SLIDE 12

CS 3505 L02 - 12

Program Structure

Physical organization

– Types are defined in files (each type in 1 or more files – partial classes) » Partial classes!! – Files are compiled into modules – Modules are grouped into assemblies – Assemblies usually 1 to 1 with modules

Assembly Module File Type

slide-13
SLIDE 13

CS 3505 L02 - 13

Files, Preprocessor, Namespace

C++ style comments (// and /* */ Files in C++ and Java

– C++: header and cpp file, multiple classes per file allowed – Java: one file with one class per file and file named same class

C#

– One file (.cs extension) – Any number of class definitions per file allowed

C# has C++ preprocessor concept (#define, etc.) Java uses the package concept, C# uses namespace

– Allow multiple namespaces per file

Also have alias: using foo = namespace.namespace.class; C# always uses . ; no more . or -> or ::

JAVA

package <Package name>; import <package hierarchy>.<class name>; class Customer { ... }

C#

using <namespace hierarchy>.<class name>; namespace <namespace name> { class Customer { ... } }

slide-14
SLIDE 14

CS 3505 L02 - 14

Types

Unified Type System

Value types

– Directly contain data – Cannot be null

Reference types

– Contain references to objects – May be null i nt i nt i = 123; i = 123; st r i ng s = " Hel l o wor l d" ; st r i ng s = " Hel l o wor l d" ; 123 i s "Hello world"

slide-15
SLIDE 15

CS 3505 L02 - 15

Types

Unified Type System

Value types

– Primitives int i; float x; – Enums enum State { Off, On } – Structs struct Point {int x,y;} – Unsigned ints are included for writing systems code (not in Java)

Reference types

– Root

  • bject

– String string – Classes class Foo: Bar, IFoo {...} – Interfaces interface IFoo: IBar {...} – Arrays string[] a = new string[10]; – Delegates delegate void Empty();

slide-16
SLIDE 16

CS 3505 L02 - 16

Types

Unified Type System

Value (Struct) Reference (Class)

Variable holds Actual value Memory location Allocated on Stack, member Heap Nullability Always has value May be null Default value null Aliasing (in a scope) No Yes Assignment means Copy data Copy reference

slide-17
SLIDE 17

CS 3505 L02 - 17

Types

Unified Type System

Benefits of value types

– No heap allocation, less GC pressure – More efficient use of memory – Less reference indirection – Unified type system

» No primitive/object dichotomy » THIS IS A BIG DEAL!!!!

slide-18
SLIDE 18

CS 3505 L02 - 18

Types

Conversions

Implicit conversions

– Occur automatically – Guaranteed to succeed – No information (precision) loss

Explicit conversions

– Require a cast – May not succeed – Information (precision) might be lost

Both implicit and explicit conversions can be user-

defined

int x = 123456; long y = x; // implicit short z = (short)x; // explicit double d = 1.2345678901234; float f = (float)d; // explicit long l = (long)d; // explicit

slide-19
SLIDE 19

CS 3505 L02 - 19

Types

Unified Type System

Everything is an object

– All types ultimately inherit from object – Any piece of data can be stored, transported, and manipulated with no extra work

MemoryStream FileStream Stream Hashtable int double

  • bject
slide-20
SLIDE 20

CS 3505 L02 - 20

Types

Unified Type System

Polymorphism

– The ability to perform an operation on an object without knowing the precise type of the object – Notice use of primitive types too!! (Java added in 1.5) void Poly(object o) { Console.WriteLine(o.ToString()); } Poly(42); Poly(“abcd”); Poly(12.345678901234m); Poly(new Point(23,45));

slide-21
SLIDE 21

CS 3505 L02 - 21

Types

Unified Type System

Question: How can we treat value and reference

types polymorphically?

– How does an int (value type) get converted into an object (reference type)?

Answer: Boxing!

– Boxing – take something and wrap it up and put it into a Box!!! (objectification ☺) – A key innovation of C# – Only value types get boxed – Reference types do not get boxed

slide-22
SLIDE 22

CS 3505 L02 - 22

Types

Unified Type System

Boxing

– Copies a value type into a reference type (obj ect

  • bj ect )

– Each value type has corresponding “hidden” reference type – Note that a reference-type copy is made of the value type

» Value types are never aliased

– Value type is converted implicitly to obj ect

  • bj ect , a reference

type

» Essentially an “up cast” » So you can do things like toString on an int

slide-23
SLIDE 23

CS 3505 L02 - 23

Types

Unified Type System

Unboxing

– Inverse operation of boxing – Copies the value out of the box

» Copies from reference type to value type

– Requires an explicit conversion

» May not succeed (like all explicit conversions) » Essentially a “down cast”

slide-24
SLIDE 24

CS 3505 L02 - 24

Types

Unified Type System

Boxing and unboxing

i nt i nt i = 123; i = 123;

  • bj ect o = i ;
  • bj ect o = i ;

i nt i nt j = ( i nt ) o; j = ( i nt ) o; 123 i

  • 123

j 123 System.Int32

slide-25
SLIDE 25

CS 3505 L02 - 25

Types

Unified Type System

Benefits of boxing

– Enables polymorphism across all types – Collection classes work with all types » Oh, yeah, this is HUGELY cool!!! – Eliminates need for wrapper classes

Disadvantages of boxing

– Some performance cost doing the conversion

slide-26
SLIDE 26

CS 3505 L02 - 26

Classes

The class concept is pretty much the same as for

Java and C++ and C#

Some syntactic differences

– Like how you specify inheritance – C++ permits multiple inheritance – C# has destructors (Java doesn’t)

Other differences we will see as we go along

slide-27
SLIDE 27

CS 3505 L02 - 27

Class Access Control

public – visible to all protected – visible only from derived classes private – visible only within the given class (default,

where in Java default is internal)

internal – visible only within the same assembly protected internal – visible only to the current

assembly or types derived from the containing class

sealed - can’t be inherited (like final in Java) – structs

are implicitly sealed

const – like C++ (compile time) read-only – like const, but runtime, set in constructor

slide-28
SLIDE 28

CS 3505 L02 - 28

Class Inheritance

Use : to indicate inheritance (like extends in Java)

– Just like C++

Constructors can invoke base constructor by

mentioning name as in C++

– public child (int x, int y) : base(x, y) …

Casting up and down like C++ Use virtual keyword to indicate virtual functions Abstract class concept

– Using abstract keyword

slide-29
SLIDE 29

CS 3505 L02 - 29

interface IB extends IA { void f (); } interface IA { void g (); } interface IC extends IA { void f (); } class X implements IB, IC { void () { System.out.println ("g"); } void () { System.out.println ("f"); } } g f

Interfaces in Java 1.4

ERROR – This will not compile in JAVA 1.4 and before

slide-30
SLIDE 30

CS 3505 L02 - 30

interface IB extends IA { void f (); } interface IA { void g (); } interface IC extends IA { void f (); } class X implements IB, IC { void () { System.out.println ("g"); } void () { System.out.println ("f"); } } g f

Interfaces in Java 1.5

This will compile in JAVA 1.5! Notice, only one ‘f()’!

slide-31
SLIDE 31

CS 3505 L02 - 31

class X : IB, IC { void () { Console.WriteLine ("IA.g"); } void () { Console.WriteLine ("IC.f"); } void () { Console.WriteLine ("IB.f"); } } IA.g IB.f IC.f interface IA { void g (); } interface IB : IA { void f (); } interface IC : IA { void f (); }

Interfaces in C#

class Test { public static void Main () { X x = new X (); ((IA)x).g(); ((IC)x).f(); ((IB)x).f(); } }

slide-32
SLIDE 32

CS 3505 L02 - 32

Structs

Similar to classes, but

– User-defined value type – Always inherits from object – High performance – Stack allocated

Ideal for lightweight objects

– i nt i nt , f l oat f l oat , doubl e doubl e, etc., are all structs – User-defined “primitive” types

» Complex, point, rectangle, color, rational Multiple interface inheritance Same members as class Member access

– publ i c publ i c, i nt er nal i nt er nal , pr i vat e pr i vat e

Instantiated with new

new operator

Structs are “final” – can’t inherit from them

slide-33
SLIDE 33

CS 3505 L02 - 33

Allocation: Structs vs. Classes

struct SPoint { int x, y; ... } class CPoint { int x, y; ... } SPoint sp = new SPoint(10, 20); CPoint cp = new CPoint(10, 20); 10 20 sp sp cp cp 10 20 CPoint

slide-34
SLIDE 34

CS 3505 L02 - 34

Classes and Structs - Similarities

Both are user-defined types Both can implement multiple interfaces Both can contain

– Data

» Fields, constants, events, arrays

– Functions

» Methods, properties, indexers, operators, constructors

– Type definitions

» Classes, structs, enums, interfaces, delegates

slide-35
SLIDE 35

CS 3505 L02 - 35

Class Struct

Reference type Value type Can inherit from any non-sealed reference type No inheritance (inherits only from Syst em . Val ueType Syst em . Val ueType) Can have a destructor No destructor Can have user-defined parameterless constructor No user-defined parameterless constructor

Classes and Structs - Differences

slide-36
SLIDE 36

CS 3505 L02 - 36

C++ Struct C# Struct

Same as C++ class, but all members are publ i c publ i c User-defined value type Can be allocated on the heap,

  • n the stack or as a member

(can be used as value or reference)

Always allocated on the stack or as a member Members are always publ i c publ i c

Members can be publ i c publ i c, i nt er nal i nt er nal or pr i vat e pr i vat e

C# Structs vs. C++ Structs

Very different from C++ struct

slide-37
SLIDE 37

CS 3505 L02 - 37

public class Car : Vehicle { public enum Make { GM, Honda, BMW } Make make; string vid; Point location; Car(Make m, string vid; Point loc) { this.make = m; this.vid = vid; this.location = loc; } public void Drive() { Console.WriteLine(“vroom”); } } Car c = new Car(Car.Make.BMW, “JF3559QT98”, new Point(3,7)); c.Drive();

Class Example

slide-38
SLIDE 38

CS 3505 L02 - 38

public struct Point { int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } } Point p = new Point(2,5); p.X += 100; int px = p.X; // px = 102

Struct Example

These are properties which we’ll describe later.

slide-39
SLIDE 39

CS 3505 L02 - 39

Enums

Enums are first

class

Enums are

typesafe

Values are optional

enum Suit { Clubs = 0, Diamonds = 1, Hearts, Spades } … Suit s = Suit.Clubs; Console.WriteLine (s); //-> Clubs Console.WriteLine((int)s); //-> 0 Suit s2 = Suit.Spades; Console.WriteLine((int)s2); //->3

slide-40
SLIDE 40

CS 3505 L02 - 40

Most Operators Similar

Check out ‘is’

using System; public class ShowTypes { public static void Main(string[] args) { CheckType (5); CheckType (10f); CheckType ("Hello"); } private static void CheckType (object obj) { if (obj is int) { Console.WriteLine("Integer parameter"); } else if (obj is float) { Console.WriteLine("Float parameter"); } else if (obj is string) { Console.WriteLine("String parameter"); } } }

slide-41
SLIDE 41

CS 3505 L02 - 41

Statements

Overview

High C++ fidelity i f

i f , whi l e whi l e, do do require bool bool condition

– no if (x=1) error

got o

got o can’t jump into blocks

swi t ch

swi t ch statement

– No fall-through is allowed you must use break

f or each

f or each statement

– Go through arrays or collections

Expression

statements must do work

void Foo() { i == 1; // error }

slide-42
SLIDE 42

CS 3505 L02 - 42

Statements

Variables

Variables must be assigned a value before they can

be used

– Explicitly or automatically – Called definite assignment

Automatic assignment occurs for static fields, class

instance fields and array elements

void Foo() { string s; Console.WriteLine(s); // Error }

slide-43
SLIDE 43

CS 3505 L02 - 43

Statements

Variables and Constants

Within the scope of a variable or constant it is an

error to declare another variable or constant with the same name

{ int x; { int x; // Error: can’t hide variable x } }

slide-44
SLIDE 44

CS 3505 L02 - 44

Program Structure

Main Method

Execution begins at the static M

ai n( ) M ai n( ) method

Can have only one method with one of

the following signatures in an assembly

– static void Main() – static int Main() – static void Main(string[] args) – static int Main(string[] args)

ar gs[ 0] = par am

1, ar gs[ 1] = par am 2 ( i n ar gs[ 0] = par am 1, ar gs[ 1] = par am 2 ( i n C++ ar gs[ 0] i s pr ogr am . exe C++ ar gs[ 0] i s pr ogr am . exe nam e) nam e)

slide-45
SLIDE 45

CS 3505 L02 - 45

Passing Arguments

Java – Primitives by value; Objects by ref C++ – By value with copy constructors for objects; Reference by specification C# – Primitives by value; Objects by ref; Value can be by ref by saying “ref” – “out” – just like “ref” except initial value ignored, and MUST be assigned using System; public class RefClass { public static void Main(string[] args) { int total = 20; Console.WriteLine("Original value of 'total': {0}", total); // Call the Add method Add (10, ref total); Console.WriteLine("Value after Add() call: {0}", total); } public static void Add (int i, ref int result) { result += i; } }

slide-46
SLIDE 46

CS 3505 L02 - 46

Properties

Formalized getter/setter model of Java

public class Animal { private string name; public string Species { get { return name; } set { name = value; } // Notice magic variable value } } Animal animal = new Animal() animal.Species = "Lion"; // Set the property str = animal.Species; // Get the property value string

Compiles to get_Species/set_Species for languages that

don’t have properties yet

slide-47
SLIDE 47

Examples

Timer Drawing Class with properties