CSci 1113, Fall 2015 Lab Exercise 11 (Week 13): Discrete Event Simulation. Warm-up. Stretch

Similar documents
CSci 1113, Fall 2018 Lab Exercise 11 (Week 13): Graphics. Warm-up

CISC 1600, Lab 2.1: Processing

1 Getting started with Processing

CMPSCI 119 LAB #2 Anime Eyes Professor William T. Verts

Variables One More (but not the last) Time with feeling

CISC 1600, Lab 3.1: Processing

1 Getting started with Processing

Chapter 6 Introduction to Defining Classes

Sudoku-4: Logical Structure

CMPSCI 119 LAB #2 Greebles / Anime Eyes Professor William T. Verts

Programming Project 1

Repe$$on CSC 121 Spring 2017 Howard Rosenthal

Control Flow: Loop Statements

We will start our journey into Processing with creating static images using commands available in Processing:

CISC 1600 Lecture 3.1 Introduction to Processing

Assignment 4. Aggregate Objects, Command-Line Arguments, ArrayLists. COMP-202B, Winter 2011, All Sections. Due: Tuesday, March 22, 2011 (13:00)

CS Programming Exercise:

CISC 1600, Lab 2.3: Processing animation, objects, and arrays

Introduction to Internet of Things Prof. Sudip Misra Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

CSci 1113 Lab Exercise 6 (Week 7): Arrays & Strings

CS 134 Programming Exercise 9:

Pre-Lab Excel Problem

Art, Nature, and Patterns Introduction

+ Inheritance. Sometimes we need to create new more specialized types that are similar to types we have already created.

CS1950U Setup Spring 2018

egrapher Language Reference Manual

Laboratory Exercise 5

Programs as Models. Procedural Paradigm. Class Methods. CS256 Computer Science I Kevin Sahr, PhD. Lecture 11: Objects

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Introduction. Create a New Project. Create the Main Form. Assignment 1 Lights Out! in C# GUI Programming 10 points

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Structured Programming Using C++ Lecture 10 : Graphics Programming with the Dark GDK Library. Dr. Amal Khalifa. Lecture Contents:

Animations that make decisions

Activity: page 1/10 Introduction to Excel. Getting Started

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Unit 1 Lesson 4. Introduction to Control Statements

Create a memory DC for double buffering

Introduction to Processing

Defining Classes and Methods

1. Complete these exercises to practice creating user functions in small sketches.

Basic Computer Programming (Processing)

ASSIGNMENT 2. COMP-202A, Fall 2013, All Sections. Due: October 20 th, 2013 (23:59)

CSci 1113, Fall 2015 Lab Exercise 7 (Week 8): Arrays! Strings! Recursion! Oh my!

What can we do with Processing? Let s check. Natural Language and Dialogue Systems Lab Guest Image. Remember how colors work.

Class #1. introduction, functions, variables, conditionals

Microscopic Measurement

Introduction to Programming Using Java (98-388)

In this lecture we will briefly examine a few new controls, introduce the concept of scope, random numbers, and drawing simple graphics.

Bridging Graphics. Lori Scarlatos, January 2007

The Fundamentals. Document Basics

Programming Exercise

Name: Dr. Fritz Wilhelm Lab 1, Presentation of lab reports Page # 1 of 7 5/17/2012 Physics 120 Section: ####

Notes from the Boards Set # 5 Page

int a; int b = 3; for (a = 0; a < 8 b < 20; a++) {a = a + b; b = b + a;}

Animations involving numbers

Tutorial 3: Constructive Editing (2D-CAD)

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

CS Multimedia and Communications. Lab 06: Webpage Tables and Image Links (Website Design part 3 of 3)

Solution Notes. COMP 151: Terms Test

MATLAB Introduction to MATLAB Programming

Creating Vector Shapes Week 2 Assignment 1. Illustrator Defaults

DEC HEX ACTION EXTRA DESCRIPTION

2IS45 Programming

APCS Semester #1 Final Exam Practice Problems

CSci 1113 Lab Exercise 5 (Week 6): Reference Parameters and Basic File I/O

Fall 2013 Program/Homework Assignment #2 (100 points) -(Corrected Version)

Laboratory Exercise 8

Shape Cluster Photo Written by Steve Patterson

