+ All Categories
Home > Documents > Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game...

Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game...

Date post: 23-Feb-2018
Category:
Upload: voxuyen
View: 233 times
Download: 2 times
Share this document with a friend
12
Introduction to Game Programming Introduction to Game Programming Autumn Autumn 2016 2016 2. Scripting games, and 2. Scripting games, and 2. Scripting games, and 2. Scripting games, and C# (.Net/Mono) C# (.Net/Mono) Chapter 11 " Chapter 11 "Scripting languages and file formats Scripting languages and file formats" " [Madhav, 2014, pp. 224 [Madhav, 2014, pp. 224-242]. 242]. Section 15.8 " Section 15.8 "Scripting Scripting" in [Gregory, 2014, pp. 954 " in [Gregory, 2014, pp. 954-978] 978] Juha Vihavainen Juha Vihavainen University of Helsinki University of Helsinki Section 15.8 " Section 15.8 "Scripting Scripting" in [Gregory, 2014, pp. 954 " in [Gregory, 2014, pp. 954-978] 978] Bytecode Bytecode design pattern [ design pattern [Game Programming Patterns Game Programming Patterns] Outline Outline Scripting languages Scripting languages the tradeoffs of using scripts the tradeoffs of using scripts different types of scripting languages different types of scripting languages Implementing a scripting language (very briefly) Implementing a scripting language (very briefly) the phases of processing a programming language the phases of processing a programming language interpretation by a VM interpretation by a VM vs vs. native execution . native execution Bytecode Bytecode design pattern design pattern "give behavior the flexibility of data by encoding it as "give behavior the flexibility of data by encoding it as "give behavior the flexibility of data by encoding it as "give behavior the flexibility of data by encoding it as instructions for a virtual machine" instructions for a virtual machine" ~ metaprogramming, managing code as resource ~ metaprogramming, managing code as resource C# C# - a scripting language in, e.g., XNA and Unity a scripting language in, e.g., XNA and Unity 6.12.2016 6.12.2016 2 Juha Vihavainen / University of Helsinki Juha Vihavainen / University of Helsinki
Transcript
Page 1: Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game Programming Autumn Autumn 20162016 2. ... and C# (.Net/Mono) Chapter 11 " Scripting languages

Introduction to Game ProgrammingIntroduction to Game ProgrammingAutumn Autumn 20162016

2. Scripting games, and 2. Scripting games, and 2. Scripting games, and 2. Scripting games, and C# (.Net/Mono) C# (.Net/Mono)

Chapter 11 "Chapter 11 "Scripting languages and file formatsScripting languages and file formats" " [Madhav, 2014, pp. 224[Madhav, 2014, pp. 224--242]. 242].

Section 15.8 "Section 15.8 "ScriptingScripting" in [Gregory, 2014, pp. 954" in [Gregory, 2014, pp. 954--978]978]

Juha VihavainenJuha Vihavainen

University of HelsinkiUniversity of Helsinki

Section 15.8 "Section 15.8 "ScriptingScripting" in [Gregory, 2014, pp. 954" in [Gregory, 2014, pp. 954--978]978]

BytecodeBytecodedesign pattern [design pattern [Game Programming PatternsGame Programming Patterns]]

OutlineOutline�� Scripting languagesScripting languages

�� the tradeoffs of using scriptsthe tradeoffs of using scripts

�� different types of scripting languagesdifferent types of scripting languages

�� Implementing a scripting language (very briefly)Implementing a scripting language (very briefly)

�� the phases of processing a programming languagethe phases of processing a programming language

�� interpretation by a VM interpretation by a VM vsvs. native execution. native execution

�� BytecodeBytecodedesign pattern design pattern

�� "give behavior the flexibility of data by encoding it as "give behavior the flexibility of data by encoding it as �� "give behavior the flexibility of data by encoding it as "give behavior the flexibility of data by encoding it as instructions for a virtual machine" instructions for a virtual machine"

�� ~ metaprogramming, managing code as resource~ metaprogramming, managing code as resource

�� C#C# -- a scripting language in, e.g., XNA and Unitya scripting language in, e.g., XNA and Unity

6.12.20166.12.2016 22Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

Page 2: Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game Programming Autumn Autumn 20162016 2. ... and C# (.Net/Mono) Chapter 11 " Scripting languages

Evolution of (scripting) languagesEvolution of (scripting) languages

