149B U G S A N D D E B U G G I N G 3 Add a “print” top_num = 5 and “input()” total = 0 This command prints the The program doesn’t show for n in range(top_num): current value of the loop what it’s doing at each variable and the total so far step. Adding a “print“ total = total + n command here will let you see what’s happening. print(‘DEBUG: n=’, n, ‘total=’, total) The “input()” command waits for the “return” or input() “Enter” key to be pressed before looping. print(‘Sum of numbers 1 to’, top_num, ‘is’, total) 4 New output DEBUG: n= 0 total= 0 This is actually the The loop is only adding the numbers DEBUG: n= 1 total= 1 sum of the numbers from 0 up to 4, and not 1 to 5. This is DEBUG: n= 2 total= 3 from 0 to 4, not 1 to 5 because a “for” loop always starts counting DEBUG: n= 3 total= 6 from 0 (unless told otherwise), and always DEBUG: n= 4 total= 10 stops 1 before the end of the range. Sum of numbers 1 to 5 is 10 5 Fix the top_num = 5 The new range will count faulty line total = 0 from 1 and stop at “top_num” (1 less than “top_num + 1”) The range should go from 1 up to for n in range(1, top_num + 1): “top_num + 1”, so that the loop adds up the total = total + n numbers from 1 to ”top_num” (5). print(‘DEBUG: n=’, n, ‘total=’, total) input() print(‘Sum of numbers 1 to’, top_num, ‘is’, total) 6 Correct output DEBUG: n= 1 total= 1 The “print” command shows that the program is adding the numbers from DEBUG: n= 2 total= 3 When “n= 3”, the 1 to 5 and getting the correct answer. DEBUG: n= 3 total= 6 total is (1 + 2 + 3) The bug has now been fixed! DEBUG: n= 4 total= 10 The correct answer DEBUG: n= 5 total= 15 is now printed Sum of numbers 1 to 5 is 15
150 P L A Y I N G W I T H P Y T H O N Algorithms SEE ALSO An algorithm is a set of instructions for performing a task. 16–17 Think like Some algorithms are more efficient than others and take less time or effort. Different types of algorithms can be a computer used for simple tasks such as sorting a list of numbers. Libraries 152–153 Insertion sort △ Sorting in order “Insertion sort” takes each Imagine you’ve been given your class’s exam papers to put paper in turn and inserts it into in order from the lowest to the highest mark. “Insertion the correct (sorted) place. sort” creates a sorted section at the top of the pile and then inserts each unsorted paper into the correct position. 45 ▽ How it works When counting the “Insertion sort” goes through each positions, Python starts at 0 of these stages sorting the numbers far quicker than a human could. 0123 6 is sorted into position 1 265143 6 is more than 2, so is sorted after 2 in the sorted section 5 is sorted into position 1 265143 The value of 5 is between 2 and 6, so moves to position 1. 6 shifts to position 2 1 is sorted into position 0 256143 4 is sorted into position 2 1 is less than 2, so moves to 3 is sorted into position 2 position 0. 2, 5, and 6 shuffle down 125643 4 is between 2 and 5, so moves to position 2. 5 and 6 shuffle down 124563 Sorted! 123456 4, 5, and 6 shuffle along to make room for 3 in position 2
151A L G O R I T H M S Selection sort △ Swapping positions Switching one thing with another “Selection sort” works differently to “insertion sort”. It swaps is usually quick and doesn’t affect pairs of items rather than constantly shifting all of the items. anything else in the list. Each swap moves one number to its final (sorted) position. Swap the smallest value with the first value Swaps 1 and 2 2 6 5 1 4 3 Swap the smallest value in the unsorted part (2) with the first value in the unsorted part (6) Swaps 2 and 6 1 6 5 2 4 3 1 2 5 6 4 3Swaps 3 and 5 3 is the smallest value in the unsorted part. Swap it with 5, the first value in the unsorted part 1 2 3 6 4 5Swaps 4 and 6 5 isn’t in the right position yet, but 4 is smaller so it’s swapped first Swaps 5 and 6 1 2 3 4 6 5 Sorted! The largest number is in last position after the swap, so no further swapping is required 123456 EXPERT TIPS “a” is a list of unsorted numbers Sorting in Python >>> a = [4, 9, 3, 8, 2, 6, 1, 5, 7] There are lots of different sorting algorithms, each with different >>> a.sort() This calls the The numbers strengths and weaknesses. Python’s >>> a “sort()” function in list “a” are “sort()” function uses an algorithm now sorted called “Timsort”, named after its [1, 2, 3, 4, 5, 6, 7, 8, 9] designer, Tim Peters. It’s based on two sorting algorithms: “Insertion sort” and “Merge sort”. Type in this code to see how it works.
152 P L A Y I N G W I T H P Y T H O N SEE ALSO Libraries Making 154–155 Writing new code takes time, so it’s useful to be able windows to reuse bits of other programs. These snippets of code can be shared in packages called “libraries”. Color and 156–157 coordinates Standard Library modules ◁ Batteries included Python comes with a “Standard Library” that has lots of useful bits of code ready to use. Stand-alone Python’s motto sections of a library called “modules” can be added is “batteries are to Python to make it even more powerful. included”. This means it comes with lots of ready- to-use code. ◁ Random ▽ Turtle This module is used to This module can pick draw lines and shapes a random number, on the screen. or shuffle a list into a random order. △ Time The Time module gives the current time and date, and can calculate dates—for instance, what day will it be in three days’ time? ▽ Tkinter ▷ Math Tkinter is used to make buttons, windows, and other graphics that Use the Math help users interact with programs. module to work with complex △ Socket mathematical The code in this module helps calculations. computers connect to each other over networks and the Internet.
153L I B R A R I E S Importing modules EXPERT TIPS Before using a module, you have to tell the computer Pygame to import it so it can be used by your program. This allows the bits of code it contains to be available to you. Pygame is a Importing modules is done using the “import” command. Python library Python can import modules in a few different ways. designed for writing video import random ◁ “import random” games. Pygame gives you access to sound modules random.randint(1, 6) This way of importing and special graphics that can be random.choice(my_list) requires you to type the used in games. You’ll be able to module name at the start of use Pygame once you have a good the code. It makes it easier to understanding of the basics of read because you know Python covered in this book. which module it came from. The module name comes Imports all the functions before each function from the Random module ▷ “from random import *” from random import * Importing a module like this works well for randint(1, 6) This code doesn’t show small programs. But it can get confusing choice(my_list) which module the with bigger programs because it isn’t clear function came from which module the function belongs to. Imports only the ◁ “from random import randint” “randint” function You can import a single function from from random import randint the module. This can be more efficient than importing the whole module if randint(1, 6) it’s the only function you want to use. Only the “randint” function is available Help and documentation Help ◁ Help! About IDLE Not sure how to use a module or what functions IDLE Help At the top of any IDLE are available? The Python Library Reference has Python Docs window, click “Help” and all the details. Simply click on the library you choose “Python Docs”. want to learn more about. It’s a good idea to get This brings up a window to know the libraries, modules, and functions with lots of useful that are available, so you don’t waste time information. writing code that already exists.
154 P L A Y I N G W I T H P Y T H O N Making windows SEE ALSO Many programs have windows and buttons that can Color and 156–157 be used to control them. These make up the “graphical user interface”, or “GUI” (pronounced “gooey”). coordinates Make a simple window Making 158–159 The first step in creating a GUI is to make the window that shapes will hold everything else inside it. Tkinter (from Python’s Standard Library) can be used to create a simple one. Changing 160–161 things 1 Enter the code This imports Tkinter 2 A Tkinter window appears This code imports Tkinter from the from the library Run the code and a window appears. library and creates a new window. Tkinter It looks a bit dull for now, but this is only the must be imported before it can be used. first part of your GUI. from tkinter import * Tk window = Tk() This creates a Tkinter window Add buttons to the window 1 Create two buttons Write this code to create a Make the GUI more interactive by adding buttons. simple window with two buttons. A different message will be displayed when the user clicks each button. from tkinter import * This message appears when def bAaction(): button A is pressed print(‘Thank you!’) This message appears when button B is pressed def bBaction(): This label will appear This tells the program print(‘Ouch! That hurt!’) on button A which function to run when the button is clicked window = Tk() buttonA = Button(window, text=‘Press me!’, command=bAaction) buttonB = Button(window, text=‘Don\\’t press!’, command=bBaction) buttonA.pack() This code tells the computer to This label will appear buttonB.pack() put the buttons in the window on button B
155M A K I N G W I N D O W S 2 Click the buttons Tk Click the button to Output appears in to print messages Press me! show a message the shell window When the program is run, a window Don’t press! Thank you! with two buttons appears. Click the buttons and different messages will Ouch! That hurt! appear in the shell. You’ve now made an interactive GUI that responds to the user’s commands. Roll the dice Tkinter can be used to build a GUI for a simple application. The code below creates a program that simulates rolling a six-sided dice. 1 Create a dice simulator This program creates a button that, when pressed, tells the function “roll()” to display a random number between 1 and 6. from tkinter import * This imports the This code clears the text inside the from random import randint function “randint” from text box and replaces it with a def roll(): the random library random number between 1 and 6 text.delete(0.0, END) text.insert(END, str(randint(1,6))) This tells the program which window = Tk() Creates a text box to display function to run when the random number the button is clicked text = Text(window, width=1, height=1) buttonA = Button(window, text=‘Press to roll!’, command=roll) text.pack() This puts the text box and This label appears buttonA.pack() the button in the window on the button 2 Press the button to Tk EXPERT TIPS roll the dice Run the program, then click the 6 Clear and simple button to roll the dice and see the result. This program can be simply Press to roll! When you’re designing a GUI, try changed so that it simulates a not to confuse the user by filling 12-sided dice, or a coin being tossed. the screen with too many buttons. Label each button with a sensible A new number appears here name to make the application each time the button is clicked easy to understand.
156 P L A Y I N G W I T H P Y T H O N Color and coordinates SEE ALSO Pictures and graphics on a computer screen are 154–155 Making made up of tiny colored dots called pixels. To create graphics in a program, the computer needs windows to be told exactly what color each pixel should be. Making 158–159 shapes Changing 160–161 things Selecting colors EXPERT TIPS It’s important to describe colors in a way that Mixing colors computers can understand. Tkinter includes a useful tool to help you do this. Each pixel can give out red, green, and blue light. By mixing these 1 Launch the color selection tool colors together, you can make Type the following code into the shell any color imaginable. window to launch the Tkinter tool for selecting colors. This imports all of the Red and Red and blue Tkinter functions green make make purple yellow R >>> from tkinter import * GB >>> t = Tk() >>> colorchooser.askcolor() Mixing all three makes white Use the American spelling of color Select the color you want by clicking on it 2 Choose a color The “color chooser” window will appear. Pick the color you want and then click the “OK” button. This window makes it easy to pick the exact color you want 3 Color values ((60.234, 190.742, 52.203), ‘#3cbe34’) When a color is selected, a list of numbers will appear in the shell Red value Green value Blue value Code for the color window. These numbers are the values in hexadecimal of red, green, and blue that have been (see pp.182–183) mixed to make the chosen color.
157C O L O R A N D C O O R D I N A T E S Drawing on a canvas EXPERT TIPS To create graphics using Python, Coordinates you need to make a blank area to draw on. This is known as a canvas. In Tkinter, x coordinates get larger moving to You can use x and y coordinates to the right, and y coordinates get larger moving tell Python exactly where to draw downward. (0,0) is in the top-left corner. on the canvas. +x 1 Create a graphics program (0,0) Use this code to create a window and put a canvas inside it. It will then draw (300,50) random circles on the canvas. +y (50,100) (250,200) from random import * This imports the “randint” and “choice” functions from the Random module from tkinter import * This imports all of the size = 500 Tkinter functions The variable “size” sets the window = Tk() dimensions of the canvas canvas = Canvas(window, width=size, height=size) This creates a canvas inside canvas.pack() A forever loop makes the a window while True: program draw circles endlessly This chooses a random color from the list col = choice([‘pink’, ‘orange’, ‘purple’, ‘yellow’]) x0 = randint(0, size) This creates a circle of a y0 = randint(0, size) random size in a random d = randint(0, size/5) place on the canvas canvas.create_oval(x0, y0, x0 + d, y0 + d, fill=col) window.update() This part of the line draws the circle 2 Colored canvas Tk This part fills it with the Run the code and the color that has been program will start drawing chosen ( “col”) circles on the canvas. The size of each circle is random Circles are drawn in random places
158 P L A Y I N G W I T H P Y T H O N Making shapes SEE ALSO As well as adding windows, buttons, and colors to Changing 160–161 a graphical user interface (GUI), Tkinter can also be things used to draw shapes. Reacting 162–163 to events Creating basic shapes Rectangles and ovals are useful shapes for drawing all sorts of things. Once a canvas has been created, the following functions can be used to draw shapes on it. >>> from tkinter import * Sets the size of the canvas >>> window = Tk() Creates a canvas to draw on Sets the position and >>> drawing = Canvas(window, height=500, width=500) size of the rectangle using coordinates >>> drawing.pack() Draws a rectangle (see below) >>> rect1 = drawing.create_rectangle(100, 100, 300, 200) >>> square1 = drawing.create_rectangle(30, 30, 80, 80) >>> oval1 = drawing.create_oval(100, 100, 300, 200) A square can be made by >>> circle1 = drawing.create_oval(30, 30, 80, 80) drawing a rectangle with all sides the same length Draws a circle Sets the position and size of the circle Drawing with coordinates ▽ Coordinates grid The top-left corner of the rectangle Coordinates are used to tell the computer exactly is at coordinates (50, 50). The where to create shapes. The first number (“x”) tells the bottom-right corner is at (250, 350). computer how far along the screen to go. The second number (“y”) tells the computer how far down to go. 0 100 200 300 400 500 (x1=50, y1=50) 500 400 300 200 100 0 This is the name of Coordinates for the the canvas top left of the rectangle >>> drawing.create_rectangle(50, 50, 250, 350) △ Setting the coordinates Coordinates for (x2=250, y2=350) the bottom right The first two numbers give the of the rectangle coordinates for the top-left corner of the rectangle. The second two numbers locate the bottom-right corner.
159M A K I N G S H A P E S Adding color to shapes Creates a solid blue circle with It’s also possible to create colored shapes. Code can be used to set different colors for the outline a red outline and the inside (“fill”) of each shape. >>> drawing.create_oval(30, 30, 80, 80, outline=‘red’, fill=‘blue’) Draw an alien You can draw almost anything by combining different shapes. Here are some instructions for creating an alien using ovals, lines, and triangles. 1 Create the alien For each part of the alien, you must define the type of shape, size, position on the canvas, and color. Each shape has a unique ID number that can be stored in a variable. from tkinter import * Sets “Alien” as the window = Tk() title of the window Creates the canvas window.title(‘Alien’) c = Canvas(window, height=300, width=400) Draws a green oval for the body c.pack() body = c.create_oval(100, 150, 300, 250, fill=‘green’) Draws a black dot eye = c.create_oval(170, 70, 230, 130, fill=‘white’) inside the eye eyeball = c.create_oval(190, 90, 210, 110, fill=‘black’) mouth = c.create_oval(150, 220, 250, 240, fill=‘red’) Draws a red oval neck = c.create_line(200, 150, 200, 130) for the mouth hat = c.create_polygon(180, 75, 220, 75, 200, 20, fill=‘blue’) Draws a blue triangle for the alien’s hat 2 Meet the alien The finished alien Run the code to draw the alien. It has a green body, a red mouth, and one eye on a stalk. It’s also wearing a lovely blue hat.
160 P L A Y I N G W I T H P Y T H O N Changing things SEE ALSO Once a graphic has been drawn on the canvas, it doesn’t 158–159 Making need to stay the same. Code can be used to change the way it looks, or move it around the screen. shapes Reacting to 162–163 events Moving shapes REMEMBER To make a shape move on the canvas, you need to Meaningful names tell the computer what to move (the name or ID you gave the shape) and where to move it. It’s a good idea to use sensible names to identify the shapes The eyeball on the canvas. These pages turns left, then use names like “eyeball” and back again “mouth” so the code is easy to read and understand. Shape’s name, ◁ Moving eyeballs or ID Type this code into the shell window to make the eyeball turn >>> c.move(eyeball, -10, 0) to the left, then turn back again. >>> c.move(eyeball, 10, 0) This function Sets coordinates moves shapes for the movement Changing colors You can make the mouth look as though it is opening and closing by simply changing the color of the oval. Mouth open 1 Write the code The function The opened Mouth Type this code to create two “itemconfig()” changes mouth will closed functions that will make the mouth the properties be black seem to open and close. of shapes you’ve 2 Open and close already drawn Type this code into the shell window to make the mouth open and close. def mouth_open(): >>> mouth_open() c.itemconfig(mouth, fill=‘black’) >>> mouth_close() def mouth_close(): The shape’s ID The closed Enter these commands to make the alien open and mouth will close its mouth c.itemconfig(mouth, fill=‘red’) be red
161C H A N G I N G T H I N G S Hide and show ◁ Blinking alien Shapes can be hidden using the “itemconfig()” To make the alien blink, function. If you hide the eyeball, and then you need to hide the show it again a moment later, the alien looks pupil and make the as though it is blinking. white of the eye green. 1 Create blinking functions Turns the 2 Blink and unblink This code creates two functions white of the Type this code into the shell so you can make the alien blink. eye green window to make the alien blink. def blink(): The shape’s ID >>> blink() >>> unblink() c.itemconfig(eye, fill=‘green’) c.itemconfig(eyeball, state=HIDDEN) The “unblink()” command makes def unblink(): Makes the eye Hides the the eye appear white again pupil open again c.itemconfig(eye, fill=‘white’) Reveals the pupil c.itemconfig(eyeball, state=NORMAL) Saying things I am an alien! Text can also be displayed on the screen to make the alien talk. You can even make it say different things in response to user commands. 1 Adding text Positions the text Put what you want This code adds text to the graphic on the canvas the alien to say in of the alien and creates a function to quote marks steal its hat. words = c.create_text(200, 280, text=‘I am an alien!’) def steal_hat(): This hides As soon as the hat c.itemconfig(hat, state=HIDDEN) the hat disappears the alien will ask for it back c.itemconfig(words, text=‘Give my hat back!’) 2 Steal the hat A new message Give my hat back! Type this code into the shell window appears when the and see what happens. hat disappears >>> steal_hat() Type this to steal the hat
162 P L A Y I N G W I T H P Y T H O N SEE ALSO Reacting to events 158–159 Making Computers receive a signal when a key is pressed or a shapes mouse is moved. This is called an “event”. Programs can instruct the computer to respond to any events it detects. 160–161 Changing things Event names Lots of different events can be triggered using input devices like a mouse or keyboard. Tkinter has names to describe each of these events. Mouse events Keyboard events <Button-1> <Right> <Up> Left mouse Right arrow Up arrow Down arrow button clicked key pressed key pressed key pressed <Button-3> <Left> <Down> Right mouse Left arrow “A” key Different letters button clicked key pressed pressed can go here Spacebar <space> <KeyPress-a> pressed Mouse events Burp! To make a program respond to mouse events, simply link (or bind) a function to an event. Here, the function “burp” is created, then bound to the “<Button-1>” event. This brings the Tkinter window to the front of your screen window.attributes(‘-topmost’, 1) def burp(event): Creates a function △ Burping alien mouth_open() called “burp” Click the left mouse button and c.itemconfig(words, text=‘Burp!’) the alien lets out a burp. This is because the “burp” function c.bind_all(‘<Button-1>’, burp) Links the left mouse click has been used. to the “burp” function
REACTING TO EVENTS 163 Key events Functions can also be bound to keys on the keyboard in the same way. Type in the code below to make the alien blink when the “A” and “Z” keys are pressed. def blink2(event): Makes the eye green (closed) c.itemconfig(eye, fill=‘green’) c.itemconfig(eyeball, state=HIDDEN) def unblink2(event): Hides the c.itemconfig(eye, fill=‘white’) eyeball c.itemconfig(eyeball, state=NORMAL) az c.bind_all(‘<KeyPress-a>’, blink2) Shows the △ Make the alien blink When this code is run, the “A” key eyeball will make the eye close, and the “Z” key will make it open again. c.bind_all(‘<KeyPress-z>’, unblink2) This code links This binds the function functions to events “unblink2” to the “Z” key Moving with keys Key presses can also be used to trigger movement. This code binds the arrow keys to functions that make the alien’s eyeball move. def eye_control(event): This line finds out the name of the pressed key key = event.keysym if key == “Up”: The eyeball moves up if the up arrow c.move(eyeball, 0, -1) key is pressed elif key == “Down”: The eyeball c.move(eyeball, 0, 1) moves left if the left arrow key is elif key == “Left”: pressed c.move(eyeball, -1, 0) Activates the △ Eyeball control elif key == “Right”: function The eyeball moves in the direction “eye_control” of the pressed arrow key. c.move(eyeball, 1, 0) when any key is pressed c.bind_all(‘<Key>’, eye_control)
164 P L A Y I N G W I T H P Y T H O N SEE ALSO PROJECT 7 154–155 Making Bubble blaster windows This project uses all the skills taught in this chapter 156–157 Color and to make a game. It’s a big project, so tackle it in stages and remember to save the program regularly. Try to coordinates understand how each part fits together before moving on to the next stage. By the end you’ll have a game 158–159 Making that you can play and share with friends. shapes Aim of the game Before writing any code, think about the overall plan for the game and how it should work. Here are the main rules that set out how the game will be played: The player controls a submarine The arrow keys move the submarine Popping bubbles scores points A timer is set to 30 seconds at the start Scoring 1,000 points earns extra time The game ends when the time runs out
165B U B B L E B L A S T E R Create the game window IDLE File Edit Shell Debug Window Help and the submarine Bubble Blaster Start by setting the scene. Open a new code window in IDLE. Type in the code below to create the window for the game, and the submarine that the player controls. Use the Tkinter library to build the graphical 1 user interface (GUI). This code will create the main window for the game. from tkinter import * Imports all of the Tkinter functions HEIGHT = 500 WIDTH = 800 Sets the size Sets dark blue as of the window the color of the background (the sea) window = Tk() Give the game a snappy title window.title(‘Bubble Blaster’) c = Canvas(window, width=WIDTH, height=HEIGHT, bg=‘darkblue’) c.pack() Creates a canvas that The submarine will can be drawn on be represented by a triangle inside a circle A simple graphic will represent the submarine in this Draws a red triangle for the submarine 2 game. This can be made using some of the drawing functions from Tkinter. Type out this code, then run it. ship_id = c.create_polygon(5, 5, 5, 25, 30, 15, fill=‘red’) ship_id2 = c.create_oval(0, 0, 30, 30, outline=‘red’) SHIP_R = 15 The radius (size) of the submarine MID_X = WIDTH / 2 The variables “MID_X” and Draws a red “MID_Y” give the coordinates of circle outline MID_Y = HEIGHT / 2 the middle of the screen c.move(ship_id, MID_X, MID_Y) Moves both parts of the submarine Don’t forget to c.move(ship_id2, MID_X, MID_Y) to the center of the screen save your work
166 P L A Y I N G W I T H P Y T H O N BUBBLE BLASTER Controlling the submarine The next stage of the program is to write the code that makes the submarine move when the arrow keys are pressed. The code will create a function called an “event handler”. The event handler checks which key has been pressed and moves the submarine. Type this code to create a function called “move_ship”. This 3 function will move the submarine in the correct direction when a cursor key is pressed. Try running it to see how it works. SHIP_SPD = 10 The sub will move this far when a key is pressed def move_ship(event): if event.keysym == ‘Up’: c.move(ship_id, 0, -SHIP_SPD) Moves the two parts of the sub up when the up c.move(ship_id2, 0, -SHIP_SPD) arrow key is pressed elif event.keysym == ‘Down’: c.move(ship_id, 0, SHIP_SPD) These lines are activated when the down arrow key is pressed, c.move(ship_id2, 0, SHIP_SPD) and the sub moves down elif event.keysym == ‘Left’: c.move(ship_id, -SHIP_SPD, 0) The sub moves left when the left arrow key is pressed c.move(ship_id2, -SHIP_SPD, 0) elif event.keysym == ‘Right’: Moves the sub right when the right c.move(ship_id, SHIP_SPD, 0) arrow key is pressed c.move(ship_id2, SHIP_SPD, 0) y coordinate gets smaller moving up c.bind_all(‘<Key>’, move_ship) Tells Python to run “move_ship” whenever any key is pressed x coordinate gets smaller going left Don’t forget to ▷ How it works y coordinate gets x coordinate gets save your work larger moving down larger going right The “move_ship” function moves the sub in different directions. Adding to the sub’s x and y coordinates moves it right and down, while subtracting from them moves it left and up.
167B U B B L E B L A S T E R Get ready for bubbles Now the submarine can move, start creating the bubbles for the player to pop. Each bubble will be a different size and move at a different speed. Every bubble needs an ID number (so the 4 program can identify each specific bubble), a size, and a speed. from random import randint bub_id = list() This creates three empty lists bub_r = list() used to store the ID, radius (size), bub_speed = list() and speed of each bubble MIN_BUB_R = 10 MAX_BUB_R = 30 Sets the minimum radius of the bubble to 10, and the maximum to 30 MAX_BUB_SPD = 10 Sets the position Picks a random size for GAP = 100 of the bubble on the bubble, between the def create_bubble(): the canvas minimum and maximum values possible x = WIDTH + GAP y = randint(0, HEIGHT) This line of code creates r = randint(MIN_BUB_R, MAX_BUB_R) the bubble shape id1 = c.create_oval(x - r, y - r, x + r, y + r, outline=’white’) bub_id.append(id1) Adds the ID, radius, and bub_r.append(r) speed of the bubble to bub_speed.append(randint(1, MAX_BUB_SPD)) the three lists EXPERT TIPS Bubble lists Three lists are used to store bub_id: stores the ID number of the Don’t forget to information about each bubble. The bubble so the program can move it later. save your work lists start off empty, and information about each bubble is then added bub_r: stores the radius (size) of as you create it. Each list stores a the bubble. different bit of information. bub_speed: stores how fast the bubble travels across the screen.
168 P L A Y I N G W I T H P Y T H O N BUBBLE BLASTER Make the bubbles move There are now lists to store the ID, size, and speed of the bubbles, which are randomly generated. The next stage is to write the code that makes the bubbles move across the screen. This function will go def move_bubbles(): Goes through each for i in range(len(bub_id)): bubble in the list 5 through the list of bubbles and move each one in turn. c.move(bub_id[i], -bub_speed[i], 0) Moves the bubble Imports the functions across the screen you need from the according to its speed Time library This will be the main from time import sleep, time Generates a random BUB_CHANCE = 10 number from 1 to 10 6 loop for the game. It #MAIN GAME LOOP will be repeated over while True: and over while the game is running. Try running it! if randint(1, BUB_CHANCE) == 1: create_bubble() If the random number is 1, the program move_bubbles() Runs the “move_bubbles” creates a new bubble window.update() function (on average 1 in 10 times – so there aren’t Updates the window to redraw too many bubbles!) bubbles that have moved Don’t forget to sleep(0.01) save your work Slows the game down so (x0, y0) it’s not too fast to play Now you’re going to create a useful function to find out where a (x, y) 7 particular bubble is, based on the ID. This code should be added (x1, y1) to the program directly after the code you created in step 5. △ Locating bubbles def get_coords(id_num): Works out the The function finds the middle pos = c.coords(id_num) x coordinate of the of the bubble by taking the x = (pos[0] + pos[2])/2 middle of the bubble point halfway between the y = (pos[1] + pos[3])/2 corners of the box around it. return x, y Works out the y coordinate of the middle of the bubble
169B U B B L E B L A S T E R How to make bubbles pop The player will score points when the bubbles are popped, so the program has to make bubbles disappear from the screen. These next functions will allow it to do that. This function deletes the bubble with ID “i” This function will be used to remove def del_bubble(i): Deletes the bubble from del bub_r[i] the radius and speed lists 8 a bubble from the game. It does this by deleting it from all the lists, and del bub_speed[i] from the canvas. This code should c.delete(bub_id[i]) del bub_id[i] be added directly after the code you typed out in step 7. Deletes the bubble from the canvas Deletes the bubble from the ID list Type this code to def clean_up_bubs(): 9 create a function for i in range(len(bub_id)-1, -1, -1): that cleans up bubbles that have x, y = get_coords(bub_id[i]) This goes through the floated off the screen. bubble list backward This code should go if x < -GAP: Finds out where to avoid the “for” loop directly after the del_bubble(i) the bubble is causing an error when code from step 8. bubbles are deleted Now update the main If the bubble is off the screen then it is deleted; otherwise, it 10 game loop (from step would slow the game down 6) to include the helpful functions you #MAIN GAME LOOP Makes a new bubble have just created. while True: Run it to make sure you haven’t included if randint(1, BUB_CHANCE) == 1: any errors. create_bubble() Updates the positions Removes bubbles that are off the screen move_bubbles() of all the bubbles clean_up_bubs() window.update() Redraws the window Don’t forget to sleep(0.01) to show the changes save your work
170 P L A Y I N G W I T H P Y T H O N BUBBLE BLASTER Figuring out the distance between points In this game, and lots of others, it is useful to know the distance between two objects. Here’s how to use a well-known mathematical formula to have the computer work it out. This function calculates the distance between Loads the “sqrt” function from the Math library 11 two objects. Add this bit of code directly after the code you wrote in step 9. from math import sqrt Gets the position of def distance(id1, id2): the first object x1, y1 = get_coords(id1) Gets the position of Gives back the distance x2, y2 = get_coords(id2) the second object between them return sqrt((x2 - x1)**2 + (y2 - y1)**2) Pop the bubbles The player scores points by popping bubbles. Big bubbles and fast bubbles are worth more points. The next section of code works out when each bubble is popped by using its radius (the distance from the center to the edge). ▷ Collision sensing If the distance between When the submarine and a bubble crash into each other, the the center of the sub and the center of a bubble is less than their radiuses 12 program needs to pop the bubble and update the score. This bit of code should come directly after the code in step 11. added together, they have collided. def collision(): This variable keeps This loop goes through the entire list Checks for collisions points = 0 track of points scored of bubbles (it goes backwards to between the sub avoid errors when deleting bubbles) and any bubbles for bub in range(len(bub_id)-1, -1, -1): if distance(ship_id2, bub_id[bub]) < (SHIP_R + bub_r[bub]): points += (bub_r[bub] + bub_speed[bub]) del_bubble(bub) Deletes the bubble Calculates the number of return points points this bubble is worth and adds it to “points” Gives back the number of points
171B U B B L E B L A S T E R Now update the main game loop to use the 13 functions you have just created. Remember that the order is important, so make sure you put everything in the right place. Then run the code. Bubbles should burst when they hit the sub. Check the shell window to see the score. score = 0 #MAIN GAME LOOP Sets the score to zero while True: when the game starts Creates new bubbles if randint(1, BUB_CHANCE) == 1: create_bubble() move_bubbles() Adds the bubble clean_up_bubs() score to the total score += collision() print(score) window.update() Shows the score in the shell sleep(0.01) window—it will be displayed properly later This pauses the action for a very short time—try removing this and see what happens EXPERT TIPS Don’t forget to save your work Python shortcut The code “score += collision()” is a shortcut for writing “score = score + collision()”. It adds the collision score to the total score, then updates the total score. Code like this is common, so a shortcut is useful. You can also do the same thing using the “–” symbol. For example, “score –= 10” is the same as “score = score – 10”.
172 P L A Y I N G W I T H P Y T H O N BUBBLE BLASTER Adding a few final touches The main stages of the game are now working. All that remains is to add the final parts: displaying the player’s score, and setting a time limit that counts down until the game ends. Type in this code after the code you entered in step Creates “TIME” and “SCORE” labels to explain to the player 14 12. It tells the computer to display the player’s score what the numbers mean and the time left in the game. c.create_text(50, 30, text=‘TIME’, fill=‘white’ ) c.create_text(150, 30, text=‘SCORE’, fill=‘white’ ) Sets the scores and time_text = c.create_text(50, 50, fill=‘white’ ) time remaining score_text = c.create_text(150, 50, fill=‘white’ ) def show_score(score): Displays the score c.itemconfig(score_text, text=str(score)) Displays the def show_time(time_left): time remaining c.itemconfig(time_text, text=str(time_left)) Next, set up the time limit and the score required to gain 15 bonus time, and calculate the end time of the game. This bit of code should come just before the main game loop. from time import sleep, time BUB_CHANCE = 10 Imports functions from the Time library TIME_LIMIT = 30 Starts the game with a SCORE BONUS_SCORE = 1000 30-second time limit score = 0 △ Scoreboard bonus = 0 Sets when bonus time is Scoreboards are a great visual way to given (when a player has show players at a glance how well they scored 1,000 points) are doing in a game. end = time() + TIME_LIMIT Stores the finish time in a variable called “end”
173B U B B L E B L A S T E R Update the main #MAIN GAME LOOP Repeats the main game loop while time() < end: until the game ends 16 game loop to include the new score and if randint(1, BUB_CHANCE) == 1: time functions. create_bubble() Don’t forget to save your work move_bubbles() Calculates when to clean_up_bubs() give bonus time score += collision() if (int(score / BONUS_SCORE)) > bonus: bonus += 1 “print(score)” has been replaced by end += TIME_LIMIT “show_score(score)” so that the score show_score(score) now appears in the game window show_time(int(end - time())) window.update() Displays the time remaining sleep(0.01) Finally, add a “GAME OVER” graphic. This will be Puts graphic in the Sets the font— middle of the screen “Helvetica” is a good 17 shown when the time runs out. Add this to the font for big letters very bottom of your program. c.create_text(MID_X, MID_Y, \\ text=‘GAME OVER’, fill=‘white’, font=(‘Helvetica’,30)) c.create_text(MID_X, MID_Y + 30, \\ Tells you what your score was text=‘Score: ’+ str(score), fill=‘white’) Sets the text color c.create_text(MID_X, MID_Y + 45, \\ to white text=‘Bonus time: ’+ str(bonus*TIME_LIMIT), fill=‘white’) Shows how much bonus time was earned Don’t forget to save your work
174 P L A Y I N G W I T H P Y T H O N BUBBLE BLASTER The timer counts The player scores down to the end points for Time to play of the game popping bubbles with the sub Well done! You’ve finished writing Bubble blaster and it’s now ready to play. Run the IDLE File Edit Shell Debug Window program and try it out. If something isn’t Bubble Blaster working, remember the debugging tips— look back carefully over the code on the previous pages to make sure everything is typed out correctly. Left Up arrow key TIME SCORE arrow key 13 241 Down arrow key Right arrow key △ Controls The submarine is steered using the arrow keys. The program can be adjusted so it works with other controls. EXPERT TIPS Improving your game All computer games start as a basic idea. They are then played, tested, adjusted, and improved. Think of this as version one of your game. Here are some suggestions of how you could change and improve it with new code: Make the game harder by adjusting the time limit and the score required for bonus time. Choose a different color for your submarine. Create a more detailed submarine graphic. Have a special type of bubble that increases the speed of the submarine. Add a smart bomb that deletes all of the bubbles when you press the spacebar. Build a leaderboard to keep track of the best scores.
175B U B B L E B L A S T E R The bubbles float New bubbles drift in from right to left and from the right at disappear off the screen random intervals Help Players uses this submarine to pop as many bubbles as they can before time runs out The bubbles are all different sizes and move at different speeds ◁ Super submarine Now you can share this game with your friends. Take turns to see who can score the most points. Afterwards, show them the code behind it and explain how it all works.
176 P L A Y I N G W I T H P Y T H O N SEE ALSO What next? 152–153 Libraries Computer 204–205 Now that you’ve tackled the Python projects in this book, you’re on your way to becoming a great programmer. games Here are some ideas for what to do next in Python, and how to take your programming skills further. Experiment REMEMBER Play around with the code samples Read lots of code in this book. Find new ways to remix them or add new features—and Find interesting programs or don’t be afraid to break them too! libraries written by other people This is your chance to experiment and read through the code and with Python. Remember that it their comments. Try to understand is a professional programming how the code works, and why it is language with a lot of power—you built that way. This increases your can do all sorts of things with it. knowledge of coding practices. You will also learn useful bits of Build your own libraries information about libraries that you can use in future programs. Programmers love to reuse code and share their work. Create your own library of useful functions and share it. It’s a great feeling to see your code being used by another programmer. You might build something as useful as Tkinter or Turtle!
177W H A T N E X T ? Make games EXPERT TIPS with Python Different versions of Python You could create your own game using Python. The PyGame When you find code elsewhere (in other books or online), it library, which is available to may be written for a different version of Python. The versions download from the web, comes are similar, but you might need to make small changes. with lots of functions and tools that make it easier to build print ‘Hello World’ Python 2 games. Start by making simple games, then progress to more print(‘Hello World’) Python 3 complex ones. Score 56 22 Debug your code Debugging is an important part of programming. Don’t just give up if something isn’t working. Remember that computers will only do what you tell them, so look through the code and figure out why it’s not working. Sometimes looking over it with another programmer helps you find bugs quicker.
Inside computers
180 I N S I D E C O M P U T E R S SEE ALSO Inside a computer Storing data 192–193 in files The earliest computers were simple calculators. At a basic level, computers haven’t changed much since The Internet 194–195 then. They take in data (input), perform calculations, Mini 214–215 and give out answers (output). computers Basic elements The memory contains Memory information in sections, A computer consists of four main parts: input, memory, processor, and like books on library output. Input devices gather data, shelves. Memory is used similar to the way your eyes or ears collect information about the world to store programs and around you. Memory stores the data, the data they use while processors examine and alter it, just like a human brain. Output devices The control unit show the results of the processor’s retrieves programs calculations, like a person speaking or from the memory in moving after deciding what to do. order to run them ▷ Von Neumann architecture The control unit Processor loads and carries Control unit A scientist called John von Neumann first out instructions came up with the standard layout for a computer in 1945. His plan is still followed from programs today, with some improvements. Input Language and information can be input through the keyboard Mouse Keyboard Icons and menus can be selected using the mouse
181I N S I D E A C O M P U T E R Computer hardware Screen The network adapter, is used for contacting Hardware is the physical parts of The motherboard other computers a computer. Computers contain connects pieces of Graphics processor many different bits of hardware hardware together working together. As computer The battery makers pack more and more Processor supplies power features into smaller machines, the hardware components have Data storage The chipset controls to be smaller, generate less heat, Inside a laptop communication and use less power. between components The arithmetic logic LINGO unit retrieves data for its calculations from GIGO the memory “Garbage in, garbage out” (“GIGO” The processor is made up of for short) is a computing phrase two parts, one to carry out meaning that even the best instructions and the other programs will output nonsense to perform calculations if they receive the wrong input. Arithmetic logic unit The arithmetic logic unit Speakers turn (ALU) performs any calculations data into sounds 2+3=5 the program needs 5>3=? Output Printers output data onto paper Printer Screen Speaker Screens provide visual output
182 I N S I D E C O M P U T E R S Binary and bases SEE ALSO How can computers solve complex calculations when all Symbols 184–185 they understand is electrical signals? Binary numbers are used to translate these signals into numbers. and codes Logic gates 186–187 What is a base number? Each extra digit is worth 10 times the one before A “base” is the number of values that can be shown using only one x10 x10 x10 digit. Each extra digit increases the number of values that can be 1000 100 10 1 shown by a multiple of the base. The number 3274 is made ▷ Decimal system up of four digits The decimal system is the most 3 2 74 familiar counting system, and has a base of 10. It can show 10 values 3x1,000 + 2x100 + 7x10 + 4x1 = 3,274 with one digit, 100 values with two digits, and 1,000 with three digits. Binary code A wire with 1 a current At the most basic level, computers only understand ON two values: electrical signals that are “on” and “off”. ▷ 1 and 0 Because there are only two values, computers deal with A wire with 0 numbers using a base of two, or “binary”. Each digit is electrical signal either a 1 or a 0, and each extra digit in the number “on” is a 1. A wire OFF is worth two times the previous digit. with electrical signal “off” is a 0. Each extra digit is worth twice as much x2 x2 x2 x2 x2 x2 x2 128 64 32 16 8 4 2 1 ◁ Binary The range of values that can be written doubles with 1 1 1 1 0 0 0 1 each digit added. 1x128 + 1x64 + 1x32 + 1x16 + 0x8 + 0x4 + 0x2 + 1x1 = 241
183B I N A R Y A N D B A S E S Hexadecimal ▽ Understanding nibbles A “nibble” is made up of four binary When using numbers in computer programs, a base of 16 digits, which can be represented by is often used because it’s easy to translate from binary. one hexadecimal digit. Because there are only 10 symbols for numbers (0–9), the values for 10–16 are represented by the letters A–F. The number 241 in binary code 1 1110 001 1111 Binary numbers can be 0001 The number in broken down into nibbles hexadecimal made up of four digits 1111 in binary is F 0001 in binary is 1, which 1 241=F1 15, which is F in is 1 in hexadecimal The number hexadecimal in decimal ▽ Comparing base systems REMEMBER Using this table, you can see that expressing numbers in hexadecimal gives the most Bits, nibbles, and bytes information with the fewest digits. A binary digit is known as a “bit”, and is the DIFFERENT BASES smallest unit of memory in computing. Bits Decimal Binary Hexadecimal are combined to make “nibbles” and “bytes”. A 0 0000 0 kilobit is 1,024 bits. A megabit is 1,024 kilobits. 1 0001 1 Bits: Each bit is a single 2 0010 2 binary digit—a 1 or 0. 3 0011 3 4 0100 4 1 5 0101 5 Nibbles: Four bits make up 6 0110 6 a nibble—enough for one 7 0111 7 hexadecimal digit. 8 1000 8 9 1001 9 1001 10 1 0 1 0 A Bytes: Eight bits, or two 11 1 0 1 1 B hexadecimal digits, make up a 12 1 1 0 0 C byte. This gives us a range of 13 1 1 0 1 D values from 0 to 255 (00 to FF). 14 1 1 1 0 E 10110010 15 1 1 1 1 F
184 I N S I D E C O M P U T E R S Symbols and codes SEE ALSO Computers use binary code to translate numbers into 180–181 Inside electrical signals. But how would a computer use binary code to store the words and characters on this page? a computer 182–183 Binary and bases ASCII 32 SPACE ASCII 96 ` 33 ! 97 a The first computers each stored characters in their own 34 “ 64 @ 98 b unique way. This worked fine until data needed to be 35 # 65 A 99 c moved between computers. At this point, a common 36 $ 66 B 100 d system was chosen, called the American Standard Code 37 % 67 C 101 e for Information Interchange (ASCII, pronounced “askey”). 38 & 68 D 102 f 39 ‘ 69 E 103 g ▷ ASCII table 40 ( 70 F 104 h In ASCII, a decimal number value is 41 ) 71 G 105 i given to each character in the upper- 42 * 72 H 106 j and lower case alphabets. Numbers are 43 + 73 I 107 k also assigned to punctuation and other 44 , 74 J 108 l characters, such as a space. 45 - 75 K 109 m 46 . 76 L 110 n ▷ ASCII in binary R = 82 = 1010010 47 / 77 M 111 o r = 114 = 1110010 48 0 78 N 112 p Because each character has a 49 1 79 O 113 q number, that number then needs 50 2 80 P 114 r to be converted to binary to be 51 3 81 Q 115 s stored in a computer. 52 4 82 R 116 t 53 5 83 S 117 u ▽ ASCII in Python This command prints 54 6 84 T 118 v You can convert between the character, the ASCII 55 7 85 U 119 w ASCII and binary code in most value, and the binary 56 8 86 V 120 x languages, including Python. value for each letter in 57 9 87 W 121 y the name “Sam” 58 : 88 X 122 z 59 ; 89 Y 123 { >>> name = ‘Sam’ 60 < 90 Z 124 | >>> for c in name: 61 = 91 [ 125 } 62 > 92 \\ 126 ~ print(c, ord(c), bin(ord(c))) 63 ? 93 ] 127 DELETE 94 ^ S 83 0b1010011 Here are the results. The 95 _ a 97 0b1100001 beginning of each binary m 109 0b1101101 number is marked “0b”
SYMBOLS AND CODES 185 Unicode As computers across the world began to share data, the limits of ASCII began to show. Thousands of characters used in hundreds of languages had to be represented, so a universal standard called Unicode was agreed on. Unicode has over ▷ International code 110,000 characters! Unicode represents all the languages of the world. For example, the Arabic characters are represented in the range 0600–06FF. ▷ Unicode characters 2602 2EC6 08A2 0036 Unicode characters are represented by their hexadecimal value, which appears as a series of letters and numbers (see pp.182–183). Each character has its own code. More characters are added all the time, and there are some unusual ones, such as a mini umbrella. 0974 004D 2702 A147 REMEMBER ▽ Unicode in Python Unicode can be used to display special characters Hexadecimals in Python. Simply type a string containing a Unicode character code. Hexadecimal numbers have a base of 16. Ordinary decimal numbers are used for 0 to 9, Putting “\\u” before the and the values 10–15 are represented by the hexadecimal code tells the letters A to F. Each hexadecimal number has an computer this is Unicode equivalent binary value. >>> ‘Zo\\u00EB’ The Unicode value The same value ‘Zoë’ of ë as hexadecimal as binary The code is translated ë = 00EB = 11100111 into the character “ë”
186 I N S I D E C O M P U T E R S SEE ALSO Logic gates 180–181 Inside Computers use electrical signals not only to understand a computer numbers and letters but also to make decisions using devices called “logic gates”. There are four main types of 182–183 Binary logic gates: “AND”, “NOT”, “OR”, and “EXCLUSIVE OR”. and bases AND gate Gates use one or more input signals to produce an output signal, based on a simple rule. AND gates switch their output signal “on” (1) only when both input signals are “on” (1 and 1). 11 0 0 1 0 10 0 △ Inputs 1 and 1 = output 1 △ Inputs 1 and 0 = output 0 △ Inputs 0 and 0 = output 0 Both input signals are “on”, If one input is “on” but the An AND gate produces so the AND gate produces an other is “off”, the output an “off” output signal if both “on” output signal. signal is “off”. input signals are “off”. NOT gate 10 REAL WORLD These gates “flip” any input George Boole (1815–64) to its opposite. “On” input becomes “off” output, and George Boole was an English “off” input turns to “on” mathematician whose work made output. NOT gates are also logic gates possible. He worked known as “inverters”. out a system to solve logic problems. This kind of math, △ Input 1 = output 0 which deals in values that can The NOT gate flips an “on” input to only be true or false (positive or an “off” output, and vice versa. negative), is known as “Boolean logic” in his honor.
187L O G I C G A T E S OR gate An OR gate produces an “on” output when either one of the inputs is “on”, or when both are “on”. 11 0 110 10 0 △ Inputs 1 and 1 = output 1 △ Inputs 1 and 0 = output 1 △ Inputs 0 and 0 = output 0 Two “on” inputs produce One “on” and one “off” input still Only two “off” inputs produce an an “on” output. produce an “on” output. “off” output from an OR gate. EXCLUSIVE OR gate 1 1 1 This type of gate only gives 0 an “on” output when one 0 input is “on” and the other is 1 “off”. Two “on” or two “off” △ Inputs 1 and 0 = output 1 inputs will produce an “off” △ Inputs 1 and 1 = output 0 The output is only “on” when output. Gates like this are also Two “on” inputs produce the inputs are different. known as “XOR” gates. an “off” output. EXPERT TIPS Building computer circuits By combining these four basic with two NOT gates in a loop, logic gates, you can create circuits you can create a circuit that to perform a whole range of will store a bit of data (a single advanced functions. For example, 1 or 0). Even the most powerful by linking an AND gate to an XOR computers are based on gate, you create a circuit that can billions of tiny logic circuits. add two binary digits (bits) together. By linking two OR gates Computer chips contain many logic circuits
188 I N S I D E C O M P U T E R S Processors and memory SEE ALSO Inside a computer are many types of electronic chips. 180–181 Inside Most importantly, the processor chip runs programs and memory chips store data for instant access. a computer 186–187 Logic gates The processor Processors are a collection of very small and complex circuits, printed on a glasslike material called silicon. Small switches called transistors are combined to form simple logic gates, which are further combined to form complex circuits. These circuits run all the programs on your computer. ◁ Circuits in a processor The circuits are kept synchronized by a clock pulse, just like an orchestra is kept in time by a conductor. Machine code Save to memory Processors only understand a set of program instructions called “machine code”. These simple instructions for operations like adding, subtracting, and storing data are combined to create complex programs. Call another piece of code ▷ Understanding machine code Compare Machine code is just numbers, so coders two values use programming languages like Python that get converted into machine code.
189P R O C E S S O R S A N D M E M O R Y Memory LINGO Like processors, memory chips are printed on silicon. A few RAM logic gates are combined to create a “latch circuit”. Each latch stores one bit (the smallest unit of data with a binary Memory is often referred to as value of either 1 or 0), and many latches are combined to RAM (“Random Access Memory”), create megabytes and gigabytes of storage. meaning any part of it can be accessed directly. Early types Memory is made up of storage could only access data of repeated identical in order from start to end, which blocks of circuit was much slower. Every item of data has a number (called an “address”) so it can be found quickly Each block of memory can ◁ Programs and data store millions or billions of Programs constantly read, bits of data write, and update the data stored in the memory. REMEMBER MEMORY Processing information Contains the A game program position of the running The processor and memory, when combined with input and output character The character devices, give you everything you jumps on screen need for a computer. In a game Mouse click program, for example, the user OUTPUT inputs position data by clicking the INPUT PROCESSOR mouse, the processor does the calculations, reads and writes memory, and then produces output in the form of making the character jump on the screen.
190 I N S I D E C O M P U T E R S SEE ALSO Essential programs 180–181 Inside There are a few programs that every computer a computer needs in order to work. Some of the most important programs are operating systems, compilers, 182–183 Binary and interpreters. and bases 188–189 Processors and memory Operating system This program has run Each program has its and is now waiting own space in the The operating system (OS) is the for its next slice of manager of the computer’s processor time computer’s memory resources. It controls which programs are allowed to run, how Programs run in turn Program Memory long they run for, and which parts 1 Memory of the computer they use while running. The OS also provides off interfaces, such as file browsers, to let a user interact with the Program computer. Common operating 2 systems include Microsoft Windows and Mac OS X. on The operating system is like an octopus, with tentacles connecting to all parts of the computer The operating system manages the processor’s time ▷ How it works Program Memory 3 The processor’s time is divided up into slices. A off program will be given a slice. If it can’t finish in This program is that time, it is paused and waiting to run the next program runs.
191E S S E N T I A L P R O G R A M S Compilers and Compiler input data interpreters output output Program Run program The languages you write in machine in machine programs with, such as Program Run compiler Python, are known as “high- code code level languages”. Computer processors don’t understand △ Compiler output data these languages, so compilers Compilers produce translated and interpreters are used to machine code that can be saved input data translate them into a low- and run later. level language (known as Interpreter “machine code”) that a Interpreter runs program computer does understand. ▷ Interpreter input Interpreters translate the code and execute the Program program at the same time. output data Links to monitor Links to keyboard Links to speaker Links to mouse Links to printer Links to network The OS acts as a bridge Links to storage between the programs you want to run and the computer’s hardware
192 I N S I D E C O M P U T E R S SEE ALSO Storing data in files 182–183 Binary A computer’s memory doesn’t just store numbers and and bases characters. Many more types of data can be stored, including music, pictures, and videos. But how is this 188–189 Processors data stored? And how can it be found again? and memory 190–191 Essential programs How is data stored? The computer’s file system is similar to a When data is saved to be used later, it is put into a paper filing system file. This file can be given a name that will make it easy to find again. Files can be stored on a hard-drive, memory stick, or even online—so data is safe even when a computer is switched off. EXPERT TIPS ▽ File information Right-click on a file to see There is more to a file than just its properties such as file File sizes contents. File properties tell the system type, location, and size everything it needs to know about a file. Files are essentially collections of data in the form of binary digits FILE PROPERTIES (bits). File sizes are measured in the following units: The file name name groove should be Bytes (B) file type mp3 memorable extension 1 B = 8 bits (for example, 10011001) What type of file opens with Music Player Kilobytes (KB) it is, typically in three characters full directory /Users/Jack/Music 1 KB = 1,024 B path The program Megabytes (MB) that can handle size 50 MB 1 MB = 1,024 KB = 1,048,576 B the file’s data Gigabytes (GB) The location of the file on the 1 GB = 1,024 MB = 1,073,741,824 B computer Terabytes (TB) The file size 1 TB = 1,024 GB = 1,099,511,627,776 B (see the box on the left)
193S T O R I N G D A T A I N F I L E S Directories EXPERT TIPS It’s easier to find files on a computer system if they are Managing files well organized. To help with this, files can be grouped together in “directories”, also known as “folders”. It’s A file manager program helps find files often useful for directories to contain other directories and directories. Each operating system in the form of a directory tree. has a different one: ▽ Directory tree Windows: Use Windows Explorer to When directories are placed inside other look around the directory tree. directories, it creates a structure that resembles Apple: Use Finder to look around the an upside-down tree, and just like a tree it has directory tree. roots and branches (confusingly called “paths”). Ubuntu: Use Nautilus to look around the directory tree. The “root” of the directory tree, where you start looking for files This “path” This “path” contains Jack’s contains Sara’s user data user data J a c k ’s Sara’s folder folder Music Photos Mpegs are a type of video file story.txt sunnyday.png Text file film.mpg PNGs and JPEGs Music files can are two types have different of image file file extensions island.jpg groove.mp3 funk.wav
194 I N S I D E C O M P U T E R S The Internet SEE ALSO The Internet is a network of computers all across the 182–183 Binary world. With so many computers, clever systems are needed to make sure information goes to the right place. and bases 192–193 Storing data in files IP addresses Packets are put back together in Every computer or phone connected to the Internet has an address, much like a building. The addresses are called “Internet Protocol (IP) the right order addresses” and each one is made up of a series of numbers. ▽ Sending information Receiving computer accepts packets Files travel between computers in small chunks called packets. Special computers called routers forward these packets to their destination. Sending computer transmits data Packets hop from router to router around the globe to... File is broken down EXPERT TIPS 10.150.93.22 into small chunks of data called packets Internet protocol from... 62.769.20.57 ◁ Address information A protocol is a list of rules. Every packet of data “Internet Protocols” are rules for is labeled with the how big packets can be and how destination and sender’s IP they are structured. All Internet addresses. Domain names devices must follow these rules like “dk.com” are translated if they want to be able to into IP addresses. communicate with each other.
195T H E I N T E R N E T Moving data △ Electrical signals △ Light △ Radio waves Before packets can be sent Copper wires carry Special glass fibres, Different types between devices, they have to ones and zeroes as called fibre optic of radio waves can be translated into binary signals electrical signals of cables, transmit data carry ones and zeroes (ones and zeroes) that can travel different strengths. as pulses of light. without using wires. over great distances. Every device on the Internet has a “network adapter” to perform this task. Different devices send data in different forms. Ports ▽ Port numbers A device’s IP address The numbers used for ports range is like the street Just as you mail a letter to a from 0 to 65535 and are divided address of a building specific person in an apartment into three types: well-known, building, you may want to registered, and private. A port within send packets to a specific a device is program on a device. Computers IP 165.193.128.72 like an use numbers called “ports” apartment in as addresses for individual 1234 a building programs. Some common programs have ports specially Routers reserved for them. For example, deliver web browsers always receive packets like packets through port number 80. mailmen to the correct 5 78 addresses 6 EXPERT TIPS 9 10 11 12 13 14 15 16 Sockets 17 18 19 20 The combination of an IP address and a port is known as a “socket”. Sockets let programs send data directly to each other across the Internet, which is useful for things such as playing online games.
Programming in the real world
198 P R O G R A M M I N G I N T H E R E A L W O R L D Computer languages SEE ALSO Thousands of different programming languages have Computer 204–205 been created. Which one you should use depends on a games number of factors, such as the type of program being Making 206–207 written and which kind of computer it will run on. apps Popular programming languages #include <stdio.h> main() Some languages have emerged as the most popular for { creating certain types of program on certain types of computer. Here is how to run a simple “Hello World!” printf(“Hello World!”); program in a few popular programming languages. } #include <iostream> △C int main() One of the most popular { languages of all time, C is often used for programming hardware. std::cout << “Hello World!” << std::endl; } #import <stdio.h> int main(void) { printf(“Hello World!”); } △ C++ △ Objective-C alert(‘Hello World!’); Based on C, but with extra Based on C, with some extra features. Used in programs features. It has become popular △ JavaScript that need to be fast, such because of its use on Apple’s Used to create as console games. Mac and iOS devices. programs that run on web browsers, such class HelloWorldApp { <?php as simple games and public static void main(String[] args) { echo “Hello World!”; email websites. System.out.println(“Hello World!”); ?> } } △ Java ◁ PHP A very versatile language that Mostly used for creating can run on most computers. interactive websites, PHP It’s often used for coding on runs on the web servers the Android operating system. that host websites.
Search
Read the Text Version
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127
- 128
- 129
- 130
- 131
- 132
- 133
- 134
- 135
- 136
- 137
- 138
- 139
- 140
- 141
- 142
- 143
- 144
- 145
- 146
- 147
- 148
- 149
- 150
- 151
- 152
- 153
- 154
- 155
- 156
- 157
- 158
- 159
- 160
- 161
- 162
- 163
- 164
- 165
- 166
- 167
- 168
- 169
- 170
- 171
- 172
- 173
- 174
- 175
- 176
- 177
- 178
- 179
- 180
- 181
- 182
- 183
- 184
- 185
- 186
- 187
- 188
- 189
- 190
- 191
- 192
- 193
- 194
- 195
- 196
- 197
- 198
- 199
- 200
- 201
- 202
- 203
- 204
- 205
- 206
- 207
- 208
- 209
- 210
- 211
- 212
- 213
- 214
- 215
- 216
- 217
- 218
- 219
- 220
- 221
- 222
- 223
- 224
- 225
- 226