Week 3

This week, we changed how we handled keyboard input, and abstracted out Rectangle into a class. Now, moving the player feels smoother and we can create as many rectangles as we want to in a simple manner.

I will skip showing our full code base, as it's getting substantial at this point. If you would like to view the whole, uninterrupted code, I upload it on Github every week.

The Rectangle class

class Rectangle {
	constructor(x, y, w, h) {
		this.x = x;
		this.y = y;
		this.width = w;
		this.height = h;
		this.color = "#000";
		this.left = false;
		this.right = false;
		this.up = false;
		this.down = false;
	update() {
		if (this.left == true) {
			this.x -= 1;
		if (this.right == true) {
			this.x += 1;
		if (this.up == true) {
			this.y -= 1;
		if (this.down == true) {
			this.y += 1;
	render() {
		ctx.fillStyle = this.color;
		ctx.fillRect(this.x, this.y, this.width, this.height);

This class is the major addition this week. You can read more about classes here. We have replaced the global variables x and y with fields in this class, and essentially copied the render method from main. This allows our code to become much more reusable. The left, right, up, and down fields help us with user input, along with the update function, which will be covered shortly.

var player = new Rectangle(10, 10, 20, 20);

This is how we now instantiate our player. It is much easier and more extensible.

the main() function

function main() {
	//clear screen
	ctx.fillStyle = "#FFF";

Now, instead of having to put all the details of everybody's update routine in the main function, we can now simply call update() and render() for every object that needs it. Although this model can be abstracted further, our program is not complex enough for it to be beneficial.

The keyup(e) function

function keyup(e) {
	switch(e.keyCode) {
		case 37:
			player.left = false;
		case 38:
			player.up = false;
		case 39:
			player.right = false;
		case 40:
			player.down = false;

The new function we added is keyup, which we also added by using document.addEventListener() with the "keyup" argument. This mirrors the new keydown function, although player.left, right, up, and down are set to true in the keydown function. This is necessary for our new way of processing keyboard input. The actual change in location is done from the player.update() call in main.