�� Early games (applications) were written in assembly (symbolic Early games (applications) were written in assembly (symbolic machine language) for performance reasons and for reasons of machine language) for performance reasons and for reasons of availability of languages and tools; needed direct (efficient) availability of languages and tools; needed direct (efficient) availability of languages and tools; needed direct (efficient) availability of languages and tools; needed direct (efficient) access to hardwareaccess to hardware--level display bufferslevel display buffers

�� With more powerful computers and language processing tools, With more powerful computers and language processing tools, highhigh--level languages such as Fortran, Lisp, Pascal, C/C++, Java, level languages such as Fortran, Lisp, Pascal, C/C++, Java, C# etc. became practical C# etc. became practical

�� Now, we often prefer scripting languages for gameplay logicNow, we often prefer scripting languages for gameplay logic�� Now, we often prefer scripting languages for gameplay logicNow, we often prefer scripting languages for gameplay logic

�� most heavymost heavy--duty calculations are done by a game engine and duty calculations are done by a game engine and shader programs in GPU (Graphics Processing Unit)shader programs in GPU (Graphics Processing Unit)

�� in C++/C and in C++/C and shadershaderlanguageslanguages

6.12.20166.12.2016 33Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

Scripting language Scripting language tradeoffstradeoffs

AdvantagesAdvantages

it's typically much easier it's typically much easier

DisadvantagesDisadvantages

runtime performance is runtime performance is �� it's typically much easier it's typically much easier and faster to make and and faster to make and test changes in script test changes in script than with, say, C/C++than with, say, C/C++

�� unlike in C/C++, bad unlike in C/C++, bad code is unlikely to crash code is unlikely to crash the entire gamethe entire game

�� runtime performance is runtime performance is typically substantially slower typically substantially slower than C/C++than C/C++

�� use multiple languages (system, use multiple languages (system, script)script)

�� language tools may be less language tools may be less the entire gamethe entire game

language tools may be less language tools may be less mature, limited, or nonmature, limited, or non--existingexisting

6.12.20166.12.2016 44Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

Page 3: Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game Programming Autumn Autumn 20162016 2. ... and C# (.Net/Mono) Chapter 11 " Scripting languages

When to use scripting?When to use scripting?�� If performance of the component is critical, do not use script; If performance of the component is critical, do not use script;

otherwise, the benefits usually outweigh the negativesotherwise, the benefits usually outweigh the negatives

�� Sample breakdownSample breakdown

C/C++ (Native Code) Scripting Language

Rendering engine Camera logic

AI (pathfinding) AI (state machines)

Physics systems General gameplay logic

�� the lowthe low--level tasks are often part of a game engine (C++)level tasks are often part of a game engine (C++)

�� the gamethe game--specific tasks often written in a script languagespecific tasks often written in a script language

logic

File loading User interface

6.12.20166.12.2016 55Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

Types of scripting languagesTypes of scripting languages

Scripting languages that already existScripting languages that already exist

�� examplesexamples

�� Lua (WoW)Lua (WoW)

Custom LanguagesCustom Languages

�� proprietary languages created proprietary languages created �� Lua (WoW)Lua (WoW)

�� Python (Blender)Python (Blender)

�� JavaScript (in Unity, kind of)JavaScript (in Unity, kind of)

�� C# C# (XNA, Unity)(XNA, Unity)

Visual scripting systemsVisual scripting systems

�� proprietary languages created proprietary languages created for a specific game/enginefor a specific game/engine

�� examplesexamples

�� UnrealScript (late)UnrealScript (late)

�� QuakeCQuakeC

�� SCUMMSCUMM�� flowchartflowchart--like scripting systemlike scripting system

�� used for level, AI scriptingused for level, AI scripting

�� to hook up gameto hook up game--level events and behaviour level events and behaviour

�� e.g., enemies spawn when the player opens a doore.g., enemies spawn when the player opens a door

�� BlueprintBlueprint�� UnityScriptUnityScript

6.12.20166.12.2016 66Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

Page 4: Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game Programming Autumn Autumn 20162016 2. ... and C# (.Net/Mono) Chapter 11 " Scripting languages

Implementing a (scripting) languageImplementing a (scripting) language�� Language creation/compiler theory is a huge subLanguage creation/compiler theory is a huge sub--field of field of

computer sciencecomputer science

�� Programming languages are our tools, so useful to understand at Programming languages are our tools, so useful to understand at least the basic principles of how a language processor worksleast the basic principles of how a language processor worksleast the basic principles of how a language processor worksleast the basic principles of how a language processor works

