HomeTurtlegraficsGPanelRoboticsGameGrid WebTigerPython
 Python - Online
Deutsch   English   

17. Worksheets

 

 

WORKSHEET 1: PYTHON CITY

 

The worksheet depicts a realistic scenario in the IT industry: You are employed as a programmer in a company and are supposed to continue a project of your predecessor. You are given a complex, executable programme as a template. Your task is to understand the programme and make certain adjustments.

The programme draws a picture of a city. As the programme code contains random elements, the city will look different every time you run the programme.


1.

Copy the programme to WebTigerPython or WebTigerJython by clicking on the following button and run it several times.

Program:   

 

2.

 

Study the programme. The comments will help you to understand the programme structure.

3.

 

Change the number of houses. Initially only 30, then 70 and finally 45 houses should be drawn.

4.

The windows should be red, not yellow.

5.

 

You like the yellow windows better, but not all the windows should be illuminated. 30% of the windows should be black, the rest yellow. To do this, insert the following code in the right place
if random() < 0.4: meineFarbe = [0, 0, 0]

6.

 

The houses do not all have to be grey either. Half of the houses should have a reddish colour (e.g. [170, 100, 100]).

7.

 

A small star should be visible next to the moon. You draw the star round with the fillCircle() function.

8.

Draw 100 random stars in the night sky.

9.

The stars are not the same size. 30% have a diameter of 3, the rest 2.

10.

 

Add your own ideas to the picture (shooting stars, ships on the water, houses reflected in the water...)

 

 

WORKSHEET 2: MONDRIAN

 

The programme randomly divides the GPanel window vertically and horizontally into coloured rectangles. The colours are randomly selected from the colours list.

The graphics are reminiscent of the artwork of painter Piet Mondrian.

 

 

Program:     

# Mondrian.py
from gpanel import *
from random import *

def between(a, b):
    return a + (0.2 + 0.3 * random()) * (b - a)

def randomColor():
    while True:
        result = choice(colors)
        return result
    
def rect(xMin, yMin, xMax, yMax):
    for aColor in ('black', randomColor()):
        setColor(aColor)        
        fillRectangle(xMin, yMin, xMax, yMax)           
        xMin += delta
        yMin += delta
        xMax -= delta
        yMax -= delta
    
def maybe(bias = None):
    return choice([False,True,bias,bias] if bias!=None else [False,True])   

def draw(xMin = 0, yMin = 0, xMax = 500, yMax = 500):
    if xMax - xMin > threshold and yMax - yMin > threshold:
        if maybe(xMax - xMin > yMax - yMin):
            xMid = between(xMin, xMax)
            if maybe():
                draw(xMin, yMin, xMid, yMax)
                rect(xMid, yMin, xMax, yMax)
            else:
                rect(xMin, yMin, xMid, yMax)
                draw(xMid, yMin, xMax, yMax)
        else:
            yMid = between(yMin, yMax)
            if maybe():
                draw(xMin, yMin, xMax, yMid)
                rect(xMin, yMid, xMax, yMax)
            else:
                rect(xMin, yMin, xMax, yMid)
                draw(xMin, yMid, xMax, yMax)
    else:
        rect(xMin, yMin, xMax, yMax)

makeGPanel(0, 500, 0, 500)
colors = ['gray', 'lime', 'red', 'white', 'blue', 'yellow']
delta = 6
threshold = 100
setColor ('black')
draw()
► Copy to clipboard

 

1. Run the programme several times and try to understand its structure

2.

What does the Python function choise() do?

3.

Extend the list of colours with additional colours, e.g. cyan, magenta...

4.

The function draw(xMin, yMin, xMax, yMax) is recursive. What is the significance of the variable threshold? Change the value of this variable and observe the effect.

5.

What is the significance of the variable delta? Change its value and observe the effect.

6.

In the given programme, a new graphic is drawn after each programme start. Now, a new image should be drawn with each mouse click. The draw() function should not be called in the main programme, but in the callback function onMousePressed(), which you must first define and register with makeGPanel().

7.

 

Use the left and right mouse buttons to switch between two different colour lists.
You can find more colours under https://www.w3schools.com/colors/colors_x11.asp

8.

Expand the programme with your own ideas (thinner/thicker black lines, different area division, etc.)

 

 

WORKSHEET 3: BRAIN GAME

 


Game description:
The playing field consists of a lamp that can glow in red, yellow, green and blue, and is white when switched off.

There are also four circular buttons in red, yellow, green and blue. The lamp always displays longer sequences of random colours: first with one colour, then with two colours, etc. After each sequence is displayed, the player must repeat the sequence by pressing the buttons. If they do this correctly, the length of the sequence is increased by 1; if they make a mistake, the game is over. The aim is to achieve the longest possible sequence.

 

 

The problem is solved in 6 steps:

Step 1: Displaying the playing field
Use the following programme framework:

Program: 

# BrainGame0.py
from gpanel import *

def showLamp(col):
    pass

def showButton(number):
    pass

def setup():
    for i in range(4):
        showButton(i)
    showLamp(-1)
  
