Step 5 - Calculated Size
Lastly, let’s look at adding some constants and variables to make this more dynamic. We will let the user tell us what size the house should be, then calculate the positions for the shapes.
-
Start with positioning the walls. Determine what we need to calculate.
We will need to determine:
- the screen size. Create constants for
SCREEN_WIDTH
andSCREEN_HEIGHT
. - the house size - which the user will provide via the terminal at the start
- to read in house size we will need to read and convert data. So a
userInput
variable could be created for this. - the wall position (its x and y) - this is where we draw the wall.
- the screen size. Create constants for
-
Code this up and test it out:
- Add constants for screen width and height - Where else could you use these?
- Add variables for
houseSize
anduserInput
- write the terminal code to read these in - Add variables for
wallX
andwallY
- calculate these as noted above. - Compile and run and try different wall sizes.
-
As I coded this I realised I needed an extra constant -
BOTTOM_GAP
. When you find you are hard-coding values you should think if there is a meaningful name to describe the value. Naming the “bottom gap” helps make it clearer what that 100 was about, whereas the 2 does not need a different name. We are dividing by 2 to get half the value.
-
Connect the roof. Ok, this may be a bit of a challenge for you. Have a go at coding the roof based on the plan above.
-
Compile and run, then check your calculation if it doesn’t look right.
-
Finally, adjust the code so that the size of the hill is calculated from the size of the screen. It is as wide as the screen, appears 2/3rds of the way down the screen, and is 2/3rds the height of the screen.
Once you change this, try different screen sizes!
-
When you have this working you should feel confident that you can start working with graphical programs.