Displaying ready-made images - tasks¶
We learned how to display a ready-made image so that its upper left corner is at a given position on the screen. In some situations, the position of the upper left corner of the image will not be known to us, but will need to be calculated. In such cases, it may be necessary to know the width and height of the image. In Python’s PyGame library for the image im
, the width and height of this image are given as im.get_width()
and im.get_height()
respectively.
Baskets¶
Complete the following program to get the picture as in the example. The positions of the trees are given, and a basket should be drawn next to each tree so that the lower right corners of the basket and tree images overlap.
To complete this task, you need to calculate for each drawn basket the position of its top left corner, which can be done starting from the coordinates of the top left corner of the tree, using the widths and heights of both images.



import pygame as pg, petljapg
canvas = petljapg.open_window(800, 600, "Apples")
tree_image = pg.image.load("tree.png") # image of a tree
basket_image = pg.image.load("basket.png") # image of a basket
tree_positions = ((200, 70), (120, 150), (240, 290), (550, 170), (400, 200))
petljapg.wait_loop()
(PyGame_baskets1_eng)
Picking apples¶
Complete the following program to get the picture as in the example. The solution to this task is obtained by appending the previous program - copy it and add apples to the trees and to the baskets.
import pygame as pg, petljapg
canvas = petljapg.open_window(800, 600, "Apples")
tree_image = pg.image.load("tree.png") # image of a tree
apple_image = pg.image.load("apple_small.png") # image of an apple
basket_image = pg.image.load("basket.png") # image of a basket
apples_on_tree_positions = ((43,191), (61, 158), (124, 145), (134, 175), (160, 180))
apples_in_basket_positions = ((15, 38), (60, 41), (22, 43), (49, 45), (34, 48))
tree_positions = ((200, 70), (120, 150), (240, 290), (550, 170), (400, 200))
petljapg.wait_loop()
(PyGame_baskets_apples_eng)
Boxes¶
From the given data and images it is possible to determine the series x and y of the image coordinates of each box in each example. The order of displaying of the box pictures should also be taken into account here.
To better understand how the same series of numbers (for example, 10, 15, 20, 25, 30) can be obtained in two different orders, and what else to look for, answer the supporting question.
import pygame as pg, petljapg
canvas = petljapg.open_window(800, 600, "Boxes 1")
petljapg.wait_loop()
(PyGame_boxes1_eng)
import pygame as pg, petljapg
canvas = petljapg.open_window(800, 600, "Boxes 2")
petljapg.wait_loop()
(PyGame_boxes2_eng)
import pygame as pg, petljapg
canvas = petljapg.open_window(800, 600, "Boxes 3")
petljapg.wait_loop()
(PyGame_boxes3_eng)