L E S S O N 2 Background

Shapes leading to CAD system project

EEN118 LAB TWO. 1. A Five-Pointed Star.

Picket Patterns. Overview

Bits and Bytes. How do computers compute?

In this lesson you are going to create a drawing program similar to Windows Paint. 1. Start with a new project and remove the default cat sprite.

What is a variable? a named location in the computer s memory. mousex mousey. width height. fontcolor. username

(0,0) (600, 400) CS109. PictureBox and Timer Controls

The way I feel about music is that there is no right and wrong. Only true and false. Fiona Apple. true false false

Repe$$on CSC 121 Fall 2015 Howard Rosenthal

Raster Data Model & Analysis

Instructions for Crossword Assignment CS130

Defining Classes and Methods. Objectives. Objectives 6/27/2014. Chapter 5

Name: SID: LAB Section: Lab 6 - Part 1: Pixels and Triangle Rasterization

form are graphed in Cartesian coordinates, and are graphed in Cartesian coordinates.

Computer Graphics Prof. Sukhendu Das Dept. of Computer Science and Engineering Indian Institute of Technology, Madras Lecture - 14

Introduction to Google SketchUp

CS 455 Midterm Exam 1 Fall 2017 [Bono] Thursday, Sep. 28, 2017

Notes from the Boards Set BN19 Page

Final Exam Winter 2013

CSCI 161 Introduction to Computer Science

Part 1. Summary of For Loops and While Loops

The HOME Tab: Cut Copy Vertical Alignments

Graphics User Defined Forms, Part I

[ the academy_of_code] Senior Beginners

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Chapter 1: Introduction to the Microsoft Excel Spreadsheet

Give one example where you might wish to use a three dimensional array

(Refer Slide Time: 00:02:00)

Getting Started. In This Chapter

Assignment 1: grid. Due November 20, 11:59 PM Introduction

CS 307 Midterm 1 Fall 2007

Transcription:

CSci 1113, Fall 2015 Lab Exercise 11 (Week 13): Discrete Event Simulation It's time to put all of your C++ knowledge to use to implement a substantial program. In this lab exercise you will construct a complete simulation program that employs many of the object-oriented techniques presented in class to model and visualize a forest fire 1. Forest fires that threaten property and lives have been prominent in recent news items. Computer simulations of forest fires provide information that fire fighters can use to stop the fire. In this project you will simulate the spread of a fire using a Tree class and a Forest class with the forest represented by a two-dimensional array of Tree objects. Simple rules, together with the rand() pseudo-random number generator, will be used in the simulation. --------------- 1. Adapted from Introduction to Computational Science: Modeling and Simulation for the Sciences by Angela B. Shiflet and George W. Shiflet, Princeton University Press, 2006 Warm-up 1) Introduction to GraphX If you want a more detailed description of the GraphX class, see the Appendix. Download the sample. cpp from the website and compile it by running (in a terminal with all the files in the current directory): g++ GraphX.o lx11 sample.cpp Note: the third word is ell ex eleven. Everything is also case sensitive, so ensure the line is exactly as above. Then run the program by typing:./a.out Once you grow bored of the simple program, look at sample. cpp and see how it works. The majority of work is done by the GraphX class, which you should take a look at in GraphX. hpp. Once you look over what you have to work with, show the TAs the sample. cpp program running to be checked off. Stretch 1) Orbit Using GraphX, write a simple program that will display an "orbiting" circle animation. The computational approach is straightforward: Given an angular measurement theta (in degrees) and a fixed radius value r, construct a simple loop that will continuously increment the angular value from 0 through 360 degrees and plot a filled-circle at the x,y coordinates given by the polar coordinates (theta, r). This should continue until some mouse event takes place to terminate the loop. 1