�� The main phases (using the The main phases (using the PipelinePipelinearchitecture/pattern)architecture/pattern)

�� lexical analysis lexical analysis ("tokenization"): find ("tokenization"): find tokenstokens= basic text = basic text items (such as names, operators, delimiters, keywords)items (such as names, operators, delimiters, keywords)

�� syntax analysis syntax analysis (parsing): statement/block structures(parsing): statement/block structures

�� semantic analysis semantic analysis (omitted in the text book): contextual (omitted in the text book): contextual constraints (such as: "constraints (such as: "namesnamesmust be declared before use..")must be declared before use..")

�� optimization optimization (omitted in the text book): transformations for (omitted in the text book): transformations for speedup or memory improvementsspeedup or memory improvements

�� code generationcode generation: in multiple phases, again..: in multiple phases, again..

6.12.20166.12.2016 77Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

The basic idea: use an The basic idea: use an ASTAST(Abstract (Abstract SyntaxSyntaxTree)Tree)AST for "5 + 6 * 10"

�� Shows theShows the nested structure of a nested structure of a construct / whole programconstruct / whole program

�� The The InterpreterInterpreterpattern pattern [Gamma[Gamma et al.et al.]:]: how to how to evaluate sentences in a evaluate sentences in a language language

�� The AST of a sentence/The AST of a sentence/expression in a language expression in a language

6.12.20166.12.2016 88Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

expression in a language expression in a language is used for evaluating is used for evaluating (interpreting) the construct; (interpreting) the construct; traverse the tree in posttraverse the tree in post-- order order evaluating the nodes oneevaluating the nodes one--byby--one one

�� A similar traversal can be used to A similar traversal can be used to generate portable bytecode, for generate portable bytecode, for later execution later execution

Page 5: Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game Programming Autumn Autumn 20162016 2. ... and C# (.Net/Mono) Chapter 11 " Scripting languages

Implementing an interpreterImplementing an interpreterabstract class Expressionabstract class Expression

function Execute ()function Execute ()

class Integer : Expressionclass Integer : Expressionclass Integer : Expressionclass Integer : Expression

int value . . . // int value . . . // store the integral valuestore the integral valuefunction Execute ()function Execute ()

// // push value onto calculator's stack . . .push value onto calculator's stack . . .

class Addition : Expressionclass Addition : Expression

Expression lhs, rhs . . . // Expression lhs, rhs . . . // left and rightleft and right operandsoperands~ byte function Execute ()function Execute ()

// // postpost--order means left child, right child, then thisorder means left child, right child, then thislhs.Execute ()lhs.Execute () // // leave the result on stackleave the result on stackrhs.Execute ()rhs.Execute () // // leave the result on stackleave the result on stack// // add top two values on stack, push result back on . . add top two values on stack, push result back on . . ..

6.12.20166.12.2016 99Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

~ bytecode

Case: Case: WoWWoWscripting scripting [Madhav, 239[Madhav, 239--241]241]�� In an MMORPG, players may have differing preferences, e.g., some In an MMORPG, players may have differing preferences, e.g., some

players might want the enemy health to be shown in the center of the players might want the enemy health to be shown in the center of the screen, others might want it in the top right, etc.screen, others might want it in the top right, etc.

�� An An XMLXML file stores the layout of interfaces, such as placement of file stores the layout of interfaces, such as placement of images, controls, buttons, and so on images, controls, buttons, and so on images, controls, buttons, and so on images, controls, buttons, and so on

�� can inherit from a particular widget and overwrite certain can inherit from a particular widget and overwrite certain propertiesproperties

�� specifies whether there are events to registerspecifies whether there are events to register

�� specific to widgets: clicking a button, opening a frame, and specific to widgets: clicking a button, opening a frame, and sliding a slider, andsliding a slider, and

�� to the game as a whole: to deal or take damage or perform one to the game as a whole: to deal or take damage or perform one �� to the game as a whole: to deal or take damage or perform one to the game as a whole: to deal or take damage or perform one of different actionsof different actions

�� The behavior of the UI is implemented using The behavior of the UI is implemented using LuaLua languagelanguage

�� ProblemProblem of "player automation": automating gameplay with UI modof "player automation": automating gameplay with UI mod

�� For details, see the textbook [Madhav, pp. 239For details, see the textbook [Madhav, pp. 239--241]241]6.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki 1010

