Next graded assignment : Project
Prototype = 24 Aug 2015 |
Links :
IB
Comp Sci Pseudocode
Textbook PPT Slides
Processing
Lessons Java Notes by Eck Liang Java Text Schmidt Java Book IGCSE Vocab IO Gui for Processing Internal Assessment Project Notes Notes and Review Page (for 2016 exams) |
For IA project - make sure that you have
- identified and intended user for your project
- chosen a topic for your project
- discussed the project with the intended user, at least 30 minutes
before returning to school on 19 August.
It would also be good to make a small start on the prototype,
which is due on 24 August. You should not spend more than
3 or 4 hours on the prototype - it is just to get started.
Internal
Assessment Project Notes
We will discuss the concept of a PROTOTYPE.
Internal Assessment Project Notes
HL students have a Paper 3 about the following Case Study:
Case Study [HL] = CGI
The intention of the Case Study is to provide an areaWe will look through these Internal
Assessment Project Notes ,
to get an overview of :
- what the Project is (with examples)
- how long it will take
- what the goals are
- what are the first steps
Homework :
Read the notes about Starting
the Project - Suggested Topics (ignore dates),
and come to our next class with a suggestion of a
topic and intended user
that might interest you. Then we will briefly discuss your
suggestions.
Final exam today at 13:00 in room 276.
=== Today's Review ===
[HL] - Robots - http://www.howstuffworks.com/robot.htm
== Exam Hints and Suggestions ==
(0) The HL students will probably have question about ROBOTS on the exam.
(1) Answer all questions - even if you don't "know" the answer,
there is no penalty for taking a good guess.
(2) MISPRINTS can happen. If there is a misprint,
and you are unable to continue, you can
raise
your hand and ask a question. But if
at all possible,
make a SENSIBLE ASSUMPTION and continue.
Here are examples of possible problems:
- a word is misspelled in the
question.
Try to guess what it means
anyway and continue.
- a problem number is misprinted or missing
- if problem #7 is
printed twice, then write #7
twice
on your answer page and don't worry about it
- if problem #16 is
missing (jumps from #15 to #17),
just
don't write an answer for #16. Label your answers
exactly
as the questions are labelled.
- if Java code is written INCORRECTLY in
the exam question,
follow the instructions
on the cover sheet.
- if a page appears to be missing (maybe
page 5),
raise your hand and ask
the supervisor to check
whether your copy of the
exam is defective,
or whether the pages are
simply numbered incorrectly
=== Today's Review - Sample Exam ===
Here is a sample Final Exam from a previous year.
https://dl.dropboxusercontent.com/u/275979/ibcomp/YearEnd2015/FinalExamSample2015.pdf
This year's final exam will be similar, but contain more programming questions.
Here are ANSWERS for the Networks test:
https://dl.dropboxusercontent.com/u/275979/ibcomp/iboDocs/networks3testAnswers.html
Here are solutions for yesterday's problems:
=== Today's Review - Sample Exam ===
Here is a sample Final Exam from a previous year.
https://dl.dropboxusercontent.com/u/275979/ibcomp/YearEnd2015/FinalExamSample2015.pdf
This year's final exam will be similar, but contain more programming questions.
Start with numbers:
- Add Up Numbers
- Add 10% to all numbers in an array
Then searching:
- Search for a name in an array
- Count numbers in an array between MIN and MAX
- Frequency Distribution
Move on to Sorting:
- Bubble Sort
- Selection Sort
If you find the algorithm in the list,
then translate into Java and make it work correctly.
Otherwise, try writing the algorithm in Pseudocode.
If you cannot do that, then write it in Java.
=== SL+HL ===
At the Pseudocode
Practice Tool ,
- try out one of the algorithms
- TRANSLATE the algorithm in Java (Processing)
- check that your Java translation functions the same as the Pseudocode
algorithm
Start with the following algorithms:
- Ski_Trip
- Common_Factors
- Collatz_Sequence
- Elapsed_Minutes
- Date_Validation
SL students can work on this during class today.
HL students should do this as homework tonight.
=== HL ===
We will start with this program and continue,
adding the RANDOM methods written as homework.
== Homework ==
1 - change the RandomAttempt method so it's really random,
like we did in class
2 - change the Setup method so the FOR loop counts to 1000
then try counting to 10000. This should bet
answer,
but you won't see it because there are too many.
So change it to ONLY display the array IF it
actually
passes the CHECK.
3 - Change the CHECK method so that it RETURNS true or false.
4 - Change the FOR loop to a WHILE loop that quits
when CHECK is successful. Now that CHECK
returns
a BOOLEAN value, you can do this.
*** HOMEWORK (before Thursday's class) ***
Write a method that randomly scatters the numbers 1,2,3,4,5,6,7,8,9
into the cells in a 3x3 array. There are 2 possible methods:
(1) Randomly choose Row and Col and place 9 into nums[Row][Col]
Do the same with 8, but before
assigning 8 to that position,
check that it is empty
(contains 0) - if not, choose another random Row,Col
Repeat for 7
Repeat for 6
... down to 1
(2) Put 1,2,3 4,5,6 7,8,9 in order
into the array.
Then pick two numbers randomly, in
positions R1,C1 and R2,C2
SWAP these two items - if they are
the same, it doesn't matter
repeat this 1000 time, to end up with a
random arrangement of the array
====================================================
Today's Discussion
We are going to write an AI (Artificial Intelligence) program
for a famous puzzle using 2D arrays and Recursive searching.
We have 3 choices (or you can invent an idea, but that's a lot harder):
Magic Square (easiest) This is a square grid filled with numbers. Each row, each column and each diagonal must all add up to the same number. For example, in a 3x3 grid, we must place the numbers 1,2,3..9 so that each row and column and diagonal adds up to exactly 15. Reference article |
An incorrect attempt: 1 6 8 9 2 4 5 7 3 Rows and columns all add up to 15, but diagonals are not correct. |
A correct attempt: 8 1 6 3 5 7 4 9 2 |
8 Queens non-attacking (more difficult) Place 8 queens on a chess board (8x8 grid) so no queen is attacking another - that means each row, each column and each diagonal contains exactly ONE queen. Reference article |
An incorrect attempt Q - - - - - - - - - Q - - - - - - - - - Q - - - - - - - - - Q - - Q - - - - - - - - - Q - - - - - - - - - Q - - - - - - - - - Q Looks pretty good, but the main diagonal contains 2 queens. |
A correct attempt??? Q - - - - - - - - - Q - - - - - - - - - Q - - - - - - - - - Q - - - - Q - - - - - - - - - Q - - - - - - - - - Q - Q - - - - - - |
Balanced Boats (most difficult) Distribute N people into B boats in such a way that the distribution of total weights is as even as possible - making the difference between the heaviest boat and lightest boat as small as possible. This is difficult because the BEST solution is not necessarily perfect, so ALL solutions must be compared to find the best. Reference Article |
Bad Attempt: Divide 50,60,70,80,90,100 into 3 boats as evenly as possible. Boat A : 50, 60 Total = 110 Boat B : 70, 80 Total = 150 Boat C : 90, 100 Total = 190 |
Perfect Result: Divide 50,60,70,80,90,100 into 3 boats as evenly as possible. Boat A : 50, 100 Total = 150 Boat B : 60, 90 Total = 150 Boat C : 70, 80 Total = 150 |
The class can choose which problem to work on.
Then we will begin writing the program in small pieces:
1. How to store the data (in an array)
2. How to DISPLAY the data (the array)
3. How to CHECK whether stored data is "correct"
4. How to INPUT a guess
5. How to automatically create a solution ATTEMPT (random)
6. How to create ALL POSSIBLE ATTEMPTS (exhaustive
loops)
7. How to make REPEATED ATTEMPTS in a focused
fashion that converges to a good solution
(recursive)
We will have the Networks Test tomorrow, Tuesday 19 May,
so that we can discuss some larger questions before the test.
*** Test Tomorrow ***
Today we will discuss some of the
questions at the end of Chap 15,
as well some of the following questions:
Discussion Questions (1) Explain 2 differences between the World-Wide-Web and a Wide-Area-Network. (2) Outline a sensible SECURITY system for use in a Peer-to-Peer network. (3) The OSI Layers model is supposed to provide standardization for Network communications.
Explain why other standards like
ASCII, UNICODE and HTML are still needed, even though (4) Explain why SOFTWARE is more important than HARDWARE when setting up a VPN. (5) Explain why WIFI and VPN might BOTH be needed to provide mobility for some users. (6) Explain the different roles of HTTP and HTML in the World-Wide-Web. (7) Oultine 2 advantages that make Optical Fibre better than Copper Cables for outdoor use. (8)
Outline the most important difference between how SMTP transfers
email (9) Explain the importance of check-sums ina packet-switching system. (10)
Explain two essential differences between MAC security and
userID security ~~~~~~~~ (11)
Assume that a bank director wishes to be able to work from home. (a) Outline one advantage and one disadvantage of using a wireless (WIFI) connection at home. (b) Outline one advantage and one disadvantage of using VPN.
(c ) Explain why he might be able to work WITHOUT using HTTP. (d) Explain why the documents probably contain ASCII codes. (e) Outline 2 ways that ENCRYPTION might be used in this system. |
Topic 3 - Network Basics (3.1.7)
TEST on Monday 18 May about Networks.
You don't need to bring your book to class -
you may borrow a book during class.
TEST on Monday 18 May about Networks.
Topic 3 - Network Basics (3.1.6)
Basics of Protocols FTP Server
HTTP Request-Response Cycle HTTPS and SSL
How DNS Works Domain Names (URLs) (0:00-3:00)
== Homework ==
Read this chapter before class on Monday 11 May:
READ - Chapter 15 in Computer Science Illuminated
Here is a web-site that INPUTS and ANALYZES mathematical formulae.
We will write a much simpler program that can input
a mathematical formula and calculate it's value.
The following is just a first try, and only does + and * and X.
The EVALUATION method is RECURSIVE.
== Homework ==
Finish the program so that it can do - and / (subtraction and division). Then add code to do Exponents (^) by using Math.pow(a,b).
Some helpful videos:
== Homework ==
Watch this video : The OSI
Model
if(source == bTest) { test(); } } public void test() { for(int h=0; h < 4; h++) { if(hands[h]==null) { hands[h] = new Hand(3); } } testHand(hands[1],400,50+120*0,"sqsksa"); testHand(hands[2],400,50+120*1,"h9c9ha"); testHand(hands[3],400,50+120*2,"c2h3d4"); bets[1] = 100; bets[2] = 250; bets[3] = 20; lBet1.setText(bets[1]+""); lBet2.setText(bets[2]+""); lBet3.setText(bets[3]+""); repaint(); } public void testHand(Hand h, int x, int y, String codes) { if(h != null) { for(int c=0; c < 3; c++) { if(h.cards[c]!=null) { this.remove(h.cards[c]); } } } for(int c = 0; c < 3; c++) { String code = codes.substring(c*2,c*2+2); h.setCard(c, new Card(code)); h.cards[c].addTo(x + 80*c ,y,72,97,this); } } |
//
FACTORIAL means to MULTIPLY 1*2*3*...*N // In mathematics we write N! // This PROCESSING program calculates factorials RECURSIVELY, // using the concept that N! = N * (N-1)! void setup() { for(int x=1; x <=10 ; x++) { println(x + "! = " + factorial(x)); } } int factorial(int n) { if (n == 1) { return 1; } else { return n * factorial(n-1); } } Output: 1! = 1 2! = 2 3! = 6 4! = 24 5! = 120 6! = 720 7! = 5040 8! = 40320 9! = 362880 10! = 3628800 |
import java.awt.*; import java.io.*; import javax.swing.*; // A PROTOTYPE = VERY SIMPLE starting version public class Poker extends EasyApp { public static void main(String[] args) { new Poker(); } String[] codes = { "sa","s2","s3","s4","s5","s6","s7","s8","s9","st","sj","sq","sk", "ha","h2","h3","h4","h5","h6","h7","h8","h9","ht","hj","hq","hk", "da","d2","d3","d4","d5","d6","d7","d8","d9","dt","dj","dq","dk", "ca","c2","c3","c4","c5","c6","c7","c8","c9","ct","cj","cq","ck" }; Card[] deck = new Card[52]; Card[] hand = new Card[3]; // REFACTOR the program Hand[] hands = new Hand[4]; // 4 HANDS for 4 PLAYERS int[] bets = new int[4]; // 1 BET for each player int[] money = {1000000,1000,1000,1000}; Button bShuffle = addButton("Shuffle",40,40,100,30,this); // GUI Controls Button bDeal = addButton("Deal Players",160,80,120,30,this); Label lBet1 = addLabel("",320,55,70,30,this); Button bQuit1 = addButton("Quit",320,85,70,30,this); Button bDouble1 = addButton("Double",320,115,70,30,this); Label lBet2 = addLabel("",320,175,70,30,this); Button bQuit2 = addButton("Quit",320,205,70,30,this); Button bDouble2 = addButton("Double",320,235,70,30,this); Label lBet3 = addLabel("",320,295,70,30,this); Button bQuit3 = addButton("Quit",320,325,70,30,this); Button bDouble3 = addButton("Double",320,355,70,30,this); Button bDealer = addButton("Dealer",60,120,100,50,this); int clicks = 0; Font bigFont = new Font("Arial",1,16); public Poker() // CONSTRUCTOR { setTitle("Sample"); setBounds(40,40,700,400); // APPEARANCE makeDeck(); lBet1.setFont(bigFont); bQuit1.setFont(bigFont); bDouble1.setFont(bigFont); lBet2.setFont(bigFont); bQuit2.setFont(bigFont); bDouble2.setFont(bigFont); lBet3.setFont(bigFont); bQuit3.setFont(bigFont); bDouble3.setFont(bigFont); bDealer.setFont(bigFont); } public void makeDeck() { for(int c=0; c < 52; c++) { deck[c] = new Card(codes[c]); } } public int random(int min, int max) { return (int)(Math.random()*(max-min+1) + min); } public void actions(Object source, String command) { if (source == bDeal) { deal(); bets[1] = 100; bets[2] = 250; bets[3] = 20; lBet1.setText(bets[1]+""); lBet2.setText(bets[2]+""); lBet3.setText(bets[3]+""); repaint(); } if(source == bShuffle) { shuffle(); for(int h = 0; h < 4; h++) { if(hands[h] != null) { for(int c=0; c < 3; c++) { if(hands[h].cards[c]!=null) { this.remove(hands[h].cards[c]); } } } } lBet1.setText(""); lBet2.setText(""); lBet3.setText(""); repaint(); } if(source == bDealer) // Deal the dealers cards { if(hands[0] != null) { for(int c=0; c < 3; c++) { if(hands[0].cards[c]!=null) { this.remove(hands[0].cards[c]); } } } else { hands[0] = new Hand(3); } dealHand(hands[0],40,270); int highest = hands[0].getHighest(); for(int p = 1; p < 4; p++) { int winner = checkWinner( hands[0] , hands[p] ); if(winner==1) { output("Dealer wins, player " + p + " loses " + bets[p]); } else if(winner == 2) { output("Dealer loses, player " + p + " wins " + bets[p]); } else { output("Draw, player " + p + " doesn't win or lose"); } } } if(source == bDouble1) // DOUBLE button { bets[1] = bets[1]*2; // bets[1] = 100 * 2 = 200 lBet1.setText(bets[1]+""); } if(source == bDouble2) { bets[2] = bets[2]*2; lBet2.setText(bets[2]+""); } if(source == bDouble3) { bets[3] = bets[3]*2; lBet3.setText(bets[3]+""); } if(source == bQuit1) { output("Player 1 loses " + bets[1]); } if(source == bQuit2) { output("Player 2 loses " + bets[2]); } if(source == bQuit3) { output("Player 3 loses " + bets[3]); } } public int checkWinner(Hand dealer, Hand player ) { int highest = dealer.getHighest(); // get dealers highest card if(highest < 12) // does dealer have a queen or HIGHER { return 2; } // dealer can't play else if(highest > player.getHighest()) // player wins on a tie { return 1; } else if(highest < player.getHighest()) { return 2; } else { return 0; } } public void shuffle() { makeDeck(); for(int s = 0; s < 1000; s++) { int a = random(0,51); int b = random(0,51); Card carda = deck[a]; Card cardb = deck[b]; deck[a] = cardb; deck[b] = carda; } } public void deal() { for(int num = 1; num < 4; num++) { if(hands[num] != null) { for(int c=0; c < 3; c++) { if(hands[num].cards[c]!=null) { this.remove(hands[num].cards[c]); } } } else { hands[num] = new Hand(3); } dealHand(hands[num],400,50+120*(num-1)); } } public void dealHand(Hand h, int x, int y) { for(int c = 0; c < 3; c++) { h.setCard(c, deck[0]); h.cards[c].addTo(x + 80*c ,y,72,97,this); for(int m = 0; m < deck.length-1; m++) { deck[m] = deck[m+1]; deck[deck.length-1] = null; } } } } |
Homework
(1) Download the Poker3Cards program above
(2) Run the program and do some testing.
Find 3 things that do not work "correctly"
(that's okay, it's only a prototype)
(3) On the printed listing that you received in class,
write notes about the parts of the program
that DO work correctly - write at least 3
notes,
writing a comment next to a Java command
(4) Bring questions to class tomorrow, for example:
"Why does the loop in the SHUFFLE method count to
1000?"
We will continue exploring, experimenting with, and changing
this program all week. Next week, you will start making
your own program, for a game of your choice.
Most card games have multiple HANDS - several players
and each gets a set of cards dealt to them.
The OOP way to implement this is to create a HAND class.
We will start today and continue after the break.
=== Homework ==========================
We will finish a game with 3 cards.
We can program "3 card poker" -
here is an
introductory video.
There are several other YouTube videos
about 3 card poker - just search for "3 card poker".
If you can invent (or find) a better game involving
3 cards, we can program that instead.
Bring your ideas and/or wishes to class after vacation.
=======================================
ARRAY
version
of the Poker Game with Lots of Automation
Homework - in the AUTO COUNTING version of the program (above),
add a method that automatically finds the SMALLEST number
in the RESULTS array. It should also tell HOW MANY TIMES
the smallest result occured - for example:
Smallest result = 1
1 occured 5 times
*** 10 minute quiz tomorrow about this program ***
We will start with the program from last time:
ARRAY version of the Poker Game
Today we will AUTOMATE the random result trials.
=== HOMEWORK ===
Here is the AUTOMATED POKER GAME program.
Using the automated program, do 20 trials of each of the
following,
and record the results:
(1) how many times do you need to deal, over and over again,
until you get a pair
(2) once you have a pair, how many times do you need
to click the third card until you get
3-of-a-kind?
1. Short Quiz
2. Detecting pairs the hard way
3. Detecting pairs the easy way - using an array
=== HOMEWORK ===
Download
this
ARRAY version of the Poker Game.
Run it and press the buttons until you are convinced
that it never deals or chooses duplicate cards.
Now do some experiments with 3 cards.
Keep your eyes open to make sure that DUPLICATE cards never occur.
Now change the program so that it only deals 3 cards.
Press the [Deal] button many times. Decide whether
a hand of 3 cards is more likely to contain a pair,
or more likely to have all different rank cards.
Write an estimate of how often a pair occurs.
Now [Deal] until you have a hand with a pair and one different
card.
Click the different card until you have 3-of-a-kind (all 3 cards have
the same number or face). Do this several times.
Write down an estimate of how often you must click
the third card until it matches.
We will work on a Poker game for a couple days:
HOMEWORK - FINISH THE checkForFlush() method.
It starts like this:
public void checkForFlush() { char suitA = cardA.code.charAt(0); char suitB = cardB.code.charAt(0); if( suitA == suitB ) { output("Flush"); } } and the ACTIONS should be changed to: public void actions(Object source, String command) { if (source == bDeal) { deal(); clicks = 0; } else if (source == bScore) { output("You clicked a card " + clicks + " times"); checkForFlush(); //**************** } ....... |
We will start discussing RECURSION, using this example:
Hanoi.jar
public class Primes { public static void main(String[] arr) { new Primes(); } public Primes() { int number = 999997; System.out.println("====== factoring " + number + "======"); factor(number); } void factor(int num) { for(int f = 2; f < num; f++) { if( num % f == 0 ) { int other = num / f; System.out.println(num + "=" + f + "*" + other); factor(f); factor(other); return; } } } } |
ManyDiceRolls
with
GUI and Yahtzee
HOMEWORK
Draw 2 graphs
- one showing the number of PAIRS vs the number of
dice rolled
- second showing the number of YAHTZEES vs the number
of dice rolled
Use 1 million rolls each time (if possible)
We will look at how to add GUI controls to BlueJ programs.
It is similar to IO in Processing, but here it is called EasyApp.java.
Here is a better version of the Dice Rolling program: ManyDiceRolls.zip
We will work on this program for a few days.
The following method checks for ALL dice matching (Yahtzee).
Rewrite this to use loops, like getPair(), so it works for any number of dice.
public boolean
getYahtzee()
{
if(dice[0]==dice[1]
&&
dice[1] == dice[2]
&&
dice[2] == dice[3]
&&
dice[3] == dice[4]
)
{ return true; }
else
{ return false; }
}
We will use BlueJ to further our study of Object Oriented Programming.
We will work through Chapter 5 in Java
Notes .
We will start out using the PairOfDice class, with the
RollTwoPairs program.
HOMEWORK
Use the DICE ROLLING program in Chapter 5.
Change the PairOfDice CLASS so it has 3 dice.
Also include the TOTAL inside the PairOfDice CLASS.
Change the rolling program so it uses the TOTAL
that is inside the class instead of outside.
Now answer this question:
On the average, how many rolls until the 2 sets of dice have matching
totals?
1. Finish your Quiz.
2. Install BlueJ.
3. Download and unpack the source code for David Ecks JavaNotes.
4. Download David Eck's JavaNotes textbook.
We will learn how to use BlueJ to open, edit and run
standard Java programs.
Finish your 2-player TicTacToe, working with a partner.
If you finish early, you can try to figure out
how to save a SCORE on the server. This is basically
just another text file, containing the number of times
a player has won and how many times they have lost.
But that means you need to input the NAME of each player,
not X or O. Still, there should be X and O displayed
on the board, but at the end of each game each
player's score file must be updated, with either
one more win or one more loss or one more draw.
QUIZ TUESDAY about saving data on a server.
Here is a simple TicTacToe game, including checking for a winner.
https://dl.dropboxusercontent.com/u/275979/ibcomp/TicTacToe.zip
Working with your programming partner:
Once you have that working well, you need to change the game
so that the moves are made and recorded in the server.
Then the other player needs to move. The TicTacToe program
must "pick up" the move message from the server and
record an X or O in the appropriate button. You can plan on
doing this on Monday, as you will need a server.
You will have a 15 minute quiz on Tuesday. It will not be a
"programming" quiz, but will ask questions about the
problems associated with using a server to exchange messages.
Today's practice work:
- choose a partner to work with (pair programming)
- on TWO computers, run the CHAT program
that is in //hamlet/labs/computertechnology/ibcs/Chat
You need to run this inside Processing, so the location
of the "chat2.txt" file works correctly.
Change "chat2.txt" to a name that is only for your group
- Check that:
- it is possible for two players called X and O
to add moves, alternating from one to the
next
- it does not allow the same player to play
twice in a row, without the other
player moving
- Save a NEW COPY of CHAT that is just for your group,
e.g. ChatMogitAbishek and ChatRishiSantiago
- Now that you have your own copy of the program
make it simpler and easier to program by doing the following:
- instead of saving a whole sequence of moves,
just save the one single move that was made
last
- change the move protection code so that it just
checks whether the FIRST 3 letters are [X] or [O]
- change the interface to work differently:
- there should be 3 rows of 3 buttons
- when a button is clicked, the program
checks
whether it is allowed to
move by
loading the move from
chat.txt and checking
that the second letter is
the OTHER player
If it is okay, then write
this move into thew chat.txt file,
erasing the old
text from the last move
Then change the text on
the clicked button to
show the name of
the current player (X or O)
- change the screen update running in
void draw()
so that it loads the
single move made by the OTHER
player and then
changes the text on the corresponding button
** Notice that there must be OBVIOUS
AGREEMENT about
** what text will be written into the
chat.txt file, like:
** top-right or
right-top or square#3 or ....
** There must be ONE SPECIFIC VERSION
that is correct.
** Otherwise the other computer
cannot make sense of the move.
** This means the user does not
"type" the position,
** but rather this text is produced
automatically by the button.
Next period, the teacher will show the "easy" way to check
for 3 in a row. So you don't need to start this yet.
The CHAT program shows the basic techniques for sending
messages from one user to another. This same concept
can be used to exchange moves in a 2-player game.
Consider the simple example of Tic-Tac-Toe.
A "game chat" might look like this:
X - top left O - middle X - top right O - middle left X - top middle - you idiot, I win |
There is one significant difference between this game exchange
and a chat site. In a chat site, the same user can post several
different messages, one after another. But in a Tic-Tac-Toe
game, the moves must alternate : X-O-X-O-X ...
So if we convert our CHAT program into a 2-player Tic-Tac-Toe game,
the program should REFUSE to post a move until after the
other player has moved.
We will start making a simple 2-player Tic-Tac-Toe game today.
Of course, a good Tic-Tac-Toe program would also show the board
(in graphics mode), as well as understanding rules like
not accepting illegal moves - e.g. placing an X in a place
where an O has already been placed.
Anyway, we will start today.
We will investigate the problems of
- simultaneous access
- message passing
- server based storage
by looking at a simple
CHAT
program.
This is in preparation for working on a two-player network game.
This week we will work in programming
pairs, practicing the
techniques of Agile
Development.
After the break, we will perform the second cycle of
development for the BrainGames system.
We already did a Prototype, with VERY SIMPLE games.
Perhaps the INTEGRATION (assembly) of the Prototype
system is not quite complete.
Before continuing, we need a CLEAR PLAN of how
game results will be stored and WHERE and WHEN.
A particularly interesting problem is a TWO PLAYER GAME.
Not only do two computers need to exchange information
IN REAL TIME - they must also agree on the actual result(s)
and store them for both players - synchronized.
-- HOMEWORK -- Do some reading about NETWORKED GAMES, especially server-based. Look for TECHNICAL information, on the level of our BitCoin reading. Spend an hour on this over the next week and a half. Come to class with: - URL (address) of something your read that was interesting and informative - questions about things that seemed important but confusing - bring suggestions for how WE can implement TWO-PLAYER games by using the Hamlet server for exchanging data Here are some suggested web-pages to read: Ping (video gaming) What every programmer should know about game programming Source Multiplayer Networking (Valve) Distributed and Parallel Computing |
Two Player Games - e.g. NETWORK games Guess the Flag - 100 points for correct - -40 if you get it wrong - 14 questions or more - 3 flags per question ... 3x14 = 42 flags - max score 1400 Extensions - more questions - more flags per question - less well known flags - different TYPES of flags (Wappen) - recognize other stuff - street signs, a place on a map - add a CLOCK, more points for answering faster - add an opponent, you must answer faster than them - musical accompinent, interesting backgrounds - chat feature Multiplayer Games - start with TWO players - on same keyboard - Multiple mouses (no, doesn't work) - mouse vs keyboard On different computers - connect to each other = network game (LAN game) - search for the other computer - connect as to get access to the other hard-disk - maybe control the other mouse, screen, keyboard, etc - PEER-TO-PEER (P2P) networking messages go directly between computers (like a telephone) very DIRECT Client-server networking - "central" server, like Hamlet - like eMail - indirect - telephones are FULL-DUPLEX Need for Server-based 2 player game - A picture of the board : on both machines? Yes They should be SYNCHRONIZED All the game DATA must be synchronized That may require FAST = REAL-TIME communication - The server needs a copy of the game? - Do ALL PLAYER MACHINES need copies of game data? - What about SYNCHRONOUS ACCESS? ORDER of operations must be PRESERVED and CORRECT - TIME-SLICING (each player gets 1 sec, then the other gets 1 sec) - can I type when a video is running? YES - ALMOST simultaneous |
How does the Bitcoin system video point out useful concepts
for our BrainGames system?
Spend today's class learning about BITCOIN.
As you are reading and watching videos, you should
TAKE NOTES about questions that you have
or important ideas that you see/hear.
(1) Read this first page on HowStuffWorks
(2) Watch the 5 minute video on the first page (above):
https://www.youtube.com/watch?feature=player_embedded&v=LuA3xb-L8r8
(3) Watch this longer, more technical video about how BITCOIN works
inside the computer:
Bitcoin Under the
Hood
(4) Go back to HowStuffWorks and read pages 2,3,4, and 5 of the Bitcoin
article:
http://electronics.howstuffworks.com/everyday-tech/bitcoin1.htm
We will look at PASSWORD SAFETY.
Why do web-sites sometimes require passwords
containing numbers and CAPITAL letters?
Most Secure Password in the Universe : https://www.youtube.com/watch?v=rAUVUUhf7U0
Password Security : http://www.fox10phoenix.com/story/26218092/bbb-talks-password-saftey-after-largest-data-breach
Heatbleed Exploit : https://www.youtube.com/watch?v=8oI_laHhGjE
== HL HOMEWORK == (next HL meeting)
1 - why was there a picture of a CAPTCHA in the new video about passwords?
2 - Star Trek video demonstrated 2 Level Security. What was that?
3 - What does HTTPS mean and how does it work (limited details)?
Before TUESDAY, program the DECRYPTION method that matches below:
// Password Program void setup() { size(600,400); String password = input("Password"); String plainText = input("Message"); String cryptText = encrypt(plainText,password); output(cryptText); } String encrypt(String plainText,String password) { String crypt = ""; int passLetter = 0; for(int c = 0; c < plainText.length(); c++) { if(passLetter >= password.length() ) { passLetter = 0; } char pletter = password.charAt(passLetter); int pascii = (int)pletter - 65; char letter = plainText.charAt(c); int ascii = (int)letter; ascii = ascii + pascii; if(ascii > 90) { ascii = ascii - 26; } //WRAP AROUND FROM 91 BACK TO 65=A crypt = crypt + (char)ascii; passLetter++; } return plainText + "\n" + crypt; } |
Passwords are a very common form of Digital Signature -
we use a password to AUTHENTICATE access.
There are many ways to implement a password system.
The most common is to use the Password together with
an ENCRYPTION algorithm, to produce data that is unreadable
without the Password.
?? Does making data unreadable ensure PRIVACY or SAFETY or BOTH (or NEITHER)??
It is unclear whether we actually need Passwords for the BrainGames
system,
but we can create a Password system anyway.
A very simple Password+Cipher system is called the Caesar Cipher (notes
here).
This replaces every letter with a displaced letter - perhaps 3 positions
further along in the alphabet. Then it looks like this:
Plain Text = HELLO
Cipher Text = KHOOR
This system is easily cracked if we know the algorithm.
If the SHIFT number (3) is unknown, a compute can
easily try 26 different values for the SHIFT number,
until it finds the result that is readable.
A more sophisticated version is the Vigniere Cipher.
This adds a Password, and then each letter of the
plain text is shifted a different amount, according to
the Password. It can work like this (there are other variations):
Plain text : TOMORROW IS FRIDAY
Password: M A
G I C
Alpha Positions: 12 0 6 8 2
Cipher Text : T + 12 --> F
O
+ 0 --> O
M
+ 6 --> S
O
+ 8 --> W
R
+ 2 --> T
R
+ 12 --> D
O
+ 0 --> O
W
+ 6 --> C
space+
8 --> ASCII 41 --> (
... etc ...
Notice that O has and R each occur multiple times,
but have various target values. This makes decryption
considerably more difficult. For example, the most
common letter in English is E. So if we count all the
letters in a cipher text, we could guess that the most
common letter is the translation of E, and hence we
could quickly decrypt a Caesar Cipher. But the trick
won't help with a Vigniere Cipher.
You can read
more
about Vigniere Ciphers here.
We will write Java methods for both the Caeser Cipher
and a Vigniere Cipher.
Quiz Tomorrow about Checksum Algorithms
For example, here
is
a program containing 2 checksum algorithms.
String checkSumSimple(String
result) { int sum = 0; for(int c = 0; c < result.length(); c++) { char letter = result.charAt(c); int ascii = (int)letter; sum = sum + ascii; } return result + "#" + sum; } |
String checkSumBetter(String
result) { int sum = 0; for(int c = 1; c < result.length(); c++) { char ch = result.charAt(c); int ascii = (int)ch; sum = sum + ascii; } sum = sum * (int)result.charAt(0); return result + "#" + sum; } |
We will discuss the encryption algorithms that students wrote.
Here is an attempt to describe a "very clever and mysterious" encryption algorithm.
Take whatever characters are to be saved, e.g.
"A100" meaning 100 points in game A.
Add up their ASCII codes, e.g. 65+49+48+48 = 210
Concatenate that onto the String (with a
delimiter), e.g. "A100#210"
Now, if a "black hat" (bad person) wants to change the data,
say increase the score to 1000, they must also know the "secret"
of the encryption algorithm and must change the CHECK-SUM accordingly.
Do you know what the new CHECK-SUM should be?
This encryption algorithm is actually too simple, but it's not hard
to make it more complex. For example: "A100#9425" could
be valid.
Do you know what the secret algorithm is that produced this CHECK-SUM?
Now we need to put a CHECK-SUM into our data file entries.
== Homework ==
(1) Type in the checkSum method that we wrote during class -
the one that simply adds up the
ASCII codes
(2) Change the method slightly so that it is a bit more difficult
to "crack". Then
produce 6 sample codes that you can
share with the rest of the
class on Monday. Then the
other students will try to
"crack" your algorithm.
(3) Using the sample codes that the teacher showed in class,
try to "crack" the teacher's secret
algorithm - the one
mentioned above that
produces: A100#9425
Here are a few more examples so you
can test your guesses:
A1#3185
A12#6435 B2#3300 A101#9490
A#0 9#0
Here is a brief introduction to a variety of methods for Digital Signatures.
Homework : Read these pages (the first 3 for sure, the 4th is optional)
Definition of Digital Signature
What is a Digital Signature? - an explanation
How are Credit Card numbers "authenticated"?
The
Luhn Algorithm
(optional reading)
In our games project, a supervisor must COLLECT all the results from
various players.
It is essential to ensure that :
- the data was actually produced by the game program(s)
- results data does not get lost, changed or corrupted
- the player has not altered the result to their own benefit
- the player cannot MANUFACTURE results without playing a game
- other players have not altered opponents results to make them worse
- other players cannot DESTROY results to improve their own standing
In other words, we need a digital signature to ensure
that the data at the end is "authentic" - that is the
very purpose of a digital signature.
Here is a prototype program for saving game results:
This is also available on \\Hamlet\labs\ComputerTechnology\ibcs
as an uncompressed folder.
We will discuss the obvious problems with this prototype,
including how to move the data to a central shared server location.
Google Docs (Drive) = HOMEWORK
-- can we share a folder on Google docs,
using the SYNCHRONISATION utility (download from
Google)
then share the folder(s) and other people can see
each other's data
=== Possibilities for Central Shared Storage === Today's Notes Connect to HAMLET/LABS/ComptuerTechnology via WIFI connect to SMB://Hamlet/labs (Samba) Don't use Hamlet if it won't work on a Windows PC Could store data on Dropbox Run a SERVER on a PC ? Airdrop on MacBooks (won't work on a PC) Point-to-Point (peer-to-peer) DIRECT SHARE a local folder on a PC or Mac - this is probably disabled in our WIFI Access Points Amazon server ?? Haiku ?? Google Docs (Drive) !! ============================= Assumption : everything is alwasy ONLINE - not valid Having DELAYED service - like email - is a normal solution We could use Google Drive or Dropbox, which provide central storage with a slight delay - the Java program reads/writes data in a local hard-disk folder, and relies on a SYNCHRONIZATION UTILITY to upload/download (synchronize) the resulting data files. Google Drive might be a good choice, as : - all students at FIS already have Google Drive accounts - installing the synchronization utility is fairly straightforward |
Unless we can solve the problem of connecting a Windows PC
to the Hamlet server, it appears that Google Drive (or Dropbox)
is the best solution.
The teacher will explain how storage works in:
- LAN servers
- Web Servers
- Cloud Storage
- USB storage
- P2P networks
- Backups
The Brain Game System will contain 7 different games,
produced independently by 7 different programmers.
The simplest way to DISTRIBUTE the software to players
is to combine all 7 games into one single program.
Separate games can be combined as follows:
- create a MAIN program - the starting point
This must include the standard IO library
- WRAP each game into a CLASS
- add each game to the MAIN program
- add any extra files (e.g. images) into the MAIN program folder
- make sure that MAIN takes care of INSTANTIATING the
chosen game, as well as CHAINING to the individual
DRAW and ACTION methods
Here is a SAMPLE program with STUB game classes.
HOMEWORK - get a Dropbox account.
If you already have one, that will be fine.
Otherwise, go to www.dropbox.com
and
register for a free account. You will need
to use this account tomorrow during class.
TOMORROW - all about STORAGE
Question: How can we more effectively work as a team?
How do you do "teamwork"? - make sure everyone has something to do - it is probably VERY SIMPLE - they can do it = MAKE A VERY GOOD PLAN = - afterward, you need to REASSEMBLE the products - it must be POSSIBLE to reassemble it - proposal for reassembling a prototype - USB Stick + folder + put all the separate pieces into the folder copy them all into one processing window + DEBUG the result + test it, fix it + recruit a willing test subject run the program let them play ask for comments + show this to the Student Council ask if they like it (feedback) + redistribute make the necessary changes reassemble + repeat until the prototype is good enough - how long is one ITERATION ============================== Choose some VERY SIMPLE TASKS - add 2 numbers - guess a word (chosen from 3) - rock, paper, scissors - answer a question - guess the flag of a country - fix a misspelled word - jeopardy == Bring your working "game" on Tuesday == |
Software Design - Iteration, Top-down, Modularity
Homework :
Bring suggestions for what to do first in this project.
Notes about the Brain Games Tournament
Brainstorming Notes from 20 Jan
You have a test on Monday.
It will be about this program:
https://dl.dropboxusercontent.com/u/275979/ibcomp/processing/OOPcardsGame2b.zip
To prepare for the test, you should download this program and study it.
Run it, make changes, discuss it with a friend, etc.
You will be doing the test on paper - you will not be using a computer.
You will receive a printed copy of this program, exactly as it is.
Then you will answer questions about the program, like:
- explain what these specific commands do
- explain what would happen if this change were made
- explain how the program could be changed to do some specific task
Higher Level students will also have a few questions about
the Kings GUI game. So the SL part of the test will last about 30
minutes,
and the HL part will take about 15 minutes.
Here is the card game so far:
https://dl.dropboxusercontent.com/u/275979/ibcomp/processing/OOPcardsGame2.zip
Now we need to finish the user interface, showing PICTURES of cards.
14 Jan HOMEWORK = add all the code that the teacher presented in
class, including:
- dealing 4 hands correctly (add the loop with new
Hand() to create the 4 hands)
- display all 4 hands in the text window,
using nested loops with a command like:
println(hands[h].cards[c].value +
" " + hands[h].cards[c].suit);
- add a method that adds up the cards in each hand,
and stores the result in the total variable
in each hand,
something like this:
hands[0].total = hands[0].cards[0].value +
hands[0].cards[1].value + hands[0].cards[2].value;
but do all 4 hands - use loop(s) if you wish.
- change the showHands() method so that it prints all 3 cards AND the
total for each hand
Do as much of this as you can, as time permits. We will continue tomorrow.
---------------
13 Jan HOMEWORK = think about how to make the program calculate TOTALS
We will program a card game this week.
Then we will have a written test on Monday 19 Jan,
based on the card game that we wrote.
Our game will involve HANDS containing 3 cards.
We must write code to :
- make a deck of 52 cards and shuffle the deck
- deal 3 cards into each of 4 hands
- display all the hands
- calculate the value of each hand, as follows:
Each card counts for its VALUE,
but cards that MATCH another card don't count at all, e.g:
3 5 7 ==> 15
T Q A ==> 36
8 9 8 ==>
9 ( the 8's don't count because they match )
- allow players to throw away cards and "draw" replacements
- compare several hands (e.g. 4 players) to figure out the winner,
with the largest total
- FLEXIBLE EXTENSION -
allow each player to take as many cards as they wish,
keeping in mind that taking more cards increases the
chances of having duplicate (hence worthless) cards
There will be a written test on Monday 19 Jan.
This will mostly be about OOP programming.
But for [HL] students, there will also be some questions
about the KINGS game and 2-dimensional arrays.
You can practice for this be doing the questions in the link above.
We will write a short program for a card game, starting with this program:
Here is an improved version that displays PICTURES of cards.
You can play around with this a little bit.
For example, make a button that chooses 2 cards -
the top 2 cards (#0 and #1) and checks whether it is a pair -
that means the RANK is the same for both cards.
Here is a correct solution to Friday's quiz:
Assume that our school wishes to have a program that records all
the essential information about text-books that are issued to students for various classes. Write a CLASS with data elements that record the ESSENTIAL INFORMATION in appropriate variables . ** Solution ** class TextBook { String title; String author; String course; String teacher; String IDnumber; String student; String dateIssued; String dateReturned; } |
Here is a solution for Friday's homework to calculate the
cost of parking when the customer leaves.
double calculatePrice(ParkTicket info) |
Here is complete program Friday's homework: ParkingGarage2
We will spend one more day on the OOP Parking Garage notes.
Homework : Make the CALCULATEPRICE method work properly,
charging
2.50 per hour, rounded up to the next whole hours
import java.util.Date; Button bArrive = addButton("Arrive",50,50,100,50); Button bLeave = addButton("Leave",50,100,100,50); ParkTicket[] tickets = new ParkTicket[1000]; int count = 0; void setup() { size(800,600); } void draw() { } boolean action(java.awt.Event evt, Object src) { Object source = evt.target; if(source == bArrive) { arrive(); } else if(source == bLeave) { leave(); } return true; } public void arrive() { ParkTicket ticket = new ParkTicket(); // OBJECT Date today = new Date(); ticket.date = today.toString().substring(4,10); ticket.arrive = today.toString().substring(11,19); output("arrive = " + ticket.arrive); ticket.ID = input(ticket.arrive + "\n License plate?") ; tickets[count] = ticket; count = count + 1; } public void leave() { String license = input("Licensce plate?") ; for(int c = 0; c < count; c = c+1) { if(tickets[c].ID.equals(license)) { output("Ticket found! Arrived at " + tickets[c].arrive); Date now = new Date(); tickets[c].leave = now.toString().substring(11,19); output("Price = " + calculatePrice(tickets[c])); output("You are leaving at " + tickets[c].leave); return; } } } double calculatePrice(ParkTicket info) { // change arrive and leave into doubles // subtract --> elapsed // 2.50 per hour --> round the hours up // 2.50 * elapsed return 2.50; } class ParkTicket { String date = ""; String arrive = ""; // 8:30:00 String leave = ""; // 15:10:00 --> elapsed is 6.666666667 String ID = ""; double price = 2.50; } |
Read these notes about OOP = Object Oriented Programming
Continue writing your Question/Answer program.
It is due on Tuesday. If you are not making progress,
you need to ask questions and get help.
Continue working on the Question/Answer Game.
Here are a few HOW-TO hints that might be useful.
~~~~~~~~~~~~~~~~~~~~~
CENTER text in a label
labelName.setAlignment(Label.CENTER);
DISABLE a Button
buttonName.setEnabled(false);
// use (true) to re-enable the button
Background
Color
controlName.setBackground(new Color(red num, green num, blue num) );
Automatically (Constantly) Display Points
void draw()
{
score.setText(points + ""); //
score is a Label, points is a variable
} // draw()
updates the screen 60 times per second
Stop Asking Question at End of List
count
= count + 1;
if(count >= questions.length)
{
// do something appropriate, like
count = 0
}
Choose a Random Question
int q
= (int)(Math.random()*questions.length);
Continue working on your program.
Watch this video about IBM's Watson.
Download the newest verion of Parallel Arrays here.
Now read these notes about writing a Question/Answer game program.
Need help with TEXT FILES? Try watching this video.
Here is Version 2 of the ParallelArraysQuestions.
It has fixed some of the Errors/Shortcomings of the first version:
parallelArraysQuestions2.zip
Combine your questions files (including hints) with this program.
We need to fix the Kings game to avoid all the ERRORS.
Here is an attempt to check whether a square is free or not:
....
int row =
move.charAt(0)-48; //
ASCII code of zero is 48 .... |
Download the following program and do the practice exercises described in this page:
Continue working on this program: Parallel
Arrays.
Work together with other students if you wish.
Make any of the following improvements (or other improvements if you have your own idea).
Finish as much as you can. We will work on this program for another
week, so there
is no hurry - but DO practice programming.
Here are solutions to the recent homework about NUMS array methods.
Today we will discuss Parallel Arrays.
Do the practice exercises on this page.
-- Homework --
Finish as many of the methods (above) as you can with 60 minutes
at home.
== Extra Homework ==
This is a Make-up assignment for the students who missed class
on Friday, 14 Nov. (Santiago, Robin, Christian, Jan)
Here are two web-sites with interesting stories about computer
system disasters.
http://www.devtopics.com/20-famous-software-disasters/
http://catless.ncl.ac.uk/Risks
Your assignment is to find an interesting story from one of these
sites, read it completely,
and PRESENT the story to the class next week. Don't choose a story
where most of the story is actually missing.
We will probably have one presentation per day next week.
Your presentation should not last more than 5 minutes.
It should include a summary of:
** THE ROLE THAT DEFECTIVE SOFTWARE PLAYED in the accident. **
Be prepared to answer questions.
You might want to use written notes, but don't make a Powerpoint
presentation.
Here are useful ALGORITHM for this problem, as well as other problems:
We had a list of partially completed versions of these on Monday.
We need to write a good version of finding 3 numbers that add to 50.
Homework -
In the Kings game, add a CHECKFREE(row,col) method - like this:
.....
.....
if(checkFree(row,col) )
{ board[row][col] =
'K'; }
// into the corresponding number
else
{ end the game - you
cheated }
showBoard();
} while(true);
}
boolean checkFree(int r , int c)
{
check all the squares (9 of them)
return true or false
}
....
....
#1 - Write your test and turn it in.
#2 - Homework - use your computer and write a method that calculates the
AVERAGE of all the NON-ZERO
numbers in the array.
For example, if the array
contains: 0,0,0,25,15,20,0,0,0,0,0,0,
then the average is
: 60 / 3 = 20 .
This copy of the Packing program now has 12 boxes.
We will continue add a bit more AI (Artificial Intelligence).
We need to write algorithms for all of the following:
Copy these notes and program about the Packing (aka Knapsack) problem.
Hints for TRACING and DEBUGGING in Processing:
==== HOMEWORK ==== Finish problem #2 in the
Knapsack program - TEST THE PROGRAM THOROUGHLY! |
If you finish your ARRAYS TEST early, you can start your homework.
== Homework ==
Read
notes
and program about the Packing (aka Knapsack) problem.
Try running the program and packing some boxes.
Then do problem #1.
How do board games work?
How can we store Tic-Tac-Toe or Mine Sweeper or KINGS in Java?
Here is a program that has an array of numbers:
NumberArrays.zip
Run the program and try out the buttons.
Then do the following practice exercises:
== ANSWERS ==
Here are answers (Java commands) for the problems above:
Explain what is "wrong" with the java.util.Arrays.sort method.
How can we find DUPLICATE words in a list?
How can we REMOVE the duplicate words?
How can computers deal with "almost" matching words?
What is a good algorithm for choosing a word
from a list that matches a give word as closely as possible?
How does Google decide what words are a close match?
How can we find a best match in a Java program?
How long does it take to examine 50000 words in an array?
== Homework ==
Download this program Searching3.zip
Find the part where it ADDS a new word
after searching for the BEST MATCH.
Now add commands that will SORT the
newwords[] array BEFORE saving it into
the disk file. Check afterward that it
is correctly sorted. Don't spend more
than 30 minutes on this. If the file is
NOT correctly sorted, try to figure out
why this doesn't work correctly.
==HOMEWORK ==
Start with this
program (download and unpack).
Change the PREFIX function so that it is NOT case-sensitive.
That means is you search for "mon", then it will
display "Monday" as well as "monster".
================================
Here is the program so far (#1-5 below)
Button search =
addButton("Search",50,50,100,50); List results = addList("",50,150,400,400); Font big = new Font("Arial",1,24); void setup() { size(600,600); search.setFont(big); results.setFont(big); } void draw() { // don't write any commands here } boolean action(java.awt.Event evt, Object src) { Object source = evt.target; if(source == search) { String WORD = input("Type a word"); String[] words = loadStrings("wordlist.txt"); for(int c=0; c < words.length; c++) { if( words[c].equals(WORD) ) { output("Found in position " + c); } } } return true; } |
(6) Make a new button that inputs a single letter, then COUNTS
the number of words that start with that
letter.
(7) Add a LIST box.
Now add a button that inputs a PREFIX - several
letters -
and then displays all the words that start with
the PREFIX.
It displays the results by putting them into the
LIST box.
It should also count and output the number of
results.
For example:
Type a prefix : cold
results
===========
cold
colder
coldest
coldly
coldness
colds
Found 6 matching words.
In case you want more words,
try the lists on this
site.
Here is a list of English words: wordlist.txt
(1) Make a new Processing program.
(2) Add the IO
library to your program -
make a new TAB, name it IO, and copy
the IO library into the TAB.
(3) Copy the wordlist.txt file into the Sketch Folder.
(4) Make a button called [Search].
When clicked the button should input a
WORD.
Then it uses loadStrings to copy the
wordlist.txt file into an ARRAY.
Finally it SEARCHES in the ARRAY looking
for WORD.
If the WORD is found, it should output
"Found".
(5) Test your program with 3 words - one at the beginning
of the list, one near the middle, and the
other at the
end of the list. Then test with 3
NON-words -
one BEFORE the first word in the list, one
that belongs
near the middle of the list, and one that
is after the end.
//====================================
HOMEWORK - do #1-5 as homework -
we will do the rest (below) tomorrow.
//====================================
(6) Make a new button that inputs a single letter, then COUNTS
the number of words that start with that
letter.
(7) Add a LIST box.
Now add a button that inputs a PREFIX - several
letters -
and then displays all the words that start with
the PREFIX.
It displays the results by putting them into the
LIST box.
It should also count and output the number of
results.
For example:
Type a prefix : cold
results
===========
cold
colder
coldest
coldly
coldness
colds
Found 6 matching words.
In case you want more words,
try the lists on this
site.
Here are some useful links for the discussion:
http://www.nasa.gov/mission_pages/msl/index.html
http://www.howstuffworks.com/robot.htm
We want to answer the following questions:
Homework -
Answer each of the 5 questions above.
Write 3 or 4 sentences in each answer.
You may use a pen or you may type your answers, as you wish.
Either way, bring your answers ON PAPER with you to the next HL class.
Add a BUTTON called SAVE and another called RELOAD.
Then add this code. It will save the STUDENTS and ABSENTS lists
into text files, stored in the "sketch folder".
After taking attendance, the teacher can SAVE the results.
If they need to make further changes, they can RELOAD the files,
make changes, and the SAVE again.
Add the buttons and these commands to your attendance program.
Check that it correctly saves and reloads the data for both Lists.
Now make one more BUTTON called [START].
This uses loadStrings to retrieve all the names for one class,
and then puts these Strings into the Students list.
It should also REMOVE all the Strings that might be in the Absent List.
We will start with problem #2 in this attendance program.
We will make a simple Attendance Program.
Homework - make the attendance program, something like this:
Object source = evt.target;
int chosen = ((List)source).getSelectedIndex();
// CAST to a different type
if(source == students)
{
String stu =
students.getSelectedItem();
absent.add(stu);
students.remove(stu);
}
Here is a sample program that uses an AWT List component.
The sample above shows how to use a GUI IO library
to write a Processing program with Java AWT GUI components.
The teacher will explain how this works and make suggestions
for useful changes.
This page outlines how the flow-of-control functions.
Homework:
Make the program better.
(1) When [Add] is clicked,
it AUTOMATICALLY figures out B,
by subtracting... 24 - A
(2) Put it all into a SMALL window - as small as you can.
Maybe use 2 labels for
instructions on 2 lines.
It should still
be readable and usable.
(3) Make a harder problem - bigger numbers.
We wrote this program in class today -
it contains lots of Java concepts
that we will study after the break.
int match = 0; //
counts how many times a match occured // 3-4-3-5 or 3-4-3-3 or 4-4-4-4 int nomatch = 0; // counts how many times a non-match occured // 1-2-3-4 int[] freq = new int[25] ; // ARRAY = LIST 0..23 int total = 0; for(int count=0; count <= 1000000; count++) { int a = (int)random(6) + 1; // chooses 1,2,3,4,5,6 int b = (int)random(6) + 1; // chooses 1,2,3,4,5,6 int c = (int)random(6) + 1; // chooses 1,2,3,4,5,6 int d = (int)random(6) + 1; // chooses 1,2,3,4,5,6 total = a+b+c+d; freq[total]++; if(a==b || a==c || a==d || b==c || b==d || c==d ) { //println(a+" "+b+" "+c+" "+d+" = match"); match++ ; } else { //println(a+" "+b+" "+c+" "+d+" = NO match"); nomatch++; } } println("matches = " , match); println("NON matches = " , nomatch); for(int f=4; f <= 24; f++) { double pc = freq[f] / 10000.0 ; println("freq of " + f + " = " + pc + "%"); } |
Here are some useful links for the discussion:
http://www.nasa.gov/mission_pages/msl/index.html
http://www.howstuffworks.com/robot.htm
We want to answer the following questions:
Continue with your program from yesterday.
We will continue investigating the dice-rolling program:
Rolling
Dice
== HOMEWORK ==
1. What if you roll 4 dice (add another variable)?
2. With 4 dice, is a MATCH more likely than no-match?
3. With 4 dice, how often do we get ALL 4 equal?
4. How often do you get 3 matching numbers in 4 dice (e.g. 4-6-4-4)?
5. If you roll 7 dice, how likely is it that there is NO MATCH?
You need to download and install Processing from http://processing.org
(or borrow a USB stick from the teacher).
Introduction to Probability Theory
We will study this program: Rolling Dice
== Homework ==
Investigate the Dice-Rolling program.
Run it many times and decide whether
it is more likely to roll a MATCH
or to roll "no match".
Vigenere Polyalphabetic Substitution
What is "mod 26"? Why is it important?
How can we implement "mod 26" with ASCII codes?
We wrote this program in class - it will be the basis of tomorrow's quiz.
Ignore the red underlines.
== Homework ==
Spend 30 minutes on the problems in these notes:
Caesar Cypher Algorithm
== Extra Reading ==
If you are interested, you can read more about the Caesar Cipher here:
History of the Caesar
Cipher
How can we make SMARTER devices by connecting
them to other devices?
Simple Javascript String Problems
Look at this link : http://www.ridex.co.uk/cryptology/
Then try to find it at : http://www.archive.org
We will discuss ENCRYPTION.
== Homework ==
- Watch the Code Breaking Video (20 min)
==
Later
==
-
Choose one of the chapters in Too
Much Information about Cryptology
and read that
chapter. Keep track of ideas that you do NOT understand.
Pseudocode - Translate_Strings
== Homework ==
Write a Cafeteria Prices program. This must input
the name of a food and then output the corresponding price.
Do at least 5 food items.
0^0 ??
In case you (or your Math teacher) are interested in 0^0, you can read
this :
http://www.askamathematician.com/2010/12/q-what-does-00-zero-raised-to-the-zeroth-power-equal-why-do-mathematicians-and-high-school-teachers-disagree/
Homework : Try to answer 1 or more of these questions:
What does X^(1/X) look like (the graph)?
Does this have a solution: X^(1/X) = 0
What is 0^(1/0) ?
What is 0^0 ?
Pseudocode
- Solving Equations
Pseudocode errors and the IEEE Floating Point Legacy problem
The inaccuracies are connect to the IEEE
Double
Precision format.
Mohit = doors
Santiago = elevators
Robin = Taxi
Nils = Traffic
Rishi = domestic robots vacuum cleaners
Christian = other domestic robots
Mulkey = washing machine
Homework for HL Students
All of the devices discussed (above) are individual devices.
The student presentations dealt with the behavior of individual devices.
It is possible to improve performance and make the devices
"smarter" by:
- connecting many devices together so they share data
- connecting devices to a central controlling computer
For example, traffic lights are often connected to other traffic
lights
so that as cars drive along at a constant speed, each light turns
green just a bit later than the previous light. This alllows cars
to
drive at a constant speed and always get green lights -
so they never need to wait at a red light.
Think about how some of these devices could become a lot SMARTER
by connecting to other devices or to a central computer.
Especially think about:
- what data should be exchanged between devices
- what processing can be done better with this extra data.
Bring some good ideas to class next HL meeting and we will
discuss your ideas.
First a short 10 minute quiz about binary.
Then we are going to look at how decimal fractions
are stored in binary - and why that causes
errors in calculations.
Binary
Conversions
Binary
Storage
Examples
(continue)
Introductory Slideshow about How Computers Store Data
The most important issue in Computer Science is AUTOMATION.
Automation is usually accomplished via ALGORITHMS.
Algorithms are implemented by writing PROGRAMS in a PROGRAMMING
LANGUAGE.
At FIS, we will be writing programs in Javascript, to automate Web-pages.
But in IB examinations, algorithms are written in PSEUDOCODE.
Pseudocode looks like a programming language, but it is simpler.
We will start with Pseudocode, because it is simpler,
and later switch to Javascript which is more difficult but more useful.
Here is an online tool for practicing with pseudocode:
Pseudocode Practice Tool(1) Test
(2) Homework - watch this video about algorithms:
https://www.youtube.com/watch?v=ENWVRcMGDoU
You will need a working computer in class
tomorrow.
We will discuss:
- System
Monitor
Investigation
Reminder - Written test Monday covering
all the topics we have read and discussed this year.
We will discuss :
- Smartphones for Faculty
- Future PCs
Homework -
Write down 5 PROCESSING tasks that must be
occurring
inside a GPS system.
~~~~~~~~~~~~~~~~~~~~~~~
7.1.1 Discuss a range of control systems.
A variety of control systems should be examined such
as:
- automatic doors
- heating systems
- taxi meters
- elevators
- washing machines
- process control
- device drivers
- domestic robots
- GPS systems
- traffic lights
. . . and other common devices.
Technical knowledge of specific systems is not expected
but students should be able to analyse a specified system.
7.1.2 Outline uses of
microprocessors
and sensor
input in control systems.
~~~~~~~~
We
will
study some sample control systems.
In each case, consider the following questions:
HL Class on Monday - can SL students also attend?
Continue discussing these Computer
Systems
Notes
as well as the reading chapter
1.1.
We will discuss any and/or all of the following:
- textbook SYSTEM
- FIS student database and scheduling SYSTEM
- proposal for SMART PHONE SYSTEM
Today's Assignment
How do we define the term COMPUTER?
We will discuss these notes Computer
Systems
Notes .
Homework
Read chapter
1.1 in your textbook.
==== Read the information below as time permits ====
Welcome to IB Computer
Science .. more .. |
=== Review ===
[HL] - Robots - http://www.howstuffworks.com/robot.htm