CodeHS Guide

9.7.4 Leash CodeHS Answers: Complete Step-by-Step Guide for Students

📚 Unit 9 — Animation & Games ⏱ 10 min read 🎯 JavaScript + OOP Versions Covered
If you're stuck on 9.7.4 leash codehs answers, you're not alone. This is one of the trickier exercises in Unit 9. Most students get confused by the mouse event logic or the object relationship setup. This guide walks you through both versions of the exercise — step by step. You'll understand the code, not just copy it.

Table of Contents

  1. What Is the 9.7.4 Leash Exercise?
  2. Core Concepts You Need First
  3. Two Versions of the Leash Exercise
  4. Walkthrough: JavaScript Mouse Leash
  5. Walkthrough: OOP Class-Based Leash
  6. 7 Common Mistakes and Fixes
  7. How to Debug Your Program
  8. Real-World Uses of This Concept
  9. Tips for the Animation Unit
  10. LSI Keywords Reference
  11. FAQs
  12. Conclusion

What Is the 9.7.4 Leash Exercise in CodeHS?

Overview of the CodeHS Platform

CodeHS is a browser-based computer science platform used by middle and high school students across the US. Teachers assign exercises, and students write and run code directly in the browser.

Where Lesson 9.7.4 Falls in the Curriculum

Lesson 9.7 is part of the Animation and Games unit. It builds on what students learned in earlier lessons about shapes, timers, and event handlers. Lesson 9.7.4 specifically is about creating a "leash" — a tether between two objects.

Think of it as the capstone skill for object movement. If you can do this, you can build basic games with followers, companions, or camera tracking.

What Is the "Leash" Concept in Programming?

Imagine a dog on a leash. The dog follows the owner, but only as far as the leash allows. In code, this works the same way.

The follower checks its distance from the leader on every update. If it's too far, it moves closer. That's the whole mechanic.

Understanding the Core Concepts Behind 9.7.4 Leash CodeHS

Coordinate Systems and the Canvas

The CodeHS canvas is a grid. Every object has an X position (left to right) and a Y position (top to bottom). Unlike math class, Y increases downward — not upward.

Mouse Events and Real-Time Interaction

CodeHS lets your program respond every time the mouse moves. This is called event-driven programming. The key method is mouseMoveMethod().

// Example: register the mouse move handler
setMouseMoveMethod(mouseMove);

function mouseMove(e) {
    var mouseX = e.getX();
    var mouseY = e.getY();
    // update object position here
}

Object Methods and Object-Oriented Thinking

Every shape in CodeHS is an object with built-in methods. Two of the most important ones for this exercise are:

MethodWhat It DoesCommon Mistake
getCenter()Returns a Point at the center of the shapeConfusing it with getX()/getY()
setPosition(x, y)Moves the object to new coordinatesPassing wrong coordinate type
add(object)Puts a shape onto the canvasForgetting to call it after clearing
removeAll()Clears everything from the canvasNot re-adding objects after clearing
Important: getCenter() returns a Point object, not a number. To get the X value from it, you call center.x, not just center.

Distance Logic and the Leash Constraint

The core math in this exercise is the distance formula. It comes from the Pythagorean theorem and tells you how far apart two points are.

// Distance between two points
var dx = x2 - x1;
var dy = y2 - y1;
var distance = Math.sqrt(dx * dx + dy * dy);

Once you have the distance, you use an if statement: if the distance is greater than your leash length (say, 100 pixels), move the follower toward the leader.

Loops and Continuous Position Updates

A single position update only moves the object once. For smooth animation, you need the code to run repeatedly.

The Two Main Versions of 9.7.4 Leash in CodeHS

Depending on your specific CodeHS course, this exercise appears in two forms. Read your assignment carefully to know which one you have.

JavaScript Version

Mouse-Tracking Leash

  • Ball or circle follows your mouse
  • A line (the "leash") connects them
  • Uses mouse events, drawLine(), removeAll()
  • Common in JavaScript Graphics courses
OOP / Java Version