Page 6: Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game Programming Autumn Autumn 20162016 2. ... and C# (.Net/Mono) Chapter 11 " Scripting languages

On On UnityUnity scriptingscripting

�� UnityUnity scriptingscripting is is creatingcreating MonoBehaviourMonoBehaviourclassesclasses

�� For For manymany reasonsreasons, C# is the , C# is the recommendablerecommendable alternativealternative for for thosethosewhowhoalreadyalreadycancanprogramprogramwhowhoalreadyalreadycancanprogramprogram

�� UsingUsing the C# the C# programmingprogramming languagelanguage withwith the the UnityUnity engineengine

�� an an overviewoverview of C# of C# programmingprogramming ((Mono Mono version)version)

�� a a comparisoncomparison betweenbetween C# and JavaC# and Java

�� a a selectionselection of C# of C# programmingprogramming featuresfeatures and and idiomsidioms

�� on on basicbasicsyntaxsyntaxand and uniformuniform typetypesystemsystem�� on on basicbasicsyntaxsyntaxand and uniformuniform typetypesystemsystem

�� inheritanceinheritance, , genericsgenerics

�� logicallogical propertiesproperties ((accessorsaccessors))

�� manymany otherother featuresfeatures: : lambdalambda expressionsexpressions, reflection. , reflection. ..

6.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki 1111

General features of the C# language (.NET/Mono)General features of the C# language (.NET/Mono)

�� A safe, generalA safe, general--purpose objectpurpose object--oriented language, withoriented language, with

�� objectobject--oriented features, generics, threads, exceptions, . .oriented features, generics, threads, exceptions, . .

�� strong type checking: strong type checking: staticstaticplus plus dynamicdynamic�� strong type checking: strong type checking: staticstaticplus plus dynamicdynamic

�� compilecompile--time checking for early error detection & efficiencytime checking for early error detection & efficiency�� optional optional dynamicdynamic "typing" = (actually) dynamic binding"typing" = (actually) dynamic binding

�� prevention of uninitialized variables (checked at compile time)prevention of uninitialized variables (checked at compile time)�� array bounds checking (at run time, mostly)array bounds checking (at run time, mostly)�� automatic garbage collection (no dangling references..)automatic garbage collection (no dangling references..)

�� Moderately easy to learn by programmers familiar with Java Moderately easy to learn by programmers familiar with Java and/or C++ and/or C++

�� SystemsSystems: MS .NET : MS .NET CLR = VMCLR = VM;; MSMSXNA, MonoGame, Unity..XNA, MonoGame, Unity..

12126.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

Page 7: Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game Programming Autumn Autumn 20162016 2. ... and C# (.Net/Mono) Chapter 11 " Scripting languages

CIL = bytecode

E.g., UnityScript

Compile-time and run-time processes

CIL was not designed for interpretation

~ Java .class file

6.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki 1313

processes

[Illustrated C# 2012, p. 9.]

"Hello, World!" "Hello, World!" exampleexampleusing System;using System; // // import names from import names from SystemSystem

static class Hello {static class Hello {static void Main () { // static void Main () { // main entry pointmain entry point

Console.WriteLine ("Hello, World!");Console.WriteLine ("Hello, World!");Console.WriteLine ("Hello, World!");Console.WriteLine ("Hello, World!");}}

}}

�� usingusing imports the types contained in a imports the types contained in a namespacenamespaceenabling the enabling the identifier of each type to be used without qualificationidentifier of each type to be used without qualification

�� uses the predefined uses the predefined staticstatic System.Console System.Console classclass�� uses the predefined uses the predefined staticstatic System.Console System.Console classclass

�� WriteLineWriteLineis a public is a public staticstatic method of method of ConsoleConsole

�� the customary meaning for the customary meaning for staticstatic: no instances needed : no instances needed for using/calling classfor using/calling class--level data/methodslevel data/methods

14146.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

Page 8: Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game Programming Autumn Autumn 20162016 2. ... and C# (.Net/Mono) Chapter 11 " Scripting languages

Similarities in C# and JavaSimilarities in C# and Java

�� Classes and interfaces in both C# and JavaClasses and interfaces in both C# and Java

�� A single root class for inheritance treeA single root class for inheritance tree

�� java.lang.Objectjava.lang.Objectin Java (identifier, not a reserved keyword)in Java (identifier, not a reserved keyword)�� java.lang.Objectjava.lang.Objectin Java (identifier, not a reserved keyword)in Java (identifier, not a reserved keyword)

