ICS2O
Introduction to Computer Studies - Grade 10
Introduction to Computer Studies - Grade 10
Overview | Computing basics | [HTML] | [smallBASIC] | [Python] |Construct | ActionScript | GameMaker | Kodu | Summative
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 example_code to the smallbasic code window. Run it. What do you notice?
What about FAR more complex problems?
Steps to problems solving in Computer Programming can be dead simple. They consists of:
identify the problem,
create a plan (using algorithm and/or pseudocode)
write the code and test it
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:
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 = <some number>
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 < 0 and 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):
Print the following sentence - "Hello World ", and in the next line down "I am Dave, the supercomputer"
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")
Write a small program that converts a user-prompted variable in celcius to farenheight and prints the answer.
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 (note the spaces between lines):
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 printed text (set each line to a string variable, then print each one).
4. Write a single program that has 10 variables (A-J, the integer value for each variable is your choice, no user input is required) and displays the following:
When the program runs a line on the screen “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 additionally prints the sum of the first, fifth and tenth variable AND INCLUDES text saying what it's doing (e.g. "The sum of the first, fifth and tenth number is 23")
5. Using BEDMAS rules, calculate the value of VALUE in this expression where B=6, C=10, D=5, E=3, and F=4
VALUE= B + C / (D - E) * F
6. Write a program that:
sets the background colour of the textwindow to blue (hint: remember to make the whole textwindow blue you have to clear it)
Then asks the user 3 questions and pauses for user input at the end of each question, clearing the screen each time in-between.
Then prints the resulting 3 answers of the user with text that explains it all.
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 (you'll have to get into the Math.X commands)
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
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:
If (predicate) Then
(consequent)
Else
(alternative)
EndIf
if <condition> then
-- statements;
elsif condition then
-- more statements;
elsif condition then
-- more statements;
...
else
-- other statements;
endif
NOTE: We can use the boolean operators as well (greater than, less than, not equal to, equal to....) within the if/then/else statements
for example we can write the following:
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
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). GOTO commands read UPWARDS well, but are inconsisten in use if you need to go "down" in your code. Usage is as follows:
start:
textwindow.writeline("Enter a number")
a=textwindow.readnumber()
if a<10 then
textwindow.writeline("Your number is <10")
Else
GOTO start
Endif
- Notice what happens is that if the number input is greater than 10!
1. Develop a program that compares the # of hours of playing video games a week against the following scale:
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!"
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) (hint, you'll have to continue looping this code - we'll need a GOTO for this one)
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
You are to create, in increasing complexity (and thus possible mark-value): NOTE: DO NOT INSERT LOOPS....yet...
A simple trivial-pursuit-type game with questions - out of a possible 75% (i.e. meets expectations). A truly spectacular game may exceed expectations.
OR
A choose-your-own-adventure game with no more than 120 lines of code - out of a possible 100%
OR
talk to me about a possible alternative
Your evaluation is as follows:
Mac's evaluation (points to look for):
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 functionality (did you code it in a way that makes sense. Does it work? Is there a better way to have done things? Could you reduce the # of lines of code somehow and achieve the same result?)
Code logic (Did you think about your code before you started writing or did your code develop as you wrote and is therefore scattered but functional).
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
Best looking visually (not necessarily graphics, but laid-out text, alignment etc...)
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:
for ( variable initialization; condition; variable update ) {
Code to execute while the condition is true
}
repeat
There are generally 3 types of loops. The for, while, and do..while. Each of the types of loops are useful under certain circumstances.
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:
For I = 1 to 10
Loop contents
Next I
Often the code can be altered to include logic to escape the loop based on certain conditions:
//'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
In SmallBasic the syntax used is:
//'contents repeat the stated # of times//
For i= 1 to 10
TextWindow.WriteLine(i)
EndFor
When you want to have steps skipped, or a non-linear number counter you can use:
'contents repeat with a step of 2
For i= 1 to 10 Step 2
TextWindow.WriteLine(i)
EndFor
Conditional loops using the 'for loop' have the following syntax
j=0 'sets j to 0
'will show whether the loop # i is either odd or even
For i = 1 To 10
'takes the loop number and divides it by 2. The REMAINDER function is the Small Basic equivalent of Modulo
j=Math.Remainder(i,2)
'yields the REMAINDER of what's left after division by the denominator
'For example: If i=1 [the first loop] then Math.Remainder (i,2) is functionally 1/2 = 0 times with a remainder of 1. If i=7 then Math.Remainder (i,2) is 7/2 = 3 times with a remainder of 1.If i=10 then Math.Remainder (i,2) is 10/2 = 5 times with a remainder of 0.
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
*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)
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.
' Initialize the variables in a non-small basic language
Dim counter As Integer : counter = 5
Dim factorial As Long : factorial = 1
While counter > 0
factorial = factorial * counter ' Multiplies the factorial and counter
counter = counter - 1 ' Decrements the counter (subtracts it step by step)
Loop
Print factorial ' Prints out the result.
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.
Here's a simpler view of how the while loop works
'A decreasing counter with an exit-condition
i=20
While i > 10
TextWindow.WriteLine(i)
i=i-1
EndWhile
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.
'Initiallizing the variables. Seen in a non Small-Basic language
Dim counter As Integer = 5
Dim factorial As Integer = 1
Do
factorial = factorial * counter
counter = counter 1
Loop While counter > 0
Console.WriteLine(factorial)
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.
In Small Basic it's best coded into the condition of the loop itself. It could look like this:
'continues until the word is pirate
word="frank"
while word <> "pirate" 'while word is not equal to pirate
word=textwindow.Read()
textwindow.writeline("Nope")
textwindow.clear()
endWhile
textwindow.writeline("Yep")
textwindow.pause
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.
A dependent counter is one where the variable for the loop is used as part of the code in the loop block. For example:
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
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:
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
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 (show) 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'
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. This is the point in time where between loops and subroutines you may PURGE ALL MEMORY TRACES OF THE GOTO COMMAND
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:
TextWindow.WriteLine("Hi")
TextWindow.WriteLine("Press 'H' to cause something magic to happen")
a = TextWindow.readkey()
while a <> "H" and a<> "h"
wrong()
endwhile
TextWindow.WriteLine("Exactly!")
Sub wrong
TextWindow.WriteLine("nope, press it again")
a = TextWindow.readkey()
EndSub
You are to create, in increasing complexity (and thus possible mark-value):
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 truly spectacular game may exceed expectations.
OR
A choose-your-own-adventure game with less than 350 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.
OR
talk to me about a possible alternative
Mac's evaluation (points to look for):
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 functionality (did you code it in a way that makes sense. Does it work? Is there a better way to have done things? Could you reduce the # of lines of code somehow and achieve the same result?)
Code logic (Did you think about your code before you started writing or did your code develop as you wrote and is therefore scattered but functional).
Overall evaluation outcome:
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
Best looking visually (not necessarily graphics, but laid-out text, alignment etc...)
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
[other possible quiz questions]
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".
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
in pseudocode
'setting the variables to their values
#small = 0
#med = 0
#large = 0
priceSmall = 9.99
priceMed = 12.99
priceLarge = 15.99
pizzaTotal = 0
dayEnd = 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"
Let's try this!
GraphicsWindow.Show()
GraphicsWindow.Title = "Button game"
GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.Width = 800
GraphicsWindow.Height = 600
GraphicsWindow.PenColor = "white"
GraphicsWindow.DrawLine(100,100,250,250)
This program illustrates some basic components of how to use graphics in SmallBasic.
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.
In SmallBasic there are 4 basic shapes you can draw either full or empty, they are:
ellipse (an ellipse of zero eccentricity is a circle)
rectangle
triangle
line (well, you can't really fill this one)
Now, let's change the drawing a bit - try this:
GraphicsWindow.Show()
GraphicsWindow.Title = "Button game"
GraphicsWindow.BackgroundColor = "Black"
GraphicsWindow.Width = 800
GraphicsWindow.Height = 600
GraphicsWindow.PenColor = "white"
GraphicsWindow.DrawEllipse(100,280,150,400)
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:
Displaying images.
Resizing existing shapes and images.
Getting and changing the color of individual pixels.
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
'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)
'try this
'path = Program.Directory
'background = Shapes.AddImage(path+"\imageName.jpg")
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
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:
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
In addition, we perform mathematical operations on the timers:
' 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
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:
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
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.
'_________________________________________________
'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
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.
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:
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)
OR you could write the code in an array as such:
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("")
We can do this with string variables, we can of course also do this with with integer variables as well:
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("")
Now how is this useful? Well, for example, we could draw a grid using an array.
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
For a summary of arrays, a good starting place is here:
Some guidance for tic-tac-toe
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 < 100 and y>0 And y<100 Then
gridvalue[1][1] = 1
ElseIf playerturn = 1 And x > 100 And x < 200 and y>0 And y<100 Then
gridvalue[2][1] = 1
ElseIf playerturn = 1 And x > 200 And x < 300 and y>0 And y<100 Then
gridvalue[3][1] = 1
elseIf playerturn = 2 And x > 0 And x < 100 and y>0 And y<100 Then
gridvalue[1][1] = 2
ElseIf playerturn = 2 And x > 100 And x < 200 and y>0 And y<100 Then
gridvalue[2][1] = 2
ElseIf playerturn = 2 And x > 200 And x < 300 and y>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
1) You are to create a "game grid" that is 900x900. There are 30x30 pixel grids. You are to include a small circle (10x10) inside of each pixel grid center. [if successful you get a level 3+ max on your assignment]
Note: for parts 2 and 3 you will have to download the file, then extract it to your D drive in order to run it.
2) You are to dissect the name generator from the following link and create your own SW name generator using a 1 dimensional array (or a series of 1 dimensional arrays) [if successful an immediate 4- on your work]
OR
3) 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. [if successful an immideate 4+ on your work]
https://blogs.msdn.microsoft.com/alfredth/2011/03/22/programming-projects-using-arrays/
^
You are to create, in increasing complexity (and thus possible mark-value):
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.
OR
A recreation of Othello (where there are white/black tiles that are flipped as you 'capture' pieces - rules/instruction here).
OR
A simple 1 player Armaggetron/light-cycle game where, if you run into your own wall, you die. For a challenge: try assigning 'powerups' and random hazards.
OR
talk to me about a possible alternative
Your evaluation is as follows:
Mac's evaluation (points to look for):
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 functionality (did you code it in a way that makes sense. Does it work? Is there a better way to have done things? Could you reduce the # of lines of code somehow and achieve the same result?)
Code logic (Did you think about your code before you started writing or did your code develop as you wrote and is therefore scattered but functional).
Overall evaluation outcome:
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)
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
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