Your program should perform the following GraphX operations: Instantiate a GraphX object Change the units scale of the GraphX window to 400x400 by invoking the following GraphX method:.scale(400,400) Set the plotting symbol to "solidcircle" using the. symbol method Set the symbolsize to 30 pixels Set the pencolor to some color other than black or white Implement a while loop that will continue running until the GraphX input is something other than "none" The loop should compute the x,y coordinates of the orbiting circle and plot it relative to the center of the window (e. g., x + 200, y + 200), then increase the value of the angle theta by 1 degree (mod 360) and repeat the process. In order to animate the orbiting circle, immediately after plotting the filled circle, set the drawing delay to. 02 seconds and then. erase() the circle you just plotted. (The delay will cause the circle to show for a brief time before plotting the next circle). The effect should be the filled circle orbiting the window center. [ Hint: the polar coordinate conversion must use the cmath functions cos and sin which require the angle in radians ] Workout Now that you are able to plot and draw using GraphX, you are ready to tackle the Forest Fire simulation. This is a discrete simulation that will use basic object-oriented techniques to model trees and forests and visualize the progression of the fire using graphical output. Complete each of the following in order. 1) Tree Class The Tree class can represent various kinds of trees, including a null tree, i. e., a location in the forest that does not have a tree. The Tree class will have the following: Private data members: type (string) - the species of the tree (e. g., "Oak", "not_a_tree") probcatch (double) - the probability (0. 0 to 1. 0) of the tree catching on fire status (int) - the tree's status as follows: 0 - not a tree (for a forest location without a tree) 1 - a live tree (i. e., not burning) 2 - a burning tree wetness (double) - a number between 1. 0 and 100. 0 to indicate wetness (default 1. 0) burntime (int) - the number of time steps for a tree to burn (default 1) xpos (int) - the x position of the tree within a GraphX window (default 0) ypos (int) - the y position of the tree within a GraphX window (default 0) symbol (string) - the symbol used to draw the tree within a GraphX window (e. g. solidtriangle ) 2

Public member functions: A default constructor to set the default values ("not_a_tree", 1. 0, 0, 1. 0, 1, 0, 0, solidtriangle ) A constructor with parameters to let the user initialize data members getprobcatch() - an accessor function for the probcatch data member setprobcatch() - a mutator function to set probcatch getstatus() - an accessor function for the status data member setstatus() - a mutator function to set status getwetness() - an accessor function for the wetness data member setwetness() - a mutator function to set wetness getburntime() - an accessor function for the burntime data member setburntime() - a mutator function to set burntime Put the declaration part of the Tree class in file Tree. hpp and the implementation part in file Tree. cpp. Write a driver program to test the Tree class. 2) Drawing a Tree Trees will be displayed as graphical objects on a GraphX display. To display a Tree, add a void public member function to Tree named draw. The draw method will take a GraphX object (passed by reference) as its only argument and do the following: Move the pen to the x,y coordinates of the tree (make sure the pen is up!) Set symbol size to 10 pixels Set symbol to the symbol specified by the tree attribute Get the status of the tree. If the status is: 0: set the pen color to white 1: set the pen color to green 2: set the pen color to red plot the symbol Test the output of your Tree by instantiating a GraphX object of size 800 by 800 in your main function and drawing default, living, and burning trees on it at different positions. Note: GraphX will exit immediately unless you devise a way to sleep the program after displaying your trees! 3) Forest Class A forest will be represented by a two-dimensional array of Tree objects with 33 rows and 33 columns. The Forest class will initially have the following: Private data member: grid A 33x33 array of Tree objects Public member functions (see descriptions below): Forest() - default constructor draw(graphx&) - calls the draw method for each Tree object in the grid The default constructor should initialize each boundary cell of the grid array to a Tree object named "not_a_tree" with probcatch = 0, status = 0, and symbol = "solidtriangle". 3

The interior cells should each be initialized to a Tree object with probcatch = 0. 80, status = 1, and symbol = "solidtriangle" except for the single cell in the center of the grid which should be initialized to a burning Tree object, i. e., one with status = 2. Use wetness = 1. 0 and burntime = 1 for all trees. To initialize the position of the trees, each tree will be placed at 25 pixel intervals. For example: grid[0][0] should be at pixel location 0,0 grid[0][1] should be at pixel location 0,25 grid[1][0] should be at pixel location 25,0 grid[32][32] should be at pixel location 800,800 Here is the default grid array: 4