�� objectobject in C# (actually, the same as .NET's in C# (actually, the same as .NET's System.ObjectSystem.Object))

�� but value types (primitives) are also part of the hierarchybut value types (primitives) are also part of the hierarchy

�� All methods defined within classes in both Java and C# (+ All methods defined within classes in both Java and C# (+ structsstructs))

�� Both C# and Java provide extensive class libraries, garbage Both C# and Java provide extensive class libraries, garbage collection, type safety, generics, exceptions to manage errors, collection, type safety, generics, exceptions to manage errors, threads, generics, reflection facilities, bytecode verification.. threads, generics, reflection facilities, bytecode verification.. threads, generics, reflection facilities, bytecode verification.. threads, generics, reflection facilities, bytecode verification.. (some differences in details) (some differences in details)

�� Implementations are based on platformImplementations are based on platform--independent independent bytecodebytecodeand and virtual machines virtual machines (technical differences in details and tradeoffs)(technical differences in details and tradeoffs)

6.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki 1515

Differences between C# and JavaDifferences between C# and Java

�� structstructs, s, delegatedelegates, and s, and nullablenullablevalue types ("value types ("bool?bool?") in C#, only") in C#, only

�� but can use but can use wrapperwrapperclasses in Java: classes in Java: BBoolean myval = null;oolean myval = null;

�� C# provides properties, indexers, overloaded operators (needed for C# provides properties, indexers, overloaded operators (needed for �� C# provides properties, indexers, overloaded operators (needed for C# provides properties, indexers, overloaded operators (needed for value types), and many forms of function values (delegates, lambdas)value types), and many forms of function values (delegates, lambdas)

�� C# instantiates generic classes at run time; Java uses C# instantiates generic classes at run time; Java uses type erasuretype erasure

�� virtualvirtual as well as nonas well as non--virtualvirtual methods in C# (the same as in C++)methods in C# (the same as in C++)

�� Classes inside classes are Classes inside classes are staticstatic in C# (in Java, kind of in C# (in Java, kind of closuresclosures))

�� C# supports also rectangular arrays (rows are of the same length)C# supports also rectangular arrays (rows are of the same length)

�� No No checkedchecked exceptionsexceptionsin C# (similar to C++)in C# (similar to C++)

�� In Java, an enumeration type is a special form of a class, and each In Java, an enumeration type is a special form of a class, and each enumerated value is an instance (object) of this special classenumerated value is an instance (object) of this special class

�� In C#, an enumeration type is a value type (as in C/C++)In C#, an enumeration type is a value type (as in C/C++)

6.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki 1616

Page 9: Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game Programming Autumn Autumn 20162016 2. ... and C# (.Net/Mono) Chapter 11 " Scripting languages

Meaning of some (exotic) C# keywordsMeaning of some (exotic) C# keywords

Can test before downcast: "Can test before downcast: "asas T" (or T" (or nullnull) ) -- also: "also: "isis T"T"

""basebase" (= "super") for calling base methods/ctor " (= "super") for calling base methods/ctor

""checkedchecked (expr)" / "(expr)" / "checkedchecked { . . }": checks for { . . }": checks for intint overflows overflows

"unchecked { . . . }" , too

""checkedchecked (expr)" / "(expr)" / "checkedchecked { . . }": checks for { . . }": checks for intint overflows overflows

"" internalinternal": visible only in this or friend assemblies (spec. via attributes)": visible only in this or friend assemblies (spec. via attributes)

""namespacenamespace": logical scopes to enclose names (similar to C++)": logical scopes to enclose names (similar to C++)

""operatoroperator": overloading (only of existing operator symbols)": overloading (only of existing operator symbols)

""paramsparams": for defining variable": for defining variable--length argument listslength argument lists

""readonlyreadonly": cannot be reassigned ": cannot be reassigned -- after initialization (vs. after initialization (vs. constconst))""sealedsealed" (= "" (= "finalfinal" in Java): cannot have subclasses" in Java): cannot have subclasses

""structstruct": ": useruser--defined defined value typevalue type, somewhat similar to , somewhat similar to classclass""virtualvirtual" / "" / "overrideoverride": explicit dynamically bound methods": explicit dynamically bound methods

""dynamicdynamic" : check called methods at run" : check called methods at run--time, time, onlyonly (~ "(~ "duck typingduck typing"?)"?)

