Download Loops in C# Statement sequences do while loop and more Summaries Advanced Computer Programming in PDF only on Docsity!
slide 2 gaius
Loops in C#
while loop
do while loop
for loop
foreach loop
choose them wisely, a good choice of loop can make
your code cleaner
slide 3 gaius
Statement sequences
in the following slides statementsequences is used
in C# this can mean
a single statement
or a compound statement
a compound statement starts with { and ends with a }
individual statements are separated by ;
slide 4 gaius
do while loop
syntax of this loop is
do statementsequences; while (expr);
it should be used when the loop must run at least
once
remember the guessing number game, you must
make at least one guess!
gaius
while loop
syntax of this loop is
while (expr) statementsequences;
useful if there are occasions when the loop body
statementsequence should never execute
sometimes called a N and a ½ loop
N times around the loop, but it requires some set
up for the initial conditional expression
gaius
while loop
char ch;
ch = f.ReadChar (); // the ½ component while (ch != ’z’) { ... // the N component ch = f.ReadChar (); }
slide 7 gaius
for loop
allows us to combine the N and ½ loop into one
compound statement
the syntax is:
for ( initialisers ; expression; iterators ) statementsequences;
slide 8 gaius
for loop
for (int i = 1; i <= 12; i++) Console.WriteLine ("8 x {0} = {1}", i, 8*i);
and
for (int i = 1; i <= 12; i++) { 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
gaius
Example function, implementing a delay
function
suppose we want a delay of ¼ of a second in our
program we might write:
public static void delay () { Thread.Sleep (250); // sleep for 250 milliseconds }
gaius
Example function, implementing a delay
function
we can call this in our program, like this:
slide 15 gaius
Example function, implementing a delay
function
using System; using System.Threading;
public class test { 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 16 gaius
Example function, implementing a delay
function
sometimes it is useful to use a function to change the
name of the action
as in the case above
gaius
Example function, implementing a delay
function
we notice that the previous code is the skeleton for a
game loop
it would be interesting to explore whether we can poll
the keyboard for input and take action if no input is
seen
it would give us the ability to produce retro
console based games
at the same time it allows us to explore how functions
operate
gaius
Example function, implementing a delay
function
consider the main method (function):
public static void Main () { char ch = ’a’; // variable is assigned as not ’x’
Console.Clear (); // clears screen do { if (GetChar (ref ch)) Console.WriteLine ("you typed {0}", ch); else { Console.WriteLine ("move monster"); delay (); } } while (ch != ’x’); }
slide 19 gaius
Reference parameters
we are calling our own function GetChar which will
return a bool value indicating whether a keyboard
character has been pressed by the user
if true is returned then the parameter, ch, will
be the pressed key
otherwise it is left alone
notice that we are not passing the value into the
function, but rather the address (or reference) of the
variable
the function uses the address to assign a new value to
the variable
which is seen by the caller
slide 20 gaius
Reference parameters
the function must also be declared knowing that this
parameter is a reference parameter
public static bool GetChar (ref char ch) { if (Console.KeyAvailable) { ConsoleKeyInfo k = Console.ReadKey (); ch = k.KeyChar; return true; } return false; }
gaius
Declaring arrays in C#
example declare an integer array
int[] myArray;
instantiate an array to contain five integer values (all
zero)
myArray = new int[5];
gaius
Initialising arrays
int[] myPrimes1 = new int[5] {1, 2, 3, 5, 7}; int[] myPrimes2 = {1, 2, 3, 5, 7};
int[] myArray2 = new int[10];
for (int i = 0; i < myArray2.Length; i++) { myArray2[i] = 42; }
slide 27 gaius
Initialising arrays
int total = 0;
foreach (int v in myPrimes2) { total += v; }
slide 28 gaius
Multidimensional arrays
double [,]matrix = new double[3,3]; /* indices 0-2, 0-2 *
for (int i = 0; i < 3 ; i++) { for (int j = 0; j < 3; j++) { matrix[i, j] = 0.0; } }
gaius
Version 2: An Improved method of
iterative over an array
double [,]matrix = new double[3,3]; /* indices 0-2, 0-2 */
for (int i = 0; i < matrix.GetLength (0); i++) { for (int j = 0; j < matrix.GetLength (1); j++) { matrix[i, j] = 0.0; } }
gaius
Chasing game
returning to our game, we could extend our main
function to include the concept of a level and
initialise a 2D world from reading a file
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}", s }
slide 31 gaius
Using file input to configure the game
useful to configure levels using plain ascii text
slide 32 gaius
Using file input to configure the game
#..#######.##.##....p....##.###.###....### ##.#######....##.........##.....###.###### #..........##.#############.###.........## #.######.####...................#######.## #..#####.####.#############.###.#######.## ##.#####.####......###......###..........# #........#########.###.#################.# #.################.###.#################.# #m.......................................# ##########################################
gaius
Using file input to configure the game
public static bool gathered_food () { return food == 0; }
gaius
Using file input to configure the game
public static bool GetCharTimeout (ref char ch) { 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 gaius
Using file input to configure the game
public static bool GetChar (ref char ch) { if (Console.KeyAvailable) { ConsoleKeyInfo k = Console.ReadKey ();
if (k.Key == ConsoleKey.Escape) Environment.Exit(0);
ch = k.KeyChar; return true; } return false; }
slide 40 gaius
Tutorial Questions
download the 〈http://
floppsie.comp.glam.ac.uk/download/
csharp/robot.cs〉 code and 〈http://
floppsie.comp.glam.ac.uk/download/
csharp/level1〉 file
build it and see the game start
copy level1 to level
now edit level1 and make some changes
notice that the move_monster code is a dummy
function
complete it
notice that it moves right, 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 how a ref parameter can be passed to
another ref parameter
finish the scoring for the game
implement the reduced thinking time the human has
every 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
how might you improve the move_monster
function?
how might you add multiple monsters?
what changes need to be made to the code?
hint maybe use 1 , 2 , 3 and 4 in the level design
to represent initial positions of the four monsters
change the code so that four monsters chase you