Class-Based Leash

  • You create a Dog class and a Leash class
  • The leash holds a reference to the dog object
  • No canvas — just constructors and methods
  • Common in Java / AP CS courses
Not sure which version? If your exercise shows a canvas with shapes, it's the JavaScript version. If the task mentions creating two classes, it's the OOP version.

Step-by-Step Walkthrough — JavaScript Mouse Leash Version

STEP 1

Set Up Your Canvas and Objects

First, create a circle. Give it a radius, color, and starting position. Then add it to the canvas.

var ball = new Circle(20);
ball.setColor(Color.red);
ball.setPosition(200, 200);
add(ball);
STEP 2

Decide on Fixed vs. Dynamic Points

You need two endpoints for the leash line. In most versions of this exercise, one end is the ball and the other is the mouse cursor.

Most 9.7.4 assignments use a dynamic mouse end and a ball that follows it.

STEP 3

Write the mouseMoveMethod Handler

Register your mouse move function. Inside it, get the mouse position and move the ball there.

setMouseMoveMethod(mouseMove);

function mouseMove(e) {
    var mouseX = e.getX();
    var mouseY = e.getY();
    ball.setPosition(mouseX - ball.getRadius(), mouseY - ball.getRadius());
}

The - ball.getRadius() offset centers the ball on the cursor instead of placing the corner at the cursor.

STEP 4

Draw the Leash Line

Use drawLine() or a Line object to draw the tether. You need the ball's center and the anchor point.

function mouseMove(e) {
    var mouseX = e.getX();
    var mouseY = e.getY();

    removeAll();

    // Re-draw ball
    ball.setPosition(mouseX - ball.getRadius(), mouseY - ball.getRadius());
    add(ball);

    // Draw leash line from canvas center to ball center
    var center = ball.getCenter();
    var line = new Line(200, 200, center.x, center.y);
    line.setColor(Color.gray);
    add(line);
}
STEP 5

Clear the Canvas on Each Update

Every time the mouse moves, you need to erase the old drawing and redraw everything. This is done with removeAll().

STEP 6

Test and Verify Your Output

Run your code and check these things:

Step-by-Step Walkthrough — Object-Oriented / Class-Based Leash Version

STEP 1

Create the Dog Class

Your Dog class needs a constructor with two parameters: name and breed. Store them as instance variables using this.

class Dog {
    constructor(name, breed) {
        this.name = name;
        this.breed = breed;
    }

    getInfo() {
        return this.name + " is a " + this.breed;
    }
}
STEP 2

Create the Leash Class

The Leash class holds a reference to a Dog object. This is different from storing a simple string or number — you're storing a full object.

class Leash {
    constructor(dog) {
        this.dog = dog;
    }

    getDogInfo() {
        return this.dog.getInfo();
    }
}
STEP 3

Connect Dog and Leash in Main

In your main program, create a Dog first. Then pass it into the Leash constructor.

// Main program
var myDog = new Dog("Max", "Labrador");
var myLeash = new Leash(myDog);

// Access dog info through the leash
println(myLeash.getDogInfo());
// Output: Max is a Labrador
STEP 4

Verify Object Relationships Work

Add a println() call to check that the leash correctly returns the dog's info. The data should flow: Leash → Dog → getInfo().

7 Common Mistakes and How to Fix Them

#MistakeWhat HappensFix
1 Not calling removeAll() Old lines stay on canvas — trail effect Always call removeAll() before redrawing
2 Using getX() instead of getCenter().x Line connects to wrong point Use getCenter() then access .x and .y
3 Not registering the mouse handler Nothing happens on mouse move Call setMouseMoveMethod(yourFunction)
4 Ball jumps to cursor instantly No smooth leash feel Add a distance check — only move if distance > threshold
5 Follower never stops moving Overshoots and jitters Check your distance condition and threshold value
6 Forgetting this. in class constructor Instance variables are lost immediately Write this.name = name, not just name = name
7 Dog info not showing through Leash Undefined or empty output Check that the Dog object is stored in this.dog and that you call its method correctly

How to Debug Your 9.7.4 Leash CodeHS Program

