TwoShips
- Created by ProfAnand on
30.01.2022, 21:20
GraphicSVG Game
Fork
×
-- Keyboard control for two players type alias Model = { time : Float , posL : (Float,Float) , posR : (Float,Float) , velL : (Float,Float) , velR : (Float,Float) , winner : String } winR = 5 winX = -60 winY = -40 -- two players are moving around, call them L and R, so we need to keep -- track of both where they are, and where they are headed (their velocity) init = { time = 0 , posL = (-20,0), posR = (20,0), velL = (0,0), velR = (0,0), winner = "" } -- the definition of velocity is the change in the position in a unit of time -- the definition of acceleration is the change in the velocity in a unit of time -- Wow! Those sound very similar. -- We only need function to make the change needed over one unity of time. -- We will use the time between Ticks as the unit of time, although -- this is not a great unit of time, since Ticks come more slowly when -- your computer is busy, or just gets slow. timeStep (changeX,changeY) (x,y) = (x + s * changeX, y + s * changeY) friction (x,y) = (0.95 * x, 0.95 * y) -- To make the game playable, we use a scaling factor, s. s = 0.1 -- You aren't supposed to know about this defintion of velocity until grade 11, -- so don't tell anyone we told you. -- we don't need to use any notifyTap or notifyTapAt in this type of game myShapes model = [ circle winR |> filled green |> move (winX,winY) , drawShip (rgb 255 0 0) model.posL model.velL , drawShip (rgb 0 0 255) model.posR model.velR , text model.winner |> centered |> size 40 |> filled (rgb 0 0 255) ] isInCircleWithRCentre r (x,y) (u,v) = (x-u)^2 + (y-v)^2 < r^2 -- nor do we need any new messages type Msg = Tick Float GetKeyState -- since we will have two ships which look alike, we will use will make a -- function to draw them, which takes the colour as an input -- Do you know why this ship points in the direction of motion? drawShip clr pos (vx,vy) = group [ polygon [(2 * vx,2 * vy),(-vy,vx),(vy,-vx)] |> filled clr , circle 1 |> filled clr ] |> move pos -- the update function records the time (in case we want animations) -- and uses the timeStep function to change the two positions and two -- velocities according to their definitions update msg model = case msg of Tick t (_,accelR,accelL) -> { model | time = t , posL = timeStep model.velL model.posL , posR = timeStep model.velR model.posR , velL = timeStep accelL model.velL |> friction , velR = timeStep accelR model.velR |> friction , winner = if model.winner == "" then if isInCircleWithRCentre winR (winX,winY) model.posR then "Blue wins!" else if isInCircleWithRCentre winR (winX,winY) model.posL then "Red wins!" else "" else model.winner } main = gameApp Tick { model = init, view = view, update = update, title = "Game Slot" } view model = collage 192 128 (myShapes model)
Create a basic game with user interaction, but no commands (needed for better random numbers).