ics2O_smallbasic

include component="page" page="course_tabs_header"

include component="page" page="menu_ics2O_crumbs"

=s//mall//Basic=

Microsoft has a freeware package for simple programming called [|smallBasic].

Install smallBasic and copy the following into the code window:

'Starting with a text window for the settings TextWindow.WriteLine("Hello World")

//TRYTHIS: What about "printing" something else?//

Press the large play button (or faster yet, hit F5) and what happens? You have written and run your first bit of code! What about a more difficult bit of code. Copy the contents of to the smallbasic code window. Run it. What do you notice?

What about FAR more complex problems?

Problem Solving
Steps to problems solving in Computer Programming can be dead simple. They consists of:
 * 1) identify the problem,
 * 2) create a plan (using [|algorithm]and/or [|pseudocode])
 * 3) write the code and test it
 * 4) review for optimal solutions.

E.g. what are the steps to getting a pizza delivered to your home? What are the steps to filling your car with gas?

With smallBasic there are certain pieces of code, think of them as tags from HTML, that will allow you to solve your problem. They will appear as you begin typing in smallBasic.

Let's start with some of the basics of computer programming:

Sequential Programming
Literally, a set of instructions to be run in a pre-programmed sequence. There are several other types of concepts in computer science, but we'll address those shortly. In older versions of programming BASIC sequential lines of code used to be numbered and the computer would actually run according to this number. Number lines are no longer necessary, but still, code runs in order until you tell it to do otherwise.


 * Concepts in Sequential Programming:**
 * There are only 16 command in all of small basic
 * input
 * something a user types into the computer as part of a program
 * variable: something that can take on any given value (text or #)
 * a String Variable
 * (usually logical), which holds in memory, some input from a user
 * e.g. name = user's inputted name when prompted
 * a = text input
 * Integer Variable
 * mathematical operations can be done on it
 * a = whatever # is of interest
 * BEDMAS rules
 * [|Modulo Operators](math.remainder)
 * logic a=a+2 works in computer programming, but not in standard math. However a+2 = a doesn't work!
 * good way of keeping counters


 * Syntax errors vs. Logic errors**
 * syntax errors occur when you have typing mistakes. E.g. when you type textWindow.reed instead of textWindow.read in smallBasic. Logic errors occurs when there is a fallacy of reasoning. i.e. In python, typing if x 5. Since a value can't be less than 0 and greater than 5, a logical error will occur.

Try the following things in smallBasic ([|smallBasic reference guide] and [|API references] and a [|complete list of commands]):
 * 1) Print the following sentence - "Hello World ", and in the next line down "I am Dave, the supercomputer"
 * 2) Write a small program that asks the user to input their name, then captures that name, then prints it on the following line along with the line "i'm happy to meet you //name//")
 * 3) Write a small program that converts a user-prompted variable in celcius to farenheight and prints the answer.

Assignment #4
1. Write a program that will display the following when you run it:

Mr. McIntyre Rocks the world

2. Write a program that displays the following:

This

is

awesome

