NODE.js Hackathon: Building a Tik-Tac-Toe Game

Introduction to TypeScript:

Hello friends, woof! I am TRex, a German Shepherd, and today I'm going to narrate a tail-wagging story about my day, intertwined with learning about TypeScript. Hold on to your leashes as we embark on this pawsome journey together.

Early Morning Walks and TypeScript Introduction:

Every day starts with a brisk walk as the sun rises.
Just as my day has a structured beginning, TypeScript is a structured superset of JavaScript.
It adds static types to the language, allowing you to write safer and more robust code by catching errors during development rather than runtime.
Enabling us to do Design-based, Component-driven Programming.

Breakfast Time and Variables:

After our walk, it's breakfast time! I have two bowls: one for kibble and one for water.
In TypeScript, think of these bowls as variables, containers that hold data. You might have a kibble variable and a water variable, and you can specify what type of data (or treat) each variable holds, like string, number, or boolean.
typescriptCopy code
let kibble: number = 100;
let water: string = "fresh";

Since tyepscript is object oriented typed, why can't I say int i = 1 in TypeScript. Should it not allow int ?

In TypeScript, the syntax is a bit different from other statically typed languages like Java or C#. TypeScript is a superset of JavaScript, and it maintains a lot of JavaScript's syntax while adding static typing. In TypeScript, you use the number type for all numeric values, whether integer or floating-point.
So, instead of writing:
javaCopy code
int i = 1; // This is Java or C#, not TypeScript

You would write:
typescriptCopy code
let i: number = 1; // This is TypeScript

