Here you will find the source code for the space game, as described in the upcoming book Graphic Guide to Python
Copyright 2018 Antony Lees
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
# ship direction x_direction = 0 y_direction = 0 # coordinates of the ship ship_x = 0 ship_y = 0 # current score score = 0 def setup(): # screen size size(600,400) # black background background(0) # white lines stroke(255) # smooth edges smooth() # draw rectangles from the centre rectMode(CENTER) # initialise the ship initialise_ship() # set score to 0 score = 0 def initialise_ship(): global x_direction global y_direction global ship_x global ship_y # choose random direction x_direction = random(-2, 2) y_direction = random(-2, 2) # start in the middle of the screen ship_x = width//2 ship_y = height//2 def draw(): # redraw the background background(0) # display the current mouse coordinates text("({},{})".format(mouseX, mouseY), mouseX, mouseY) # draw the targeting lines so that they leave a space around the mouse pointer line(0, 0, mouseX - 20, mouseY- 20) line(width, 0, mouseX + 20, mouseY - 20) line(0, height, mouseX - 20, mouseY + 20) line(width, height, mouseX + 20, mouseY + 20) # display the ship draw_ship() # display the score display_score() def draw_ship(): global show_ship global ship_x global ship_y global x_direction global y_direction # draw the ship rect(ship_x, ship_y, 5, 5) # left wing line(ship_x - 10, ship_y - 10, ship_x - 10, ship_y + 10) line(ship_x, ship_y, ship_x - 10, ship_y) # right wing line(ship_x + 10, ship_y - 10, ship_x + 10, ship_y + 10) line(ship_x, ship_y, ship_x + 10, ship_y) # display its coordinates text("({},{})".format(int(ship_x), int(ship_y)), ship_x, ship_y + 25) # update coordinates for next time ship_x = ship_x + x_direction ship_y = ship_y + y_direction # if current coordinates mean the ship has left the screen if ship_x < 0 or ship_x > width or ship_y < 0 or ship_y > height: # new ship initialise_ship() def display_score(): # display near the top of the screen text("Score: {}".format(score), width/2, 10) def mouseClicked(): global score global show_ship # fire! stroke(0, 255, 0) strokeWeight(3) line(0, height//2, mouseX, mouseY) line(width, height//2, mouseX, mouseY) # reset colour stroke(255) strokeWeight(1) # if the left mouse button was clicked if mouseButton == LEFT: # if the button was pressed in the region of the ship if mouseX > (ship_x - 10) and mouseX < (ship_x + 10): # add 1 to the score score += 1 initialise_ship()