3. Write a program that displays the above information but using each line as a variable that is a character string instead of plain text. 4. Write a single program that has 10 variables (A-J, the integer value for each variable is your choice and hardcoded into the program) and displays the following: 5. Using BEDMAS rules, calculate the value of VALUE in this expression where B=6, C=10, D=5, E=3, and F=4 6. Write a program that: 7. Write a basic program that reads the user's input of an integer, then prints that integer in a cleared window. 8. Write a basic program that prompts the user to enter a decimal number of any length, then prints the rounded number in a cleared window. 9. Write a basic program that reads the user's input of their marks in their courses, then displays their rounded numerical average in a cleared window. 10. Write a basic program that both creates, then displays 5 random numbers between 1 and 100
 * When the program runs a line “the sum of the variables is”
 * The next visible line will be the calculated sum of the variables is printed after the above statement
 * When the program runs it prints only the sum of the first, fifth and tenth variable AND INCLUDES text saying what it's doing
 * VALUE= B + C / (D - E) * F
 * sets the background colour of the textwindow to blue (hint: remember to make the whole textwindow blue you have to clear it)
 * Asks the user 3 questions and pauses for user input at the end of each question, clearing the screen each time in-between.
 * Prints the resulting 3 answers of the user with text that explains it all.


 * **CATEGORY** || **4** || **3** || **2** || **1** ||
 * **Solutions are elegant**


 * ** || Judicious use of techniques lead to exemplary answers. || Uses techniques correctly leading to a answers of expected quality and context || Answers are missing and/or quality is insufficient to meet expectations || Both quality and quantity of answers do not approach expectations. ||
 * **Product fundamentals (answers are clear and concise)**


 * ** || Fundamental concepts clearly demonstrated beyond expectations. Code is clear and follows convention in a way superior to what was expected. || Fundamental concepts generally demonstrated at level expectations. Code is clear and follows convention in a way that was expected. || Concepts generally demonstrated at level slightly below expectations. Code is somewhat clear and generally follows convention. || Concepts demonstrated at a level below expectations. Code is somewhat difficult to follow and needs refinement in order to approach expectations. ||
 * **Use of Time**
 * ** || Used time well during each class period (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well during most class periods (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well (as shown by observation by teacher and documentation of progress in journal), but required reminders on one or more occasions to do so. || Used time poorly (as shown by observation by teacher and/or documentation of progress in journal) in spite of several reminders to do so. ||

Conditional Logic
In programming, you can evaluate user inputted integers and strings against stored variables to incredible effect. Typical conditional logic commands include __**if, then, else**__. Typical logic would have the programmer checking either inputs or variables against some previous defined value or string to see what outcome should happen. It is important to remember

Usage of conditional logic can be seen as follows: code If (predicate) Then

(consequent)

Else

(alternative)

EndIf code

code if then

-- statements;

elsif condition then

-- more statements;

elsif condition then

-- more statements;

...

else

-- other statements;

endif code

NOTE: We can use the boolean operators as well within the if/then/else statements for example we can write the following:

code textwindow.writeline("Enter a number")

a=textwindow.read

if a<10 then

textwindow.writeline("Your number is <10")

Else

textwindow.writeline("Your number is >=10")

Endif code GOTO statements are also useful in navigating through conditional logic. The GOTO command in a sequential bit of code to redirect the user to a different location within the code (thus forcing a change in the flow of the code). Usage is as follows:

code start:

textwindow.writeline("Enter a number")

a=textwindow.readnumber

if a<10 then

textwindow.writeline("Your number is <10")

Else

GOTO start

Endif code - Notice what happens is that if the number input is greater than 10!

Assignment #5
1. Develop a program that compares the # of hours of playing video games a week against the following scale: 2. Write a program that lets the user know if he/she is of age to get a drivers license based on the user's input. 3. Write a program that has a user continually insert numbers until the user gets the 'right number' (no prompting necessary - and keep the number between 1 and 10) 4. Write a program that has a user guess until they succeed in guessing your favorite colour (keep to basic colours, no fuchsia or salmon) 5. Write a program that give the user feedback of "higher" or "lower" until the user correctly guesses the number between 1 and 100
 * less than 2 hours is "too little"
 * between 2 hours and 4 hours is "normal"
 * between 4 hours and 8 is "excessive"
 * more than 8 hours is "ridonculous!"


 * **CATEGORY** || **4** || **3** || **2** || **1** ||
 * **Diligently follows instruction**


 * ** || Judicious use of techniques lead to exemplary answers. || Uses techniques correctly leading to a answers of expected quality || Answers are missing and/or quality is insufficient to meet expectations || Both quality and quantity of answers do not approach expectations. ||
 * **Product fundamentals**

by teacher and documentation of progress in journal), but required reminders on one or more occasions to do so. || Used time poorly (as shown by observation by teacher and/or documentation of progress in journal) in spite of several reminders to do so. ||
 * ** || Fundamental concepts clearly demonstrated beyond expectations. Code is clear and follows convention in a way superior to what was expected. || Fundamental concepts generally demonstrated at level expectations. Code is clear and follows convention in a way that was expected. || Concepts generally demonstrated at level slightly below expectations. Code is somewhat clear and generally follows convention. || Concepts demonstrated at a level below expectations. Code is somewhat difficult to follow and needs refinement in order to approach expectations. ||
 * **Use of Time**
 * ** || Used time well during each class period (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well during most class periods (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well (as shown by observation

Game #1
You are to create, in increasing complexity (and thus possible mark-value): NOTE: DO NOT INSERT LOOPS....yet... OR
 * A simple trivial-pursuit-type game with questions - out of a possible 75%
 * A choose-your-own-adventure game with no more than 120 lines of code - out of a possible 100%

Your evaluation is as follows: Mac's evaluation (points to look for): Overall evaluation outcome:
 * Code planning (did you plan at all before you started writing code? - are there comments in the code that are readable and clear? Is it easy to follow?)
 * Code logic (Could you game have been written in fewer lines of code? Did you think about your code before you started writing or did your code develop as you wrote and is therefore scattered but functional).
 * Are there flaws in the logic/game?

Game-off
You will be assigned 3 random games to play. You will rank them on SurveyMonkey. Based on the ranking you give the games the top 3 will go into the 'playoff round'. EVERYBODY will play those 3 games and give them a ranking, also on SurveyMonkey (I'll post the link there once these 3 have been decided). Your marks will be based mostly on your game, but there will also be marks and bonuses assigned for class-ranking.

RANK THE GAMES

[all code is functional] by teacher and documentation of progress in journal), but required reminders on one or more occasions to do so. || Used time poorly (as shown by observation by teacher and/or documentation of progress in journal) in spite of several reminders to do so. ||
 * Game rank (how you fare compared to the others - a sliding scale out of the winners mark. If you submit something that fully functions you automatically get 1/2 value or better).
 * Bonuses:
 * Most ridiculous logic
 * [[file:jmcintyre/I like them.mp3|(linky)Most Enjoyable ]]
 * [[file:jmcintyre/so annoying.mp3|(linky)Most hated ]]
 * Best looking visually (not necessarily graphics, but laid-out text, alignment etc...)
 * **CATEGORY** || **4** || **3** || **2** || **1** ||
 * **Planning for success**
 * [comments in code]**
 * ** || Exceptional planning of product leads to exemplary roadmap for success || Planning of product leads to expected level of success || Planning of product is somewhat lacking and leads to expected level of success || Product lacks expected level of planning and or lacks success due to poor planning. ||
 * **Follows expected plan**
 * [code is neat and easily followed]**
 * ** || Judicious use of techniques lead to exemplary product. || Uses techniques correctly leading to a product of expected quality || Product is missing parts and/or quality is insufficient to meet expectations || Both quality and quantity of product does not approach expectations. ||
 * **Product fundamentals**
 * ** || Fundamental concepts clearly demonstrated beyond expectations. Code is clear and follows convention in a way superior to what was expected. || Fundamental concepts generally demonstrated at level expectations. Code is clear and follows convention in a way that was expected. || Concepts generally demonstrated at level slightly below expectations. Code is somewhat clear and generally follows convention. || Concepts demonstrated at a level below expectations. Code is somewhat difficult to follow and needs refinement in order to approach expectations. ||
 * **Use of Time**
 * ** || Used time well during each class period (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well during most class periods (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well (as shown by observation

Repetition (loops)
Loops are used to repeat a block of code. Being able to have your program repeatedly execute a block of code is one of the most basic but useful tasks in programming -- many programs or websites that produce extremely complex output (such as a message board) are really only executing a single task many times. The general loop looks like this:

code for ( variable initialization; condition; variable update ) {

Code to execute while the condition is true

}

repeat

code

There are generally 3 types of loops. The __**for, while, and do..while**__. Each of the types of loops are useful under certain circumstances.

FOR Loop
You can use a For loop __if you know how many times you want the computer to repeat the __ __instructions__. This type of for loop is characterized by counting; enumerating each of the values within a numeric integer range, or arithmetic progression. The range is often specified by a beginning and ending number, and sometimes may include a step value (allowing one to count by twos or to count backwards for instance). A representative example in BASIC is:

code For I = 1 to 10

Loop contents

Next I

code

Often the code can be altered to include logic to escape the loop based on certain conditions:

code //'using a different programming language NOT Small Basic|//

DO I = 1,N

statements !Executed for all values of I, up to a disaster if any.

IF (no good) CYCLE !Skip this value of I, continue with the next.

statements !Executed only where goodness prevails.

IF (disaster) EXIT !Abandon the loop.

statements !While good and, no disaster.

END DO

code

In SmallBasic the syntax used is:

code //'contents repeat the stated # of times//

For i= 1 to 10

TextWindow.WriteLine(i)

EndFor code

When you want to have steps skipped, or a non-linear number counter you can use:

code 'contents repeat with a step of 2

For i= 1 to 10 Step 2

TextWindow.WriteLine(i)

EndFor code Conditional loops using the 'for loop' have the following syntax code j=0 'sets j to 0

'will show whether the loop # i is either odd or even

For i = 1 To 10

j=Math.Remainder(i,2) 'takes the loop number and divides it by 2. The REMAINDER function is the Small Basic equivalent of [|Modulus] only

'yields the REMAINDER of what's left after division by the denominator (2 in this case) e.g. 1/2 = 0 with a remainder of 1. As such j will be 1. 9/3 REMAINDER will

'yield 0 because the number divides evenly into the other number with 0 remaining

TextWindow.WriteLine(j) 'writes the variable to prove to us that it is what we think it is

If j = 0 Then ' condition for when j has a 0 remainder after being divided by two

TextWindow.WriteLine("Even")

Else

TextWindow.writeline("Odd")

endif

EndFor code
 * Now - try changing the code so that the remainder function is (i,3) - see the change?
 * Now - try changing the code so that the loop is for i = 1 to 50 and the remainder function is (i,5)

WHILE Loop
You can use a While loop __if you want the program to repeat the instructions until a specific condition is true__. The while construct consists of a block of code and a condition. The condition is evaluated, and if the condition is true, the code within the block is executed (continually checking that condition). This repeats until the condition becomes false. Because while loops check the condition before the block is executed, the control structure is often also known as a ** pre-test loop **.

code ' Initialize the variables

Dim counter As Integer : counter = 5

Dim factorial As Long : factorial = 1

While counter > 0

factorial = factorial * counter ' Multiply

counter = counter - 1 ' Decrement

Loop

Print factorial ' Prints out the result.

code In the above example, the value of 'factorial' is greater than 0 each time the loop repeats itself until the 6th iteration, at which time the loop exits - at which point the next line of code executes - printing (showing in a textbox.writeline in Small Basic) the variable factorial.

code 'A decreasing counter with an exit-condition

i=20

While i > 10

TextWindow.WriteLine(i)

i=i-1

EndWhile

code

DO-WHILE Loop
The do while construct consists of a block of code and a condition. **First**, the code within the block is executed, and **then** the condition is evaluated. If the condition is true the code within the block is executed again. This repeats until the condition becomes false. Because do while loops check the condition after the block is executed, the control structure is often also known as a **post-test loop**. Contrast with the while loop, which tests the condition before the code within the block is executed.

code 'Initiallizing the variables

Dim counter As Integer = 5

Dim factorial As Integer = 1

Do

factorial = factorial * counter

counter = counter 1

Loop While counter > 0

Console.WriteLine(factorial) code In the above example, the value of factorial is returned after the conditions are met. __In Small Basic there is no DO-WHILE loop per se__....you use the while/endwhile loop and place the condition further on in the code to give you the post-test loop structure.

Try the following: 1. Write a program that displays the numbers 0 to 100 in 5 step increments. 2. Write a program that counts backwards from 100 to 1 displaying each step. 3. Write a program that continues asking for your favorite colour as long as it's not blue.

Independent vs. dependent counters
A __dependent counter__ is one where the variable for the loop is used as part of the code in the loop block. For example: code fred = 0 for i = 3 to 15 step 3 textwindow.writeline(i) 'because i is tied directly to the variable or IS the variable the counter fred is DEPENDENT fred = fred + i textwindow.writeline(fred + ", " + i) endfor

code

An independent counter is one where the variable is initiated outside the loop and is affected simply because it accumulates during the loop, but isn't tied to the loop counter itself. For example: code fred = 15

for i = 10 to 100 'while the variable fred is accumulated (run) IN the loop, it isn't tied to i (or the loop number) fred = fred + 4 textwindow.writeline(fred) endfor code

Assignment#6 Loop questions
1. Write a short loop that will print the phrase “Happy Birthday” ten times. 2. Create a program that displays the loop # that you are on. 3. Create a program that includes an “independent counter” for 15 loops (i.e. a counter that runs independently of the loop number). The program must indicate the loop # and the independent counter # each loop. 4. Write a program that will calculate the interest and year-end balance, each year for ten years, on $5000 deposited in a term account with an interest rate of 8% per year. 5. Design a short interactive program that will prompt the user for a year in the future and then print a list of all the years between now and that user-selected year variable. 6. Design a loop structure that will print the value of the loop counter (typically "i") in one column and the output from the accumulator “t=t+i” (where "i" is the loop number) beside it in another column. The variable “t” begins with a value of 500, and the upper limit of the loop is 15. 7. Design a loop structure that will count backwards. The loop is to print the year and your age beginning with the current year and age, and continue until the loop reaches the year in which you were born. 8. Write a program that will keep track of the sum total of 2 dice rolled 5 times, print off the result each of the 5 times, and print off the total result after the 5 times. 9. Write a program that generates a random number between 1 and 100 and displays that number - only exiting the program if the number is 52 10. Write a program that continues prompting user input for a keystroke forever unless the user presses the key 'r'


 * **CATEGORY** || **4** || **3** || **2** || **1** ||
 * **Diligently follows instruction**


 * ** || Judicious use of techniques lead to exemplary answers. || Uses techniques correctly leading to a answers of expected quality || Answers are missing and/or quality is insufficient to meet expectations || Both quality and quantity of answers do not approach expectations. ||
 * **Product fundamentals**

by teacher and documentation of progress in journal), but required reminders on one or more occasions to do so. || Used time poorly (as shown by observation by teacher and/or documentation of progress in journal) in spite of several reminders to do so. ||
 * ** || Fundamental concepts clearly demonstrated beyond expectations. Code is clear and follows convention in a way superior to what was expected. || Fundamental concepts generally demonstrated at level expectations. Code is clear and follows convention in a way that was expected. || Concepts generally demonstrated at level slightly below expectations. Code is somewhat clear and generally follows convention. || Concepts demonstrated at a level below expectations. Code is somewhat difficult to follow and needs refinement in order to approach expectations. ||
 * **Use of Time**
 * ** || Used time well during each class period (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well during most class periods (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well (as shown by observation

 =Subroutines=

A subroutine is a sequence of program instructions that perform a specific task, packaged as a unit. This unit can then be used in programs wherever that particular task should be performed. Subprograms may be defined within programs (e.g. Small Basic), or separately in libraries that can be used by multiple programs (C+, java). In various languages they are called different things (procedure, a function, a routine, a method, or a subprogram).

As the name subprogram suggests, a subroutine behaves in much the same way as a computer program that is used as one step in a larger program or another subprogram. A subroutine is often coded so that it can be started (called) several times and/or from several places during one execution of the program, including from other subroutines, and then branch back (return) to the next instruction after the call once the subroutine's task is done. In other words, a subroutine can be run from anywhere in the program at any time.

The form of a subroutine is fairly simple in Small Basic. The subroutine is called, then runs its course, then code continues from the point where the subroutine was called (unless otherwise specified).

Try the following:

code TextWindow.WriteLine("Hi")

TextWindow.WriteLine("Press 'H' to cause something magic to happen")

a = TextWindow.readkey

while a <> "H"

wrong

endwhile

TextWindow.WriteLine("Exactly!")

Sub wrong

TextWindow.WriteLine("nope, press it again")

a = TextWindow.readkey

EndSub code

Game #2
You are to create, in increasing complexity (and thus possible mark-value): OR
 * A simple "Who wants to be a millionaire" type game - out of a possible 80% NOTE: your score must be kept and displayed each round.
 * A choose-your-own-adventure game with less than 320 lines of code - out of a possible 100% NOTE: you must have a health and a score counter. The game is over when your health is 0.

Your evaluation is as follows: Mac's evaluation (points to look for):
 * Code planning (did you plan at all before you started writing code?)
 * Code structure (How easy to follow your code and syntax - including spelling)
 * Code logic (Could you game have been written in fewer lines of code? Did you think about your code before you started writing or did your code develop as you wrote and is therefore scattered but functional). /5
 * Code functionality (does it work?)
 * No flaws
 * Some minor flaws, but still quite functional
 * Some major flaws, but code still executes
 * Major flaws, code won't execute, but is present

Overall evaluation outcome:

Game-off
You will be assigned 3 random games to play. You will rank them on SurveyMonkey. Based on the ranking you give the games the top 3 will go into the 'playoff round'. EVERYBODY will play those 3 games and give them a ranking, also on SurveyMonkey (I'll post the link there once these 3 have been decided). Your marks will be based mostly on your game, but there will also be marks and bonuses assigned for class-ranking.

RANK THE GAMES


 * Game rank (how you fare compared to the others - a sliding scale out of the winners mark. If you submit something that fully functions you automatically get 1/2 value or better).
 * Bonuses:
 * Most ridiculous logic
 * [[file:jmcintyre/I like them.mp3|(linky)Most Enjoyable ]]
 * [[file:jmcintyre/so annoying.mp3|(linky)Most hated ]]
 * Best looking visually (not necessarily graphics, but laid-out text, alignment etc...)
 * **CATEGORY** || **4** || **3** || **2** || **1** ||
 * **Planning for success**
 * ** || Exceptional planning of product leads to exemplary roadmap for success || Planning of product leads to expected level of success || Planning of product is somewhat lacking and leads to expected level of success || Product lacks expected level of planning and or lacks success due to poor planning. ||
 * **Follows expected plan**
 * ** || Judicious use of techniques lead to exemplary product. || Uses techniques correctly leading to a product of expected quality || Product is missing parts and/or quality is insufficient to meet expectations || Both quality and quantity of product does not approach expectations. ||
 * **Product fundamentals**

by teacher and documentation of progress in journal), but required reminders on one or more occasions to do so. || Used time poorly (as shown by observation by teacher and/or documentation of progress in journal) in spite of several reminders to do so. ||
 * ** || Fundamental concepts clearly demonstrated beyond expectations. Code is clear and follows convention in a way superior to what was expected. || Fundamental concepts generally demonstrated at level expectations. Code is clear and follows convention in a way that was expected. || Concepts generally demonstrated at level slightly below expectations. Code is somewhat clear and generally follows convention. || Concepts demonstrated at a level below expectations. Code is somewhat difficult to follow and needs refinement in order to approach expectations. ||
 * **Use of Time**
 * <C4>** || Used time well during each class period (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well during most class periods (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well (as shown by observation

Quiz #1
Create a program that is a combat simulator. You are to have an introductory screen that allows you to pick your class. The following will be available to the player (the player must be able to see the stats for all classes before choosing their class). __Medic__: Hit Points: 50 Damage: 5-7 Self-Heal Chance: heals 4-7 HP 30% of the time.

__Warrior__: Hit Points: 95 Damage: 8-12 power-hit: hits for 15-20 5% of the time

__Bowmaster__: Hit Points: 70 Damage: 7-10 bleed hit: hits for additional 5-8 damage 20% of the time.

Ensure that you set appropriate variables for each of the categories. When the player is done move to a simple combat phase (don't make a story). Combat will continue until either the player is dead, or the monster is dead.

The monster(s) available are: __Troglodyte__: Hit Points: 35-45 Damage: 9-15 Poison Chance: 15% of the time they will damage an additional 8-10 poison damage

__Goblin horde__: randomly between 5-8 goblins at one time Hit Points: 10-14 Damage: 3-6 special attack: none

__Troll__: Hit Points: 75-85 Damage: 30-40 but only hits 50% of the time. special: regenerates 6 HP at the end of each turn.

__**You will be evaluated on the following:**__

Documentation – <B3, C4> 2 marks Program Structure – <A2, B2> 4 marks Completion of Programming Task – <B2, B3> 4 marks

//**[previously]**// //Write a fully functional AND documented program which prompts the user to enter their pizza order. The user has 3 options, small medium and large. They also have the option of having pepperoni (by default) or pepperoni & cheese (an extra).//


 * // Small pepperoni pizzas have the price of $9.99 //
 * // Medium pepperoni pizzas have the price of $12.99 //
 * // Large pepperoni pizzas have the price of $15.99 //
 * // To add extra cheese is to add $0.99 to the cost of the pizza. //

// You must run a program that keeps track of //
 * // the cost of the pizza(s), if there are multiple pizzas, ordered in each order. //
 * // adds tax (13% sales tax) to the pizza and displays it for the customer at the end of the ordering process. //

//**The program is to continue until the "owner" inputs "dayend".**//

//A bonus of 1 mark will be applied if the program tallies the total day's sales and displays it for the owner once dayend is typed in.//

//Place the file in the appropriate HANDIN folder upon completion.//

//This quiz will be evaluated as follows://

//Documentation – 2 marks//

//Program Structure – 4 marks//

//Completion of Programming Task – 4 marks//

//Total – 10 marks//

//a quick pseudo-code solution// code in pseudocode 'setting the variables to their values

priceSmall = 9.99 priceMed = 12.99 priceLarge = 15.99 pizzaTotal = 0 dayEnd = 0
 * 1) small = 0
 * 2) med = 0
 * 3) large = 0

'loop to keep going until the owner wants to quit while pizzaOrder = 0

'ordering info t.wl - "hi, type of pizza (s),(m),(l)?" typeOfPizza = t.read if typeOfPizza = s then #small = #small + 1 elseif typeOfPizza = m then #med = #med + 1 elseif typeOfPizza = l then #large = #large + 1 endif

'option to quit t.wl - "are you done with your order?" quitTime = t.read

'order price calculation if quitTime = yes then pizzaTotal = #small*9.99 + #medium*12.99 + #large*15.99 pizzaTotal = pizzaTotal *1.13 t.wl = total price is pizzaTotal t.clear #small = 0 #med = 0 #large = 0 endif

'triggers the end of the program for day's end.

t.wl- "Is this day's end?" dayEnd = t.read

if dayEnd= "dayend" or dayEnd = "owner" then pizzaOrder = 1 endif

endWhile

t.wl = "thank you and good day"

code

Graphics
//**Let's try this!**// code GraphicsWindow.Show

GraphicsWindow.Title = "Button game"

GraphicsWindow.BackgroundColor = "Black"

GraphicsWindow.Width = 800

GraphicsWindow.Height = 600

GraphicsWindow.PenColor = "white"

GraphicsWindow.DrawLine(100,100,250,250)

code

This program illustrates some basic components of how to use graphics in SmallBasic.
 * 1) The GraphicsWindow.XXX command controls aspects of the graphics window popup such as change the graphics window's background color, height, width, placement relative to the screen's top-left corner, title, and whether the user can resize the graphics window.
 * 2) In SmallBasic there are 4 basic shapes you can draw either full or empty, they are:
 * 3) ellipse (an ellipse of zero eccentricity is a circle)
 * 4) rectangle
 * 5) triangle
 * 6) line (well, you can't really fill this one)

//Now, let's change the drawing a bit - try this://

code GraphicsWindow.Show

GraphicsWindow.Title = "Button game"

GraphicsWindow.BackgroundColor = "Black"

GraphicsWindow.Width = 800

GraphicsWindow.Height = 600

GraphicsWindow.PenColor = "white"

GraphicsWindow.DrawEllipse(100,280,150,400)

code

What did you notice? Let's analyze what happened. We drew our ellipse of y=400 high, BUT, our graphics window is only 600 pixels high AND we started drawing it at 280 which puts our ellipse's end at 680 pixels. When doing graphics you need to constantly remember positioning in your graphics window. Please remember this important fact as we keep going.

Other things you can do with graphics windows are:
 * 1) Displaying images.
 * 2) Resizing existing shapes and images.
 * 3) Getting and changing the color of individual pixels.
 * 4) Responding to user actions such as pressing and releasing keys on the keyboard, moving the mouse, and clicking and releasing mouse buttons.

//let's try this interactive bit of code// code 'creates a graphics window that allows you to click and return something based on the click location

'sets up filepath

filepath = "d:\"

'start of code_________________________________________

GraphicsWindow.Show

GraphicsWindow.Title = "Button game"

'graphics window fill is blue by default_______________________

GraphicsWindow.BackgroundColor = "Black"

GraphicsWindow.Width = 800

GraphicsWindow.Height = 600

'colour fills are blue by default_____________________________

GraphicsWindow.BrushColor = "blue"

GraphicsWindow.FillRectangle(400, 300, 50, 50)

'save the Google image to your root d:\ drive. Uncomment the line below and try it

GraphicsWindow.DrawImage(filepath + "logo1w.png",150,150)

GraphicsWindow.MouseDown = OnMouseDown

Sub OnMouseDown

'looks up the the x and y position_________________________

x = GraphicsWindow.MouseX

y = GraphicsWindow.MouseY

'makes a condition based on what x and y are ________________

If(x >349 And x <451 And y > 249 And y < 351) Then

GraphicsWindow.ShowMessage("Congratulations! You have won the Button game!", "You Won!")

EndIf

EndSub

code

What do we notice about interactivity? By capturing mouse input we have included a level of complexity to our regular programming we've learned. What else can we do? We can capture text, redraw images etc. Here is an example of this interactivity:

code GraphicsWindow.Show

GraphicsWindow.Height = 800

GraphicsWindow.Width = 800

GraphicsWindow.MouseDown = OnMouseDown

GraphicsWindow.MouseUp = OnMouseUp

GraphicsWindow.MouseMove = OnMouseMove

GraphicsWindow.KeyDown = OnKeyDown

GraphicsWindow.KeyUp = OnKeyUp

GraphicsWindow.TextInput = OnTextInput

Sub OnKeyDown

GraphicsWindow.Title = "The " + GraphicsWindow.LastKey + " key was pressed down."

EndSub

Sub OnKeyUp

GraphicsWindow.Title = "The " + GraphicsWindow.LastKey + " key was released."

EndSub

Sub OnMouseDown

GraphicsWindow.Title = "The mouse button was pressed down."

EndSub

Sub OnMouseUp

GraphicsWindow.Title = "The mouse button was released."

EndSub

Sub OnMouseMove

GraphicsWindow.Title = "The mouse moved to " + GraphicsWindow.MouseX + ", " + GraphicsWindow.MouseY + "."

EndSub

Sub OnTextInput

GraphicsWindow.Title = "Some text was input."

If GraphicsWindow.LastKey = "H" then

GraphicsWindow.DrawBoundText(300,300,150,"Holy Crap this works!")

EndIf

If GraphicsWindow.LastKey = "C" Then

GraphicsWindow.Clear

GraphicsWindow.DrawBoundText(300,300,150,"Clear!!!")

EndIf

EndSub

'__________________________

'Sub Timer

'If GraphicsWindow.LastKey = "T" then

'count = count +1

'GraphicsWindow.Clear

'GraphicsWindow.DrawText(200,200,Clock.ElapsedMilliseconds)

'GraphicsWindow.DrawText(400,400,count)

'endif

' EndSub

code

In addition, we perform mathematical operations on the timers:

code ' sets timer interval in milliseconds

Timer.Interval =1000

'sets timer start time

Timer=10

'tells the system that on a tick (event) to do something, in this case - run OnTimerTick subroutine

Timer.Tick = OnTimerTick

Sub OnTimerTick

GraphicsWindow.Clear

GraphicsWindow.DrawText(100,100,Timer)

__'GraphicsWindow.DrawText(100,120,Clock.Millisecond)__

Timer = Timer - 1 'counts the timer down

If Timer <= 0 Then

Program.End

EndIf

EndSub

code Notice how the timer didn't quite get to zero? Why? Uncomment the underlined line of code. What do you notice? So how could we have returned unbiased time?

We can also pull information from the mouse position. Try this:

code GraphicsWindow.Show

GraphicsWindow.Height = 800

GraphicsWindow.Width = 800

GraphicsWindow.MouseMove = OnMouseMove

Sub OnMouseMove

GraphicsWindow.Clear

GraphicsWindow.DrawText(100,100,GraphicsWindow.MouseX)

GraphicsWindow.DrawText(130,100,GraphicsWindow.MouseY)

If (GraphicsWindow.MouseX >= 200 And GraphicsWindow.MouseX <= 300) And (GraphicsWindow.MouseY >= 200 And GraphicsWindow.MouseY <= 250) Then

Program.End

EndIf

EndSub

code

So you ask "How the heck do I make a guy run across the screen?". Patience grasshopper. Let's start with a simple control of a circle.

code '_________________________________________________

'User enters how big and long the grpahics window will be

'_________________________________________________

TextWindow.writeline("How big do you want your screen to be?")

TextWindow.writeline("Height")

gh = TextWindow.Read

TextWindow.writeline("Width")

gw = TextWindow.Read

GraphicsWindow.Height = gh

GraphicsWindow.Width = gw

GraphicsWindow.Show

'_________________________________________________

'Shape is drawn

'_________________________________________________

ball = Shapes.AddEllipse(100,100)

'_________________________________________________

'subroutine to move the shape called

GraphicsWindow.TextInput = MoveShape

'_________________________________________________

Sub MoveShape

'_________________________________________________

'finds out the location of the ball - useful in many games

'_________________________________________________

top = Shapes.GetTop(ball)

side = Shapes.GetLeft(ball)

'_________________________________________________

'moves the ball

'_________________________________________________

GraphicsWindow.Title = "Last Key: " + GraphicsWindow.LastKey + " Screen Position Top: " + top + " Screen Position Left: " + side

If GraphicsWindow.LastKey = "W" Then

y = y-10

Shapes.Move(ball,x,y)

ElseIf GraphicsWindow.LastKey = "A" Then

x = x-10

Shapes.Move(ball,x,y)

elseif GraphicsWindow.LastKey = "D" Then

x = x+10

Shapes.Move(ball,x,y)

elseif GraphicsWindow.LastKey = "S" Then

y = y+10

Shapes.Move(ball,x,y)

EndIf

EndSub

code

Assignment # 7
1. Create a game window of 400 pixels wide by 600 pixels high. Draw a 60x60 square at position 100H,150W 2. Do the same as in #1 except make the square's center is in the absolute middle of the screen. 3. Do the same as in #2 except make the screen defined by user input, then make the square's center in the absolute middle of the screen no matter how big the screen is. 4. Draw a 3D box (or at least a 2D representation of a 3D box). The face of the box should be 100 pixels high/wide. (HINT: think back to isometric drawing from gr. 9) 5. Make an on-screen counter that responds by increasing by 1 every time you press the button 'G'. The program should indicate it's done when the counter hits 10. 6. Draw a stick-man in the middle of a screen. Behind the stickman should be a background jpg of your choice. 7. Make a simple triangle that is manipulated with keys 8. Create a random number of circles appearing randomly around the screen (800x600). 9. Create a rectangle, manipulated by keys, that causes a windows message to appear when it runs into a wall (rectangle on your screen) (HINT: you need to be doing collision detection, by knowing the bounds of each shape). A hint with collision detection can be found with this import code SLF163 10. Create a circle which follows your mouse around on the screen.


 * **CATEGORY** || **4** || **3** || **2** || **1** ||
 * **Diligently follows instruction**


 * <B1, B3, A2, A3>** || Judicious use of techniques lead to exemplary answers. || Uses techniques correctly leading to a answers of expected quality || Answers are missing and/or quality is insufficient to meet expectations || Both quality and quantity of answers do not approach expectations. ||
 * **Product fundamentals**

by teacher and documentation of progress in journal), but required reminders on one or more occasions to do so. || Used time poorly (as shown by observation by teacher and/or documentation of progress in journal) in spite of several reminders to do so. ||
 * <B2>** || Fundamental concepts clearly demonstrated beyond expectations. Code is clear and follows convention in a way superior to what was expected. || Fundamental concepts generally demonstrated at level expectations. Code is clear and follows convention in a way that was expected. || Concepts generally demonstrated at level slightly below expectations. Code is somewhat clear and generally follows convention. || Concepts demonstrated at a level below expectations. Code is somewhat difficult to follow and needs refinement in order to approach expectations. ||
 * **Use of Time**
 * <C4>** || Used time well during each class period (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well during most class periods (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well (as shown by observation

== =Arrays=

An array is a special kind of variable which can hold more than one value at a time. Basically, what it means is that instead of having to store individual inputs under different variable names, you can use a single variable to store multiple pieces of data. Arrays work from things called indexes which are the placeholders within the array. The great thing about arrays is that they can work off of loops since they're adding indexes to any particular array variable. There is a problem however with using arrays. Information about the arrayed shapes is ephemeral and exists only during the creation process and not once you've finished.

For example, we could include 5 colours as 5 different variables with the code:

code Textwindow.write("Enter the 5 colours")

colour1=Textwindow.read

colour2=Textwindow.read

colour3=Textwindow.read

colour4=Textwindow.read

colour5=Textwindow.read

Textwindow.write("These are the 5 colours you chose";)

Textwindow.write(colour1)

Textwindow.write(colour2)

Textwindow.write(colour3)

Textwindow.write(colour4)

Textwindow.write(colour5) code OR you could write the code in an array as such:

code For i = 1 to 5

Textwindow.write("Enter Colour" + i + ":")

colour[i] = Textwindow.read

Endfor

Textwindow.write("Here are you 5 colours")

For i = 1 to 5

Textwindow.write(colour[i] + ", ")

Endfor

Textwindow.writeline("") code We can do this with string variables, we can of course also do this with with integer variables as well: code For x = 1 to 4

Textwindow.write("Enter 4 numbers; ")

number[x] = Textwindow.read

Endfor

Textwindow.write("Here are you 4 numbers")

For x = 1 to 4

Textwindow.write(number[x] + ", ")

Endfor

Textwindow.writeline("") code Now how is this useful? Well, for example, we could draw a grid using an array. code rows = 10

columns = 10

size = 40

For r = 1 To rows

For c = 1 To columns

GraphicsWindow.BrushColor = GraphicsWindow.GetRandomColor

boxes[r][c] = Shapes.AddRectangle(size,size)

Shapes.Move(boxes[r][c], c * size, r * size)

EndFor

EndFor code

For a summary of arrays, a good starting place is here:

[|Array-love]

//Some guidance for tic-tac-toe//

code GraphicsWindow.Show GraphicsWindow.Height=300 GraphicsWindow.width=300

'draws grid for game For a = 0 To 300 Step 100 For b = 0 To 300 Step 100 GraphicsWindow.DrawRectangle(a,b,100,100) EndFor EndFor

'sets values for grid to zero (empty)

For i = 1 to 3 For j = 1 To 3 gridvalue[i][j] = 0 EndFor endfor

'sets flag for playerturn to player 1 playerturn = 1

'calls mouseclick event GraphicsWindow.MouseDown = onmouseclick

'mouseclick event Sub onmouseclick

'gets position of cursor x = GraphicsWindow.MouseX y = GraphicsWindow.MouseY

' places gamepiece for player If playerturn = 1 Then

' sets shape for player 1 GraphicsWindow.BrushColor="Black" player1 = Shapes.AddEllipse(50,50) Shapes.HideShape(player1)

'moves shape to x/y coordinates Shapes.Move(player1,x-25,y-25) Shapes.ShowShape(player1)

matrixupdate

playerturn = 2

ElseIf playerturn = 2 then

'sets shape for player 2 GraphicsWindow.BrushColor="Red" player2 = Shapes.AddRectangle(50,50) Shapes.HideShape(player2)

'moves shape to x/y coordinates Shapes.Move(player2,x-25,y-25) Shapes.ShowShape(player2)

matrixupdate playerturn = 1

EndIf

EndSub

'sub for logic setting up gridspacing sub matrixupdate 'or whatever you want to call it

If playerturn = 1 And x > 0 And x 0 And y<100 Then gridvalue[1][1] = 1 ElseIf playerturn = 1 And x > 100 And x 0 And y<100 Then gridvalue[2][1] = 1 ElseIf playerturn = 1 And x > 200 And x 0 And y<100 Then gridvalue[3][1] = 1 elseIf playerturn = 2 And x > 0 And x 0 And y<100 Then gridvalue[1][1] = 2 ElseIf playerturn = 2 And x > 100 And x 0 And y<100 Then gridvalue[2][1] = 2 ElseIf playerturn = 2 And x > 200 And x 0 And y<100 Then gridvalue[3][1] = 2 EndIf

'debugging showing grid values in case you get stuck - debugging is your friend!!! GraphicsWindow.drawtext(5,2,"Value of grid space:" ) GraphicsWindow.drawtext(5,12,gridvalue[1][1])

'logic dictating a win for  either player If gridvalue[1][1] = 1 And gridvalue[2][1] =1 And gridvalue[3][1] = 1 Then GraphicsWindow.ShowMessage(win statement for 1) Program.Delay(1000) Program.End ElseIf gridvalue[1][1] = 2 And gridvalue[2][1] =2 And gridvalue[3][1] = 2 Then GraphicsWindow.ShowMessage(win statement for #2) Program.Delay(1000) Program.End EndIf

EndSub

code



Assignment #8 - Arrays
1) You are to dissect the name generator from the following website and create your own SW name generator using a 1 dimensional array (or a series of 1 dimensional arrays)

[]

OR

2) Get the encrypted EXE generator in the handout folder (or found here). Figure out the cypher encryption technique and create a program that uses a 1-dimensional array to encodes and decode any message using that type of cypher. https://blogs.msdn.microsoft.com/alfredth/2011/03/22/programming-projects-using-arrays/ ^


 * **CATEGORY** || **4** || **3** || **2** || **1** ||
 * **Diligently follows instruction**


 * <B1, B3, A2, A3>** || Judicious use of techniques lead to exemplary answers. || Uses techniques correctly leading to a answers of expected quality || Answers are missing and/or quality is insufficient to meet expectations || Both quality and quantity of answers do not approach expectations. ||
 * **Product fundamentals**

by teacher and documentation of progress in journal), but required reminders on one or more occasions to do so. || Used time poorly (as shown by observation by teacher and/or documentation of progress in journal) in spite of several reminders to do so. ||
 * <B2>** || Fundamental concepts clearly demonstrated beyond expectations. Code is clear and follows convention in a way superior to what was expected. || Fundamental concepts generally demonstrated at level expectations. Code is clear and follows convention in a way that was expected. || Concepts generally demonstrated at level slightly below expectations. Code is somewhat clear and generally follows convention. || Concepts demonstrated at a level below expectations. Code is somewhat difficult to follow and needs refinement in order to approach expectations. ||
 * **Use of Time**
 * <C4>** || Used time well during each class period (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well during most class periods (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well (as shown by observation

Game # 3
You are to create, in increasing complexity (and thus possible mark-value): OR OR
 * A simple 'hot seat' tic-tac-toe game with a drawn border, and X and O images. There are to be 2 players using one mouse/keyboard - all basic Tic-Tac-Toe rules apply.
 * A recreation of Othello (where there are white/black tiles that are flipped as you 'capture' pieces - rules/instruction [|here]).
 * A simple 1 player Armaggetron/light-cycle game where, if you run into your own wall, you die. Extra marks will be given for assigning 'powerups' and random hazards.

Your evaluation is as follows:

Mac's evaluation (points to look for):
 * Code planning (did you plan at all before you started writing code?)
 * Code structure (How easy to follow your code and syntax - including spelling)
 * Code logic (Could you game have been written in fewer lines of code? Did you think about your code before you started writing or did your code develop as you wrote and is therefore scattered but functional). /5
 * Code functionality (does it work?)
 * No flaws
 * Some minor flaws, but still quite functional
 * Some major flaws, but code still executes
 * Major flaws, code won't execute, but is present

Overall evaluation outcome:

Game-off
You will be assigned 3 random games to play. You will rank them on SurveyMonkey. Based on the ranking you give the games the top 3 will go into the 'playoff round'. EVERYBODY will play those 3 games and give them a ranking, also on SurveyMonkey (I'll post the link there once these 3 have been decided). Your marks will be based mostly on your game, but there will also be marks and bonuses assigned for class-ranking.

RANK THE GAMES


 * Game rank (how you fare compared to the others - a sliding scale out of the winners mark. If you submit something that fully functions you automatically get 1/2 value or better).
 * Bonuses:
 * Most ridiculous logic
 * Most Enjoyable
 * Most hated
 * Best looking visually (Graphics)
 * **CATEGORY** || **4** || **3** || **2** || **1** ||
 * **Planning for success**
 * <A1, B2>** || Exceptional planning of product leads to exemplary roadmap for success || Planning of product leads to expected level of success || Planning of product is somewhat lacking and leads to expected level of success || Product lacks expected level of planning and or lacks success due to poor planning. ||
 * **Follows expected plan**
 * <B3, A2, A3>** || Judicious use of techniques lead to exemplary product. || Uses techniques correctly leading to a product of expected quality || Product is missing parts and/or quality is insufficient to meet expectations || Both quality and quantity of product does not approach expectations. ||
 * **Product fundamentals**

by teacher and documentation of progress in journal), but required reminders on one or more occasions to do so. || Used time poorly (as shown by observation by teacher and/or documentation of progress in journal) in spite of several reminders to do so. ||
 * <B2>** || Fundamental concepts clearly demonstrated beyond expectations. Code is clear and follows convention in a way superior to what was expected. || Fundamental concepts generally demonstrated at level expectations. Code is clear and follows convention in a way that was expected. || Concepts generally demonstrated at level slightly below expectations. Code is somewhat clear and generally follows convention. || Concepts demonstrated at a level below expectations. Code is somewhat difficult to follow and needs refinement in order to approach expectations. ||
 * **Use of Time**
 * <C4>** || Used time well during each class period (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well during most class periods (as shown by observation by teacher, and documentation of progress in journal) with no reminders. || Used time well (as shown by observation

Small Basic Graphics Quiz

 * Create a graphics window defined by user input (textwindow is fine for the input)
 * Write a program that introduces blue (0000FF) circles of radius 10 pixels. They are to be appear randomly around the screen every 0.1 seconds.
 * In your title you will show how many seconds you have been "playing".
 * Create red square of side length 10 pixels which is your "gamepiece". It is to be controlled by your mouse cursor.
 * Create a black square 25 pixels by 25 pixels. It will be placed in the top right corner of the screen (the exact placement is up to you). Your goal is to drag your red square from a start spot (at the top left corner) to the black square. If you successfully do so you will have a message appear saying you won appear.

__ This quiz will be evaluated as follows: __

Documentation(comments) – 2 marks

Program Structure – 4 marks

Completion of Programming Task – 4 marks

Total – 10 marks

Small Basic Graphics Quiz (version 2)

 * Have a window appear that is randomly sized but no smaller than 400 x 400 and no larger than 1000 x 1000
 * Write a program that introduces random coloured circles of radius 10 pixels on grid points spaced 50 pixels apart. These circles (and thus grid) will occupy the top half of the screen only.
 * Keep track of how long you have been "playing" in seconds in the graphics window title.
 * Create red square of side length 10 pixels which is your "gamepiece". It is to be controlled by the "A, S, D, W" keys.
 * Create a black square 25 pixels by 25 pixels. It will be placed in the middle of the screen (the exact placement is up to you). Your goal is to move your gamepiece from a start spot (at the top left corner) to the black square. If you successfully do so you will have a message appear saying you won appear.

__ This quiz will be evaluated as follows: __

Documentation(comments) – 2 marks

Program Structure – 4 marks

Completion of Programming Task – 4 marks

Total – 10 marks

Write a program that introduces a blue square of side-length 25 pixels in the center of a user-defined window. The square is to be moved with the keys A,S,D,W. A timer should be included, displaying in the title, how long, in seconds, the user has been 'playing'. There should be a red circle of 100 diameter somewhere on the screen that, if the square "player" hits it, a message appears to inform the user that they've failed.