Put the declaration part of the Forest class in file Forest. hpp and the implementation part in file Forest. cpp. Write a driver program to test the Forest class. 4) Burning Trees Two member functions need to be added to the Forest class to cause the fire to spread from one tree to another: nextstatus() and applynextstatus() Note that each cell of grid is a Tree object. Use the getstatus() function of the Tree class to get the status of each cell and the setstatus() function to change it. Also, each Tree object has a probcatch value. nextstatus() Function nextstatus() has int parameters i and j for the row and column indices of grid and returns the status value of cell grid[i][j] for the next time step as follows: If the cell is empty (status = 0) it remains empty If the cell has a tree (1) then it will become a burning tree (2) if one or more of its neighbors (top, bottom, left, or right) is burning AND a random number between 0. 0 and 1. 0 is less than the object's probcatch value; otherwise it stays a tree If the cell has a burning tree (2) it becomes empty (0) applynextstatus() Function applynextstatus() applies nextstatus to each interior cell of the grid to generate a new grid array representing the next time step in the simulation. The function should: Copy grid to a new 2D array of Tree objects named next_grid Use a doubly nested loop and the nextstatus function to determine the status values for the interior cells of next_grid Copy next_grid to grid Note: when a member function of a class calls another member function, the dot operator is not used. For example, to call nextstatus from applynextstatus do int stat; stat = nextstatus(i,j); Test the nextstatus() and applynextstatus() methods in a calling program. 5) The Forest is Burning! (Fire Simulation) Write a Forest method named isburning() that returns the boolean value true if at least one cell in grid has a burning tree (i. e., status = 2) and false otherwise. Now write a main program that will: Instantiate a default Forest object. Use a while loop that calls applynextstatus until isburning becomes false. Draw the Forest at each iteration of the loop. 5

Challege 1) Build a Better Forest You now have a forest fire simulator, but the forest has only one kind of tree and the fire always starts with one burning tree in the center. So, add a member function to the Forest class named setgrid() that has six parameters: i, j - the coordinates of a grid cell prob - used to set the value of probcatch for the Tree object in the cell stat - used to set the value of status for the Tree object in the cell wet - used to set the value of wetness for the Tree object in the cell burn - used to set the value of burntime for the Tree object in the cell For example, the following will set the Tree in location 3,6 to have probcatch = 0. 95, status = 1, wetness = 1. 0, and burntime = 1: Forest blue; blue.setgrid(3, 6, 0.95, 1, 1.0, 1); After you've tested setgrid, write a program to instantiate a default Forest object and then use setgrid to populate the northern half of the forest with trees that burn easily (probcatch = 0. 8) and the southern half with trees that do not (probcatch = 0. 2). Then set a fire somewhere and burn the forest to see what happens. 2) A Lightning Storm A forest fire can be started by lightning. Add a member function to the Forest class called lightning to cause trees in a forest to catch fire if struck by lightning. The lightning function will have a parameter lightprob of type double, where lightprob is the probability of a tree catching on fire if struck by lightning (a value between 0. 0 and 1. 0). Use the following rule to create the function: check grid location containing a tree (status = 1); it becomes a burning tree (status = 2) if a random number between 0. 0 and 1. 0 is less than lightprob. (Generate a new random number for each location containing a tree. ) Write the statements that would appear in a calling function to Instantiate a Forest object Invoke the lightning method to have lightning strike the forest (try probability = 0. 05) With this initial configuration, run the fire simulation to burn the forest. Appendix: Graphical output will be used to display the progress of the simulation as it unfolds in time. We've created an object-based software package called GraphX for you to use that simplifies graphical output in C++ programs. Using the GraphX class is simple; you simply instantiate a GraphX object and interact with it using simple object method calls. When you first create a GraphX object, the 6