makeGPanel(-200, 200, -200, 200)
setColor("black")
fillRectangle(400, 400)
addStatusBar(30)
setup()
► Copy to clipboard

Write the functions according to the following documentation::

showLamp(col) Draws the lamp – a filled circle with a diameter of 100 in the centre of the playing field. The parameter col determines the fill colour. Red (col = 0), yellow (col = 1), green (col = 2), blue (col = 3), white (otherwise, e.g. col = -1)

showButton(number)

Draws a button: coloured circle with a diameter of 50.

Number
Color
Position
0
red
(100, 0)
1
yellow
(0, -100)
2
green
(-100, 0)
3
blue
(0, 100)
else
nothing

setup()

Creates the playing field in the initial situation

 

Step 2: Use the mouse to switch on the lamp in 4 colours
When you press the colour buttons, the lamp with the same colour is switched on. When you release the button, the lamp returns to white. Use the callbacks: onMousePressed(x, y) and onMouseReleased(x, y), which you must register with makeGPanel(). To do this, use a variable buttonIndex in the range 0...3 for clicks on buttons and -1 and -2 for clicks on white and black areas.

def onMousePressed(x,y):    
    if getPixelColorStr(x, y) == "red":
        buttonIndex = 0
    elif ...

    elif getPixelColorStr(x, y) == "white":
        buttonIndex = -1
    else:
        buttonIndex = -2    
    if buttonIndex >= 0:
        showLamp(buttonIndex)

def onMouseReleased(x,y):
    showLamp(-1)                
  
makeGPanel(-200, 200, -200, 200, mousePressed = onMousePressed, 
                                 mouseReleased = onMouseReleased)
  


Stept 3: Random sequences with the colours red, yellow, green and blue

Import the integer random numbers with from random import randint. Insert the following lines in the main section, which creates a list seq with n random numbers in the range 0..3. The number of elements in the sequence is set to n = 3 for testing purposes.

seq = []
n = 3
for i in range(n):
    seq.append(randint(0, 3))
setStatusText("Showing sequence with length " + str(n))    
showSequence()
  

Write the function showSequence() that displays these sequences. The display duration is set to 1000 milliseconds here.

def showSequence():
    for k in seq:
        delay(1000)
        showLamp(k)
        delay(1000)
        showLamp(-1)
  


Step 4: Repeat and check the sequence
After the sequence of three colours is displayed, the user begins repeating the colour sequence by pressing the buttons. If they make a mistake, the game immediately stops with an IsOver message, if they do it correctly, a success message is displayed.

The correct sequence is tested each time the mouse is released, i.e. in the callback onMouseReleased(x, y). To do this, the variable clickCount must be used to count the mouse clicks already made and with

if seq[clickCount] == buttonIndex: 
      clickCounr += 1
  

check whether the correct click was made. If this is the case, increase clickCount; otherwise, set a flag isOk = False. To inform the main programme when the test is complete, use a flag isUserActive.

global clickCount, isUserActive, isOk
if seq[clickCount] == buttonIndex: 
    setStatusText("Sequence confirmed")
    clickCount += 1
else:
    isOk = False
    setStatusText("Sequence false")
if clickCount == len(seq):
    isUserActive = False
    isOk = True
  

Once the entire sequence has been successfully tested, set isOk = True. The variables clickCount, isOk and isUserActive must be defined as global and initialised in the main programme. In the main programme, insert a wait loop that runs until the user action is complete.

isUserActive = True
isOk = False
while isUserActive:
    delay(10)
if isOk:
    setStatusText("Sequence confirmed")
else:
    setStatusText("Sequence false")    
delay(2000)
  


Stept 5: Extend the sequence
So far, you have been playing with a fixed sequence length of 3. Now you have to start with a sequence length of 1 according to the game rules and increase it by 1 if the user guesses correctly. You continue doing this until they make a mistake. You have prepared the programme so well that this extension is easy to implement. After setup() and initialising n = 1, add the rest of the programme to an endless while loop and increase n in it when the user is successful. If they make a mistake, break the loop with break.
setup()
n = 1
while True:
    clickCount = 0
    setStatusText("Showing sequence with length: " + str(n) + "...")
    delay(2000)
    seq = []
    for i in range(n):
        ....
    
    showSequence()
    setStatusTex("Click tu repeat sequence")
    isUserActice = True
    isOk = False
    if isOk:
        setStatusText("Sequence confirmed")
        delay(2000)
        n += 1
    else:    
        break
setStatusText("sequence failed")

Step 6: Making the game robust
The game can already be played if the user follows certain rules and does not click the mouse at the wrong moment. Therefore, you need to improve the programme so that a mouse click at the wrong moment does not lead to disaster. To do this, introduce another flag, isMouseEnabled, in the main programme. This is set to False at the beginning of the while True loop and is only set to True when the user is allowed to use the mouse, i.e. when they have to return the sequence. If isMouseEnabled = False, simply return to the two callbacks without taking any further action.

 if not isMouseEnabled:
      return