Use console.log() to Track Coordinates

When your object isn't moving right, print the coordinates to check what's happening.

function mouseMove(e) {
    console.log("Mouse X: " + e.getX() + " | Mouse Y: " + e.getY());
    // Check if values update on each move
}

Visual Debugging Tips

Reading CodeHS Error Messages

Two errors come up most often in this exercise:

Real-World Applications of the Leash Concept

🎮
Game Development

NPC companions that follow the player character in RPGs like Stardew Valley use the exact same distance-check logic.

📷
Camera Systems

2D game cameras that smoothly follow a character use interpolation — a more advanced version of this exercise.

🖥️
UI/UX Design

Drag-and-connect node editors (like in Figma or Blender) use line-following logic to draw connections between elements.

🤖
Robotics

Follower robots use distance sensors and the same leader-follower logic to stay within range of a target robot.

🎬
Animation Software

Bone rigs in animation tools use tethered motion — child bones follow parent bones using distance and angle constraints.

Tips for Succeeding in the CodeHS Animation & Games Unit

How to Approach Any CodeHS Exercise Without Copy-Pasting

How to Build Logical Thinking for Future Units

The leash exercise teaches a thinking pattern you'll use constantly in computer science:

  1. Check — measure the current state (distance, score, health)
  2. Decide — use if/else to determine what should happen
  3. Update — change the state based on your decision
  4. Repeat — run this loop continuously

Recognize this pattern in every future exercise. It will save you hours.

Resources Beyond CodeHS

Frequently Asked Questions

What is the 9.7.4 Leash exercise in CodeHS?
It's a programming assignment in Unit 9 that teaches students how one object follows another on a canvas using mouse events. There's also an OOP version where you create a Dog class and a Leash class with object references.
Is the 9.7.4 Leash exercise JavaScript or Java?
It appears in both. The JavaScript version uses a canvas and mouse events. The Java/OOP version involves creating two classes with constructors and instance variables. Check which course you're in to confirm which version applies.
How does the leash mechanic work in CodeHS?
The code continuously checks the distance between a leader (the mouse) and a follower (the ball). When the distance exceeds a set threshold, the follower moves toward the leader. This simulates a physical tether in code.
Why is my leash leaving trails on the canvas?
You're not calling removeAll() before redrawing. Every mouse move handler must clear the canvas first, then re-draw all objects and the leash line from scratch. Skipping this leaves old drawings behind.
What does getCenter() return in CodeHS?
It returns a Point object with two properties: .x and .y. These represent the center of the shape, not the top-left corner. This is important for accurate line drawing.
What programming concepts does 9.7.4 Leash teach?
Mouse event handling, canvas coordinate systems, object methods, distance calculation using the Pythagorean theorem, conditional logic, and continuous animation loops. For the OOP version: constructors, instance variables, and object references.
What happens if I forget this. in my class constructor?
Without this., the variable is created as a local variable inside the constructor. It disappears as soon as the constructor finishes. The object will have no stored data, and any method trying to access it will get undefined.
How do I calculate distance between two objects in CodeHS?
Use Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)). This is the standard distance formula based on the Pythagorean theorem. It gives you the straight-line distance in pixels between two canvas points.
Can I look up CodeHS 9.7.4 leash answers online?
You can find walkthroughs and explanations — like this one — to understand the logic. Copying full code without understanding it will hurt you on later assignments, since Unit 9 builds toward more complex exercises.
What unit is 9.7.4 Leash part of in CodeHS?
It's part of Unit 9 — Animation and Games — in the CodeHS JavaScript curriculum. It builds on Lessons 9.1 through 9.6, which cover graphics objects, timers, and basic event handling.

Conclusion: 9.7.4 leash codehs answers

The 9.7.4 leash codehs exercise teaches a real programming pattern — check, decide, update, repeat. Whether you're doing the JavaScript mouse version or the OOP class version, the core idea is the same: one object follows another, constrained by distance logic.

Don't just copy the code. Understand it. Close this page, open CodeHS, and write it yourself — one line at a time. That's how you build skills that actually last.