graphics environment is initialized and a blank window appears on the computer display. You draw lines and shapes on the window using various methods of the GraphX class. GraphX models drawing on a blank sheet of paper using a simulated pen. The graphics pen can be in one of two states: up or down, and can be moved anywhere within the window by providing new x (horizontal) and y (vertical) pen coordinates. If the pen is up, moving it has no effect other than changing its location. If the pen is down, moving it will cause a line to be drawn from its original location to the new one. Initially, the pen location is at x = 0, y = 0, the coordinates of the lower left corner of the window. To invoke the graphics display engine and create a visible window on your terminal, you simply declare a xnamed instance of a GraphX object, e. g.,: GraphX mywin; Instantiating a GraphX object initializes the graphics functions and displays an 800 x 600 pixel graphics window on the terminal. The window will remain visible and active until the GraphX object goes out of scope and is de-allocated. If the GraphX object is declared locally in your main() function or in the global name space, it will remain visible and active until the program is terminated. You can create multiple graphics windows by declaring additional GraphX objects. You can also alter the size of the initial window by providing the width and height to the GraphX constructor: GraphX mywin(800,800); The width and height are specified in pixel units. Each pixel is one "dot" on the video display. Interacting with a GraphX display is straightforward. After the object is declared, you simply invoke member functions as needed to draw lines and plot symbols. Here's an example that draws a square: mywin.clear(); // mywin.setpos(50,50); // move the pen to x=50, y=50 mywin.pendown(); // enable drawing by putting pen down mywin.setpos(50,150); // draw a vertical line upward mywin.setpos(150,150); // draw a horizontal line to the right mywin.setpos(150,50); // draw a vertical line downward mywin.setpos(50,50); // complete the square It's not really any more complicated than that! In fact, it is often easier as there are pre-built functions to draw common shapes (and you can specify the size). Here is a short list of important drawing methods: void.clear() void.setpos( x_location, y_location ) Clear the graphics display Move the pen location to the specified coordinates. x_location and y_location are integer distances from the origin at the lower left corner 7

void.pendown() void.penup() void.delay( delay_time ) string.input() Enable line drawing Disable line drawing Delay the start of the next GraphX operation. delay_time is a floating-point value specifying a fractional number of seconds (e. g., 1. 25) Get mouse/keyboard event status You can also display symbols at the current pen location using the. symbol() and. plot() methods. Here's an example that will move the pen and plot a green filled-circle at the pen location: mywin.penup(); // just move, don't draw! mywin.setpos(300,400); // move to location x=300, y=400 mywin.symbol("solidcircle"); // we'll draw a filled in circle mywin.symbolsize(30); // 30 pixels across mywin.pencolor("green"); // and green mywin.plot(); // plot it at the pen location And if you want to erase the symbol that was just plotted, it's easy: mywin.erase() // remove the symbol at the pen location There are many GraphX methods but you will only need a few for this Lab Exercise. Here's a summary of some of the more useful pen and plotting methods: void.plot() void.symbol( symbol_name ) void.symbolsize(size) void.pencolor(color) 8 Plot a symbol at the pen location Specify the symbol that will be plotted when.plot() is invoked. symbol_name is a string from the following list: "circle" "square" "diamond" "triangle" "invtriangle" "solidcircle" "solidsquare" "soliddiamond" "solidtriangle" "solidinvtriangle" Set the symbol size in integer number of pixels Specify the line and symbol color to use for drawing. color is a string from the following list: "black"

"white" "red" "yellow" "blue" "green" "orange" "purple" Obtaining Input GraphX input is not like the >> and << operations you've been using. The stream input and output operations are blocking, that is they do not return control to your program until the user actually enters something. The GraphX input() function is non-blocking. It returns status immediately regardless if the user has entered anything or not. The input() member function immediately returns one of the following event strings: "leftbutton", "rightbutton" or "keypress" corresponding to a left mouse button press, a right mouse button press or a keyboard key press respectively. If no input has occurred since last checking the input status, the input() function will immediately return the string "none". Non-blocking input requires that your program continually check (using a loop) the status of graphics input events. For example, the following loop checks for either left or right mouse button press events: bool done = false; while(!done) { string input = mywin.input(); if (input == rightbutton ) done = true; if (input == leftbutton ) processbuttonpress(); } Getting started Download the files GraphX. o and GraphX. hpp from the "Lab Information" section of the class website. You do this by simply clicking on them. These files go directly into your downloads (~/Downloads) folder. Copy them into your active lab directory using the Unix cp (copy) command. To use GraphX in your program, you must first include the header file in your source code: #include "GraphX.hpp" The quotation characters are used in place of "< >" to indicate that the header file is located in your current working directory. The GraphX class implemention and the Unix graphics library must be included when you compile your program. To do this, you must use the following compile command: 9

g++ GraphX.o lx11 yourprogram.cpp yourclass.cpp The third word is minus ell ex eleven. NOTE: GraphX. o will only work with the Unix X-window library. You might not be able to use this on your own computer. 10