17176.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

Defining a classDefining a class

Simple exampleSimple example

class A {class A { // // illustrative, only illustrative, only !!

In C# , a single file can contain multiple public class definitions

class A {class A { // // illustrative, only illustrative, only !!

int num1 = 1; int num1 = 1; // // can be initialized herecan be initialized hereint num2; int num2; // // = zero, by default= zero, by default

public A (int no public A (int no = 0= 0) { // ) { // can use can use optionaloptionalargumentsargumentsnum2 = no; num2 = no; // // set initial value of numberset initial value of number

}}. . .. . .. . .. . .

}}

18186.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

NamedNamedargumentsarguments: Rather than identifying an argument by : Rather than identifying an argument by position, you can identify an argument by nameposition, you can identify an argument by name "Bar (d:3);"-- in in AdaAda, these were called , these were called keyword parameterskeyword parameters

Page 10: Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game Programming Autumn Autumn 20162016 2. ... and C# (.Net/Mono) Chapter 11 " Scripting languages

SSample generic class ample generic class public class Stack <T> { public class Stack <T> { // // illustrative, onlyillustrative, only

private Entry <T> top;private Entry <T> top; // // T is T is anyanytype type ((oror constrainedconstrained))

public void Push (T data) { top = new Entry <T> (data, top); }public void Push (T data) { top = new Entry <T> (data, top); }public T Pop () {public T Pop () {

if (top == null) throw new InvalidOperationException ();if (top == null) throw new InvalidOperationException ();T result = top.data; top = top.next; return result;T result = top.data; top = top.next; return result;

}}class Entry <V> { . . . } // class Entry <V> { . . . } // C++C++--like like ((staticstatic)) class..class..

} }

�� A A generic method generic method is a method that is declared with type parametersis a method that is declared with type parameters�� A A generic method generic method is a method that is declared with type parametersis a method that is declared with type parameters

static void Swap <T> (ref T lhs, static void Swap <T> (ref T lhs, ref T ref T rhs) {rhs) {T tmp = lhs; lhs = rhs; rhs = tmp;T tmp = lhs; lhs = rhs; rhs = tmp;

}}

19196.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

Resembles C++ Resembles C++ reference reference parameters: "(parameters: "(T& reT& re)" )" Calls can use Calls can use type inference type inference

from actual argumentsfrom actual arguments

Passing arguments in C#Passing arguments in C#�� Values are usually Values are usually passed by value passed by value (of course)(of course)

�� HeapHeap--allocated objects are allocated objects are passed by referencepassed by reference

�� Variables Variables can be can be passed bypassed by--reference reference with keyword "with keyword "refref""

public static void Add (int i, public static void Add (int i, refref int result) { int result) { public static void Add (int i, public static void Add (int i, refref int result) { int result) { result += i; result += i;

} . . .} . . .

int total = 20; int total = 20; Add (10, Add (10, refref total); // total); // note obligatory keyword note obligatory keyword ""refref""Console.WriteLine ("Value after Add () call: {0}", total); Console.WriteLine ("Value after Add () call: {0}", total);

passes the passes the addressaddressof "total"of "total"

�� resembles C++ resembles C++ reference types reference types ("&")("&")

�� Also reference Also reference outout parameters (assigned within the method)parameters (assigned within the method)

�� Can also pass an objectCan also pass an object--reference variable reference variable by referenceby reference: passes the : passes the address of the local variable itself (of course)address of the local variable itself (of course)

20206.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

Page 11: Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game Programming Autumn Autumn 20162016 2. ... and C# (.Net/Mono) Chapter 11 " Scripting languages

InheritanceInheritance

�� Use "Use "::" to indicate inheritance (vs. "" to indicate inheritance (vs. "extendsextends" in Java)" in Java)

�� C++C++--like notation (but without C++ like notation (but without C++ publicpublic//private private clauses)clauses)

Constructors can invoke baseConstructors can invoke base--class constructor by special baseclass constructor by special base--class class �� Constructors can invoke baseConstructors can invoke base--class constructor by special baseclass constructor by special base--class class constructor call:constructor call:

public public Derived (Derived (int int x, x, int int y) : y) : basebase (x, y) . . //(x, y) . . // note note basebase keywordkeyword

�� Casting up and down as in Java (usually runCasting up and down as in Java (usually run--time check needed)time check needed)

�� Must use "Must use "virtualvirtual" keyword to indicate " keyword to indicate virtual functionsvirtual functions

�� Must use "Must use "overrideoverride" when " when redefiningredefininga virtual methoda virtual method�� Must use "Must use "overrideoverride" when " when redefiningredefininga virtual methoda virtual method

�� can call the basecan call the base--class implementations via "class implementations via "basebase""

�� Also: Also: abstract class abstract class concept (with concept (with ""abstractabstract" keyword)" keyword)

21216.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

C# property exampleC# property example

public class GameInfo {public class GameInfo {private string name;private string name;publicpublic string Name {string Name { // // can have access modifierscan have access modifiers

get { return name; }get { return name; }

...Name = "...";...Name = "...";

get { return name; }get { return name; }set { name = set { name = valuevalue; }; } // // contextual keyword contextual keyword valuevalue

}}}}�� getget actually a method, returning a value of the specified typeactually a method, returning a value of the specified type

�� setset uses an implicit parameter "uses an implicit parameter "valuevalue" to set some internal data " to set some internal data setset uses an implicit parameter "uses an implicit parameter "valuevalue" to set some internal data " to set some internal data representation (here simply a field but not necessarily)representation (here simply a field but not necessarily)

�� Can omit Can omit getget or or setset (but not both), and use access modifiers(but not both), and use access modifiers

�� By convention, property names capitalize the first character, so By convention, property names capitalize the first character, so often use public property "often use public property "XX" to access a " to access a privateprivate field "field "xx""

22226.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

Page 12: Introduction to Game Programming Autumn Autumn 20162016 · PDF fileIntroduction to Game Programming Autumn Autumn 20162016 2. ... and C# (.Net/Mono) Chapter 11 " Scripting languages

C# C# propertiesproperties: "logical fields": "logical fields"

�� Provide access Provide access to to an "abstract data" propertyan "abstract data" property

�� hidden custom implementations of getters and settershidden custom implementations of getters and setters

�� HHave ave syntax similar to direct variable accesssyntax similar to direct variable access�� HHave ave syntax similar to direct variable accesssyntax similar to direct variable access

�� can write "can write "foo.Xfoo.X" instead of "" instead of "foo.GetX ()foo.GetX ()""�� can can write "write "foo.X = valuefoo.X = value"" instead instead of "of "foo.SetX foo.SetX ((value);value);""

�� the actual accessor methods can additionallythe actual accessor methods can additionally

�� check state check state and so enforce and so enforce invariantsinvariants

�� provide provide lazy evaluation lazy evaluation or some other processing..or some other processing..�� provide provide lazy evaluation lazy evaluation or some other processing..or some other processing..

�� In a way, a minor feature ("syntactic sugar") butIn a way, a minor feature ("syntactic sugar") but

�� improves readability and improves readability and uniformity of access notation uniformity of access notation (~ (~ EiffelEiffel))

�� used used extensively in extensively in C#/.NET libraries, and in Unity (Mono)C#/.NET libraries, and in Unity (Mono)

23236.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki

AutomaticAutomaticpropertiesproperties�� Often, a property Often, a property justjust reads and writes one variable (reads and writes one variable (whywhy..?)..?)

�� Such Such getget andandsetset can be automatically created (by the compiler)can be automatically created (by the compiler)

public class GameInfo { public class GameInfo { public string Name { public string Name { get; set; get; set; } // } // automatic propertyautomatic propertypublic string Name { public string Name { get; set; get; set; } // } // automatic propertyautomatic property

}}�� here, a hidden "here, a hidden "private stringprivate string" member is created and used" member is created and used

�� Behaves the same way as the previous Behaves the same way as the previous NameNameproperty property

GameInfo g = new GameInfo ();GameInfo g = new GameInfo ();g.Name = "Radiant Silvergun"; g.Name = "Radiant Silvergun"; // // calls calls ""setset""g.Name = "Radiant Silvergun"; g.Name = "Radiant Silvergun"; // // calls calls ""setset""

System.Console.Write (g.Name);System.Console.Write (g.Name); // // calls calls ""getget""

�� Here too, can omit one of the two, or specify Here too, can omit one of the two, or specify restrictedrestrictedaccessibilityaccessibility

public string Name { get; public string Name { get; protectedprotected set; }set; }

24246.12.20166.12.2016 Juha Vihavainen / University of HelsinkiJuha Vihavainen / University of Helsinki


Recommended