Here you will find the source code for the space game, as described in the upcoming book Graphic Guide to R
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.
settings <- function() {
# screen size
size(600,400)
}
setup <- function() {
initialise_ship()
# black background
background(0)
# white lines
stroke(255)
score <<- 0
}
draw <- function() {
# redraw the background
background(0)
# 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 current mouse coordinates
coord_text <- paste("(", mouseX, ",", mouseY,")")
text(coord_text, mouseX, mouseY)
# draw the ship
rectMode(CENTER)
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)
# 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 || ship_x > width || ship_y < 0 || ship_y > height) {
# new ship
initialise_ship()
}
# display near the top of the screen
score_text <- paste("Score", score)
text(score_text, width/2, 10)
}
initialise_ship <- function() {
# 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
}
mouseClicked <- function() {
# 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 (mouseButtonVar == LEFT) {
# if the button was pressed in the region of the ship
if (mouseX > (ship_x - 10) && mouseX < (ship_x + 10)) {
score <<- score + 1
initialise_ship()
}
}
}