Tutorial 5
We're going to keep making the tutorials smaller, letting them transition to being more like worked examples. Why? Because for most students, it'll be more productive for you to work on your projects.
The challenge for this tutorial is to build some controls, using Vue or React, that will let you set up a Conway's Game of Life game.
Clone the code
First, get the code and put it somewhere you can load it in your browser.
To get the code, open a terminal, cd
into the public directory of whichever webserver you are using, and:
git clone https://gitlab.une.edu.au/cosc360in2018/tutorial-conway-life-t5.git
This will clone this code using the git version control system. That will, amongst other things, let you switch between different branches (eg, the solution and the start of the exercise)
Check it's working
Open index.html
in the browser, and you should find yourself faced with Conway's Game of Life from Tutorial 4.
Install loaders for Vue or React
The repository contains all the code from the previous tutorial, but not a copy of node_modules
which would be too large. Let's make NPM go and get all the modules we've already declared in packages.json
:
npm install
And before we go any further, let's put webpack into development mode. In webpack.config.js
, at the top of module.exports
, set:
mode: 'development',
If you're using Vue, install the modules for vue:
npm install --save-dev vue vue-class-component vue-property-decorator
You'll also need to alter webpack.config.js
to load the version of Vue that includes the template compiler. Change the resolve
block to:
resolve: {
extensions: ['.ts', '.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
},
If you're using React, though, you'll need to install the modules for react:
npm install --save react react-dom @types/react @types/react-dom
and edit tsconfig.json
to tell TypeScript to target React as the Virtual DOM for .tsx
files
{
"compilerOptions": {
"outDir": "./built/",
"sourceMap": true,
"strict": true,
"noImplicitReturns": true,
"module": "es2015",
"moduleResolution": "node",
"target": "es5",
"experimentalDecorators": true,
"jsx": "react"
},
"include": [
"./src/**/*"
]
}
Now the challenge
It might be useful to get ready for development by telling npm to watch our project for changes, and rebuild it automatically:
```sh
npm run build -- --watch
```
The challenge:
Using either React or Vue, create a small block that will let us set up the Game of Life game. We're going to keep the game itself rendered through d3, showing how they exist on the page, but this should have:
- Fields for how many columns and rows you want
- A button that when clicked will create the game (and trigger d3 to rerender it)
- A field for how long (in ms) each tick should be -- default it to 500
- A button that will toggle whether the tick-timer is started or not. This button should only be enabled when the game has been created.
For this exercise, we're not going to put the d3-rendered game inside the element controlled by Vue or React -- we'll just have them co-exist in different elements on the same page.
How to go about this
As is typical, I'd recommend you start just by working out the data structure for what you want to render. Looking at the requirements above, something like this seems appropriate:
export interface GameConfig {
w:number
h:number
started:boolean
created:boolean
period:number
}
The next task I would suggest is just creating this object and rendering it to a little UI using your chosen framework. That'll let you fiddle around with the layout.
Then, wire up the functionality. Note that you'll probably need to change life
. At the moment, it's a constant in that file. You will probably want it to be a variable that can be set by calling a function.
Solving this with Vue
A worked solution can be found on the vue-solution
branch of this repository. To check out the code, you could run git checkout vue-solution
. But let's talk you through it.
Getting Vue in there
First, let's get Vue rendering something, even if just Hello World.
In index.html, create a div that Vue can render to. Let's put this above the svg for the game:
<div id="app"></div>
And inside index.ts, let's import Vue and render something to that div
import Vue from "vue";
let v = new Vue({
el: "#app",
template: `
<div>
Hello {{ name }}
</div>
`,
data: {
name: "Vue"
}
})
Reload, and check we get "Hello Vue" appearing. If so, good -- Vue is working, can compile templates, and we can progress.
Defining a ConfigView
Let's create a new TypeScript file gameConfig.ts
to define a component in.
First, let's bring our definition of a game config here:
interface GameConfig {
w:number
h:number
started:boolean
created:boolean
period:number
}
Next, we'll import Vue and Component:
import Vue from "vue"
import Component from 'vue-class-component'
And then let's start defining the component. This is going to take a GameConfig as a prop, and is going to alter its fields
@Component({
props: {
config: Object as () => GameConfig
},
template: `
<div>
This will render a game config
</div>
`
})
class ConfigView extends Vue {
config!: GameConfig
constructor() {
super()
console.log("a new config view was placed")
}
}
I've included a constructor this time, so we can see in the console that we've tried to add the component.
Now, we're going to need to export the definitions of GameConfig
and ConfigView
:
export {
GameConfig as GameConfig,
ConfigView as ConfigView
}
In index.ts
, let's import our definitions:
import { ConfigView, GameConfig } from "./gameConfig"
Now we should be able to create a config (notice we're using TypeScript's structural typing here):
let config:GameConfig = {
w: 40,
h: 20,
started: false,
created: false,
period: 500
}
And we should be able to alter our invocation of Vue to use our new component (don't forget to include it in the components section at the bottom):
let v = new Vue({
el: "#app",
template: `
<div>
<ConfigView :config="config"></ConfigView>
</div>
`,
data: {
config: config
},
components: {
ConfigView
}
})
Making ConfigView alter the config
Next, let's go back to gameConfig.ts
and make our ConfigView render something more interesting that actually alters the fields.
The full HTML of the component's template in the solution is quite long, but that's because I've used Bootstrap's components to make it look pretty — the Vue aspects are quite small in there. So rather than talk you through all of my solution HTML, let's just do a short and not-so-pretty version here.
We're going to need input elements for the width and height of the grid.
The config
prop we've passed in is read-only. But it's a read-only reference to a mutable object. So we're going to bind some input controls to its fields.
First, in the component's template, we need inputs for the width and height:
template: `
<div>
Columns:
<input type="number" v-model:value="config.w" />
Rows:
<input type="number" v-model:value="config.h" />
</div>
`,
We've used v-model
rather than v-bind
to give us a two-way binding between the value of the input field and the value of config.w
and config.h
. Remember, we can't alter config
(the reference) but we can alter its fields.
If you reload the page, you should now have some fields above the grid, and they should appear initialised to 40 and 20.
Next, let's wire up a Create button. Inside the component's template, put:
<button v-bind:disabled="config.created" v-on:click="create">Create</button>
This bind's the button's "disabled" attribute so that it will become disabled when config.created
becomes true. And it sets the button so that when it is clicked it will call create()
in the component's class. We'd better go and make the create function. Remember, it needs to be a method on the ConfigView class:
create() {
console.log("Create was pressed")
this.config.created = true
}
Reload and check that logs to the browser console when you hit the button (and the button should also become disabled).
Altering render
We need to let our component actually configure our Life
instance.
First, in life.ts
, let's turn life
into a variable, and also add a create function that accepts a GameConfig
and a function for getting the value of life.
import { GameConfig } from "./gameConfig"
let life:Life = new Life(0,0)
function create(config:GameConfig) {
console.log(config.w)
life = new Life(config.w, config.h)
render()
}
function getLife() {
return life
}
Next, make sure those are exported
export {
getLife as getLife,
create as create,
render as render
}
Making ConfigView set up the game
Let's go back to gameConfig.ts
and import those definitions
import { create, render, getLife } from './render'
We can now alter the definition of our create()
method on ConfigView
to actually call create
in render.ts
:
create() {
create(this.config) // note this calls create in render.ts that we imported
render()
this.config.created = true
}
Reload, and see if it works.
Setting up the timer
JavaScript timers give you a timer id that is a number. So in our ConfigView
class let's add a field that can remember it. This is not a prop, just an ordinary field on the class. And the ?
means it might be null.
intervalId?: number
Let's now create a method on the class that can start and stop an actual timer using this field. Notice that we're using the getLife
and render
functions from render.ts
that we imported.
toggleTimer() {
if (this.config.started) {
clearInterval(this.intervalId)
this.config.started = false
} else {
this.intervalId = setInterval(() => {
let l = getLife()
if (l) l.stepGame()
render()
}, this.config.period)
this.config.started = true
}
}
And now all we need do is add some HTML to the template that'll reference the remaining fields of our GameConfig
and will call this method:
Period:
<input type="number" v-model:value="config.period" />
<button v-bind:disabled="!config.created" v-on:click="toggleTimer">
{{ config.started ? "Stop" : "Start" }}
</button>
Notice this button is bound so it's disabled until we've created the game. It's onClick is bound to the toggleTimer
method, and the text changes from Start to Stop depending on whether the timer is already started.
Solving this tutorial with React
There's a worked solution to this tutorial using React.js on the react-solution
branch. But let's talk you through it.
Some config changes
First, there's some config changes we'll make to make things easier. By default, React won't give you nice error messages -- it left them out of the library to save space. So make the HTML load the development scripts from our node_modules directory:
<script src="./node_modules/react/umd/react.development.js"></script>
<script src="./node_modules/react-dom/umd/react-dom.development.js"></script>
And tell webpack not to put React itself into bundle.js (because we're loading its development scripts separately). In webpack.config.js, inside module.exports
:
externals: {
"react": "React",
"react-dom": "ReactDOM"
}
We're also going to want to use TSX, so let's update compilerOptions in tsconfig.json
:
"jsx": "react"
And let's also rename index.ts
to index.tsx
, and then update webpack.congfig.js
to tell it about the new entry point:
entry: './src/index.tsx',
Getting React on-screen
Let's get React rendering something, even if just Hello World.
In index.html, create a div that Vue can render to. Let's put this above the svg for the game:
<div id="app"></div>
And inside index.tsx, let's import React and ReactDOM, and something to that div
import * as React from "react";
import * as ReactDOM from "react-dom";
and now for our first bit of TSX:
ReactDOM.render(
<div>Hello React</div>,
document.getElementById("app")
);
Set webpack watching the files:
npm run build -- --watch
Reload index.html in the browser, and check we get "Hello Vue" appearing. If so, good -- React is working and we can progress.
Creating a ConfigView component
Let's create a file called `gameConfig.tsx'.
First, let's import react:
import * as React from "react"
import * as ReactDOM from "react-dom"
Then let's define our GameConfig type:
export interface GameConfig {
w:number
h:number
started:boolean
created:boolean
period:number
}
And then let's define a React component:
export class ConfigView extends React.Component<GameConfig, {}> {
render() {
return <div>This will render some game config</div>
}
}
Notice that in the angle brackets, we've said this component's properties are defined by the GameConfig interface -- so, it has properties for w
, h
, etc.
Let's go back to index.tsx
and use it.
First, we need to import GameConfig
and ConfigView
:
import { GameConfig, ConfigView } from "./gameConfig"
Then we need to create some config:
let config:GameConfig = {
w: 40,
h: 20,
created: false,
started: false,
period: 500
}
and then let's alter our React call to use it:
ReactDOM.render(
<ConfigView {...config}></ConfigView>,
document.querySelector("#app")
);
We've used the spread operator {...config}
here to set all of the ConfigView's props at once.
Reload and see if the message is in the UI.