<<

slide 2 gaius Loops in #

do while loop

choose them wisely,agood choice of loop can make your code cleaner

slide 3 slide 4 gaius gaius Statement sequences do while loop

in the following slides statementsequences is used syntax of this loop is

in C# this can mean do asingle statement statementsequences; while (expr); or a compound statement

it should be used when the loop must run at least acompound statement starts with { and ends with a } once individual statements are separated by ; remember the guessing number game, you must makeatleast one guess! slide 5 slide 6 gaius gaius while loop while loop

syntax of this loop is { char ch;

ch = f.ReadChar (); // the ½ component while (expr) while (ch != ’z’) statementsequences; { ... // the N component ch = f.ReadChar (); } useful if there are occasions when the loop body statementsequence should neverexecute sometimes called a N and a ½ loop Ntimes around the loop, but it requires some set up for the initial conditional expression

slide 7 slide 8 gaius gaius forloop forloop

allows us to combine the N and ½ loop into one for (int i = 1; i <= 12; i++) compound statement Console.WriteLine ("8 x {0} = {1}", i, 8*i); the syntax is: and

for (initialisers;expression; iterators) for (int i = 1; i <= 12; i++) statementsequences; { Console.WriteLine ("8 x {0} = {1}", i, 8*i); }

are the same, however we must use { and } if we wanted multiple statements in the loop body slide 9 slide 10 gaius gaius forloop while and do while loops

do not abuse the for loop if you look carefully at these loops you will see that theyallowyou to have multiple initialisers, in most cases while and do loops complexexpressions and multiple iterators also have initialise, iterator and expression sections C# allows you to break out of the loop or the programmer can choose where and howthey continue to the next iterator value appear both are considered very bad programming practice in general it is better to use a while or a do while loop than abuse a for loop

as a programmer keep and eye on howeasy it is to maintain your code

slide 11 slide 12 gaius gaius foreach statement C# functions (methods)

useful to iterate overarrays, more about this later try and keep your function length small and have one purpose

mercylessly refactor and break functions into smaller sub functions to achieve the above aim

it allows you to focus on a smaller set of code lines should reduce the programming time makes it easier to maintain your code or for someone else to read your code slide 13 slide 14 gaius gaius Example function, implementing a delay Example function, implementing a delay function function

suppose we want a delay of ¼ of a second in our we can call this in our program, likethis: program we might write:

public static void delay () { Thread.Sleep (250); // sleep for 250 milliseconds }

slide 15 slide 16 gaius gaius Example function, implementing a delay Example function, implementing a delay function function

using System; sometimes it is useful to use a function to change the using System.Threading; name of the action public class test { as in the case above public static void delay () { Thread.Sleep (250); // sleep for 250 milliseconds }

public static void Main () { char ch; ConsoleKeyInfo name;

do { name = Console.ReadKey (); Console.WriteLine ("you typed {0}", name.KeyChar); delay (); }while (name.KeyChar != ’x’); } } slide 17 slide 18 gaius gaius Example function, implementing a delay Example function, implementing a delay function function

we notice that the previous code is the skeleton for a consider the main method (function): game loop

public static void Main () it would be interesting to explore whether we can poll { char ch = ’a’; // variable is assigned as not ’x’ the keyboard for input and takeaction if no input is Console.Clear (); // clears screen seen do { it would give usthe ability to produce retro if (GetChar (ref ch)) Console.WriteLine ("you typed {0}", ch); console based games else { Console.WriteLine ("move monster"); delay (); at the same time it allows us to explore howfunctions } operate }while (ch != ’x’); }

slide 19 slide 20 gaius gaius Reference parameters Reference parameters

we are calling our own function GetChar which will the function must also be declared knowing that this return a bool value indicating whether a keyboard parameter is a reference parameter character has been pressed by the user if true is returned then the parameter, ch,will public static bool GetChar (ref char ch) be the pressed key { otherwise it is left alone if (Console.KeyAvailable) { ConsoleKeyInfo k = Console.ReadKey (); ch = k.KeyChar; notice that we are not passing the value into the return true; } function, but rather the address (or reference) of the return false; variable }

the function uses the address to assign a newvalue to the variable which is seen by the caller slide 21 slide 22 gaius gaius Non reference parameters Non reference parameters

changing our main function to: public static void MovePlayer (char c) { switch (c) {

public static void Main () case ’w’: { // move up char ch = ’a’; // variable is assigned as not ’q’ break; case ’a’: Console.Clear (); // clears screen // move left do { break; if (GetChar (ref ch)) case ’’: MovePlayer (ch); // move right else break; MoveMonster (); case ’s’: }while (ch != ’q’); // move down } break; default: } } allows the code to be naturally extended by implementing sub functions notice howthe variable ch is passed from main by value and this copy c is tested using the switch

slide 23 slide 24 gaius gaius C# Arrays C# Arrays

in C# an array is an indexedcollection of objects, all of the same type Clear() clear arange of elements Copy() copyasection of an array to another C# provides native syntax for the declaration of Reverse() reverse order of array Array objects Sort() sort aone dim array which is itself a System.Array object Length() the length of the array Rank() number of dimensions of the array GetLength() get length of particular dim GetLowerBound get lowest bound of dim GetUpperBound get upper bound of dim slide 25 slide 26 gaius gaius Declaring arrays in C# Initialising arrays

example declare an integer array int[] myPrimes1 = new int[5] {1, 2, 3, 5, 7}; int[] myPrimes2 = {1, 2, 3, 5, 7};

int[] myArray; int[] myArray2 = new int[10];

for (int i = 0; i < myArray2.Length; i++) { instantiate an array to contain fiveinteger values (all myArray2[i] = 42; zero) }

myArray = new int[5];

slide 27 slide 28 gaius gaius Initialising arrays Multidimensional arrays

int total = 0; double [,]matrix = new double[3,3]; /* indices 0-2, 0-2 */

foreach (int v in myPrimes2) { for (int i = 0; i < 3 ; i++) { total += v; for (int j = 0; j < 3; j++) { } matrix[i, j] = 0.0; } } slide 29 slide 30 gaius gaius Version 2: An Improvedmethod of Chasing game iterative overanarray

returning to our game, we could extend our main double [,]matrix = new double[3,3]; /* indices 0-2, 0-2 */ function to include the concept of a leveland initialise a 2D world from reading a file for (int i = 0; i < matrix.GetLength (0); i++) { for (int j = 0; j < matrix.GetLength (1); j++) { matrix[i, j] = 0.0; } public static void Main () } { if (completed_all ()) Console.WriteLine ("well done, you have completed\ all levels and your score was {0}", score); else Console.WriteLine ("you died with a score of {0}", score); }

slide 31 slide 32 gaius gaius Using file input to configurethe game Using file input to configurethe game

useful to configure levels using plain ascii text ########################################## #...... ##...... # #.########.########.##.########.########.# #.########.########.##.########.########.# #.########...... ########.# #...... #########.##########...... # ##.#######.##...... ###.###.###### #..#######.##.##....p....##.###.###....### ##.#######....##...... ##.....###.###### #...... ##.#############.###...... ## #.######.####...... #######.## #..#####.####.#############.###.#######.## ##.#####.####...... ###...... ###...... # #...... #########.###.#################.# #.################.###.#################.# #m...... # ########################################## slide 33 slide 34 gaius gaius Using file input to configurethe game Using file input to configurethe game

public static bool completed_all () public static bool load_level (int level) { { while (load_level (level)) StringBuilder filename = new StringBuilder (); { string f; if (! completed_level ()) return false; filename.AppendFormat ("level{0}", level); level += 1; f=filename.ToString (); } if (File.Exists (f)) return true; return read_file (f, level); } else return false; }

slide 35 slide 36 gaius gaius Using file input to configurethe game Using file input to configurethe game

public static bool read_file (string filename, int no) public static bool completed_level () { { int row = 0; Console.Clear (); FileInfo f = new FileInfo (filename); while (! level_finished ()) StreamReader r = f.OpenText (); { string line; char ch = ’z’;

blank_grid (); redraw (); if (GetCharTimeout (ref ch)) line = r.ReadLine (); process_input (ch); while (line != null) else { if (! move_monster ()) process_line (line, row); return false; row++; } line = r.ReadLine (); return gathered_food (); } } Console.WriteLine ("finished reading file"); return true; } slide 37 slide 38 gaius gaius Using file input to configurethe game Using file input to configurethe game

public static bool gathered_food () public static bool GetCharTimeout (ref char ch) { { return food == 0; for (int i = current_delay; i > 0; i -= 40) } { if (GetChar (ref ch)) return true; else Thread.Sleep (40); // 40 millisecs } return false; }

slide 39 slide 40 gaius gaius Using file input to configurethe game Tutorial Questions

public static bool GetChar (ref char ch) download the 〈http:// { floppsie.comp.glam.ac.uk/download/ if (Console.KeyAvailable) { csharp/robot.cs〉 code and 〈http:// ConsoleKeyInfo k = Console.ReadKey (); floppsie.comp.glam.ac.uk/download/ if (k.Key == ConsoleKey.Escape) csharp/level1〉 file Environment.Exit(0);

ch = k.KeyChar; return true; build it and see the game start } return false; } copylev el1 to level2 nowedit level1 and makesome changes

notice that the move_monster code is a dummy function complete it notice that it movesright, but not up, down or left extend the right code appropriately slide 41 gaius Tutorial Questions

examine the key input routines, notice the ref parameters notice howaref parameter can be passed to another ref parameter

finish the scoring for the game implement the reduced thinking time the human has ev ery move made implement a well feature ’w’ on the map, so that if a monster falls into a well the monster respawns back at the initial position howmight you improve the move_monster function? howmight you add multiple monsters? what changes need to be made to the code? hint maybe use 1, 2, 3 and 4 in the leveldesign to represent initial positions of the four monsters change the code so that four monsters chase you