In TypeScript, the : number syntax is used to annotate a variable as holding a numeric value. TypeScript does not have specific integer and floating-point types like some other languages do (e.g., int and float in C# or Java).
The number type in TypeScript is used for all numeric values. This design decision was made to keep the language simpler and more aligned with JavaScript, which also does not distinguish between different kinds of numbers.

Calling Functions : Playing Fetch and Functions:

Next, we play fetch!
When you throw the ball (call a function in TypeScript), you expect to get the ball back (return a value).
Just like how you know the ball will come back to you, in TypeScript, you can specify what type of value a function should return.
function fetchBall(times: number): string {
return `Fetched the ball ${times} times!`;

Nap Time and Interfaces:

After a good game of fetch, I settle down for a nap.
I have different spots to choose from: my bed, the couch, or the rug.
I choose based on comfort and warmth.
Similarly, in TypeScript, you can use interfaces to define a type and ensure objects have the right shape, like choosing the perfect napping spot.
typescriptCopy code
interface NapSpot {
location: string;
comfortLevel: number;

Evening Patrol and Classes:

In the evening, it’s patrol time! I guard my yard from squirrels and birds.
My guarding duties can be thought of as a class in TypeScript, with different methods (actions) and properties (attributes).
typescriptCopy code
class GuardDog {
name: string = "TRex";
enemy: string = "squirrels";
bark(): void {
console.log("Woof! Stay away from my yard!");

Bedtime and Compiling:

At the end of my adventurous day, I curl up in my bed. Just as I recap my day's events before closing my eyes, TypeScript has a compilation step, transforming your TypeScript code into JavaScript, ensuring it’s free from errors and ready to run in any environment.
bashCopy code
tsc myCode.ts

A Tail End Note:

So friends, as I drift into my doggy dreams, remember that TypeScript is here to make your coding journey more structured and error-free, just like the organized parts of my day.
It adds types, interfaces, and classes to JavaScript: thereby enabling design-driven programmer or component-based programming.
TS provides a more robust coding experience.
Happy coding and tail wags to you all!
Love, woof, and licks,
TRex 🐾

Study this material in conjunction with : 6 Forms of Functions in JavaScript

Below is an example of a TypeScript program to demonstrate string handling by randomly generating five 5-letter words from the alphabet string. This program uses classes and objects for structure.

class RandomWordGenerator {
alphabet: string = "abcdefghijklmnopqrstuvwxyz";

// Method to generate a random 5-letter word
generateWord(): string {
let word = "";
for (let i = 0; i < 5; i++) {
const randomIndex = Math.floor(Math.random() * this.alphabet.length);
word += this.alphabet[randomIndex];
return word;

class WordList {
words: string[] = [];

// Method to add a word to the words array
addWord(word: string): void {

// Method to display the words
displayWords(): void {
console.log("Generated Words: ", this.words.join(", "));

// Create objects of the classes
const randomWordGenerator = new RandomWordGenerator();
const wordList = new WordList();

// Generate five 5-letter words and add them to the words array
for (let i = 0; i < 5; i++) {
const word = randomWordGenerator.generateWord();

// Display the generated words


RandomWordGenerator class:
alphabet: a string containing all the letters of the alphabet.
generateWord(): a method that generates a random 5-letter word. It selects a random character from alphabet five times and concatenates them to form a word.
WordList class:
words: an array to hold the generated words.
addWord(word: string): a method that adds a word to the words array.
displayWords(): a method that displays the words stored in the words array.
Creating objects of the classes:
randomWordGenerator: an object of RandomWordGenerator class.
wordList: an object of WordList class.
Generating and displaying words:
A for loop runs 5 times to generate five 5-letter words.
Each generated word is added to the words array of the wordList object using the addWord() method.
The displayWords() method is called on the wordList object to display the generated words.
To run this program, ensure you have TypeScript installed, then compile the TypeScript code to JavaScript using the tsc command and execute the JavaScript code using the node command.
bashCopy code
tsc filename.ts
node filename.js

A detailed example of a TypeScript program that showcases the use of interfaces, multiple classes, and complex method interactions.

The program involves arithmetic operations on numbers, with various classes and interfaces to handle these operations.

// Interface for Basic Arithmetic Operations
interface BasicArithmetic {
add(a: number, b: number): number;
subtract(a: number, b: number): number;

// Interface for Advanced Arithmetic Operations
interface AdvancedArithmetic extends BasicArithmetic {
multiply(a: number, b: number): number;
divide(a: number, b: number): number;

// Basic Calculator Class implementing BasicArithmetic Interface
class BasicCalculator implements BasicArithmetic {
add(a: number, b: number): number {
return a + b;

subtract(a: number, b: number): number {
return a - b;

// Advanced Calculator Class implementing AdvancedArithmetic Interface
class AdvancedCalculator extends BasicCalculator implements AdvancedArithmetic {
multiply(a: number, b: number): number {
return a * b;

divide(a: number, b: number): number {
if (b === 0) throw new Error("Cannot divide by zero!");
return a / b;

// Interface for Calculator Handler
interface CalculatorHandler {
handleCalculation(calculator: AdvancedArithmetic, a: number, b: number): void;

// Calculator Handler Class
class Handler implements CalculatorHandler {
handleCalculation(calculator: AdvancedArithmetic, a: number, b: number): void {
console.log("Addition: ", calculator.add(a, b));
console.log("Subtraction: ", calculator.subtract(a, b));
console.log("Multiplication: ", calculator.multiply(a, b));
console.log("Division: ", calculator.divide(a, b));

// Using the classes and interfaces
const advancedCalculator = new AdvancedCalculator();
const handler = new Handler();
handler.handleCalculation(advancedCalculator, 10, 5);


BasicArithmetic: Contains method signatures for basic arithmetic operations (add, subtract).
AdvancedArithmetic: Extends BasicArithmetic and adds method signatures for advanced arithmetic operations (multiply, divide).
CalculatorHandler: Contains a method signature for handling calculations.
BasicCalculator: Implements BasicArithmetic by providing implementations for add and subtract methods.
AdvancedCalculator: Extends BasicCalculator and implements AdvancedArithmetic by providing implementations for multiply and divide methods.
Handler: Implements CalculatorHandler by providing an implementation for handleCalculation, which takes an object of type AdvancedArithmetic, two numbers, and performs various arithmetic operations using the passed object.
Using the Classes and Interfaces:
An object of AdvancedCalculator (advancedCalculator) and Handler (handler) is created.
The handleCalculation method is called on the handler object, passing advancedCalculator, and two numbers (10 and 5) as arguments.
This program demonstrates the use of interfaces for enforcing method signatures, extending interfaces, implementing interfaces in classes, inheritance in classes, and handling complex method interactions and parameter passing.

5 exercise drills teaching the elements of typescript: variables and comparisions, if then, loops, arrays classes ,objects

TypeScript Exercise Drills

Below are five exercise drills to help you practice and understand the basic elements of TypeScript including variables and comparisons, conditionals (if-then), loops, arrays, classes, and objects.

Exercise 1: Variables and Comparisons


Understand how to declare variables and perform comparisons in TypeScript.


Declare two variables, a and b, and assign them different integer values.
Compare these two variables to check which one is greater or if they are equal.
Output the result to the console.

Expected Output:

"a is greater than b" if a is greater,
"b is greater than a" if b is greater,
or "a is equal to b" if they are equal.
typescriptCopy code
let a: number = 5;
let b: number = 3;
// Your code here

Exercise 2: If-Then Conditions


Use if-then conditions to control the flow of the program.


Write a program that checks whether a given number is even or odd.
Output the result to the console.

Expected Output:

"The number is even" if the number is even,
or "The number is odd" if the number is odd.
typescriptCopy code
let number: number = 4;
// Your code here

Exercise 3: Loops


Use a loop to iterate over numbers and perform operations.


Write a program that prints the first 10 multiples of a given number.

Expected Output:

"1 x number = result"
"2 x number = result"
"10 x number = result"
typescriptCopy code
let number: number = 2;
// Your code here

Exercise 4: Arrays


Understand how to declare and manipulate arrays in TypeScript.


Create an array of five numbers.
Calculate and output the sum of the numbers in the array.

Expected Output:

"The sum of the array is: result"
typescriptCopy code
let numbers: number[] = [1, 2, 3, 4, 5];
// Your code here

Exercise 5: Classes and Objects


Create and manipulate classes and objects in TypeScript.


Create a class called Person with properties name and age.
Create an object of this class and output the properties to the console.

Expected Output:

"The person's name is: name"
"The person's age is: age"
typescriptCopy code
class Person {
name: string;
age: number;
// Your constructor and methods here

// Your code here


Make sure to test your code for each exercise to ensure it works as expected. Use these exercises as a way to reinforce your understanding of TypeScript fundamentals.

NODE.js Hackathon: Building a Tik-Tac-Toe Game


Greetings everyone,
Welcome to this exciting Hackathon event! As an experienced professor, I’m eager to see the innovation and creativity from each one of you.
This Hackathon is focused on Node.js and TypeScript, bringing together backend and frontend development to create an interactive web-based Tic-Tac-Toe game where a human plays against the computer.


Strengthen understanding of Node.js and TypeScript.
Experience building and running an HTTP server.
Work with the HTML canvas element for frontend development.
Implement a basic AI for the computer's move.


Step 1: Setting Up Your Project

Initialize a new Node.js project.
Install necessary packages: typescript, express.
Set up your TypeScript configuration.
bashCopy code
npm init -y
npm install typescript express
npx tsc --init

Step 2: Creating the HTTP Server

Create an index.ts file:


index1.ts:1:17 - error TS2580: Cannot find name 'require'. Do you need to install type definitions for node? Try ` ​npm i --save-dev @types/node

import express from 'express';

const app = express();
const PORT = 3000;


app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);

In the public directory, create your HTML file index.html with a canvas element for the Tic Tac Toe board.

Step 3: Frontend Development In index.html:

Use the canvas API to draw the Tic Tac Toe grid and game pieces.
Handle user clicks on the canvas to make a move.
Send the move to the server and wait for the computer’s move in response.


Drawing the Tic Tac Toe Grid and Game Pieces
Create the canvas element and set up the script for handling the canvas API.

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic Tac Toe</title>
canvas {
border: 1px solid black;
<canvas id="board" width="300" height="300"></canvas>
// JavaScript code will go here

Inside the <script> tag:
Get the canvas context.
Draw the Tic Tac Toe grid and handle drawing the 'X' and 'O' pieces.

const canvas = document.getElementById('board');
const ctx = canvas.getContext('2d');
const cellSize = 100;
let board = [['', '', ''], ['', '', ''], ['', '', '']];
let currentPlayer = 'X';

// Drawing the Tic Tac Toe Grid
for (let i = 0; i < 4; i++) {
ctx.moveTo(i * cellSize, 0);
ctx.lineTo(i * cellSize, canvas.height);
ctx.moveTo(0, i * cellSize);
ctx.lineTo(canvas.width, i * cellSize);

// Drawing Game Pieces
function drawPiece(x, y, player) {
const xPos = x * cellSize + cellSize / 2;
const yPos = y * cellSize + cellSize / 2;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.font = '40px sans-serif';
ctx.fillText(player, xPos, yPos);

Handling User Clicks
Add an event listener to handle user clicks on the canvas. Calculate the clicked cell and make a move.
javascriptCopy code
canvas.addEventListener('click', handleCanvasClick);

function handleCanvasClick(event) {
const x = Math.floor(event.clientX / cellSize);
const y = Math.floor(event.clientY / cellSize);
makeMove(x, y);

Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
) instead.