Can anybody help me finish this program?

redcrazykid

Member
Joined
Jan 6, 2024
Messages
37
Reaction score
10
Credits
253
Code:
<html>
 <head>
  <title>NTD</title>
  <style>
BODY { font-family: Verdana; font-size: 11px; color: #000; }
  </style>
 </head>
 <body>

<script>
try {
 v2 = new Array();
 v3 = 0;
 v5 = 0;
 v10 = 0;
 function addthirdrecording(v8) {
  v9 = document.createElement('div');
  v9.style.background = '#00FF00';
  v9.style.width = '4px';
  v9.style.height = '4px';
  v9.id = '9' + document.getElementById(v8);
  v9.style.overflow = 'hidden';
  v9.style.position = 'absolute';
  v9.style.left = document.getElementById(v8).style.left;
  v9.style.top = document.getElementById(v8).style.top;
  document.body.appendChild(v9);
 }
 function createnewbox() {
  v3++;
  v1 = document.createElement('div');
  v1.style.background = '#000';
  v1.style.width = '4px';
  v1.style.height = '4px';
  v1.id = 'd' + v3;
  v1.style.overflow = 'hidden';
  v1.style.position = 'absolute';
  v1.style.left = Math.floor(Math.random() * 1000) + 'px';
  v1.style.top = Math.floor(Math.random() * 1000) + 'px';
  document.body.appendChild(v1);
 }
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 createnewbox();
 function movenewbox() {
  v5++;
  v4 = document.getElementById('d' + v5);
  if(!v4) {
   v5 = 1;
   v4 = document.getElementById('d' + v5);
  }
  v6 = (Math.floor(v4.style.top.split('px')[0]) + Math.floor(Math.random() * 2));
  v7 = (Math.floor(v4.style.left.split('px')[0]) + Math.floor(Math.random() * 2));
  v4.style.left = v7; + 'px';
  v4.style.top = v6 + 'px';
  if(v6 || v7 > 1000) {
   addthirdrecording(v4.id);
   document.body.removeChild(document.getElementById(v4.id));
   createnewbox();
  }
  setTimeout('movenewbox();', 0);
 }
 movenewbox();
}
catch(errmsg) {
 alert(errmsg);
}
</script>

 </body>
</html>


Screenshot 2024-02-09 120328.png
 


Unless anybody gets back to you beforehand - I’ll take a more detailed look at this when I get home on Sunday evening, if I have time.

It’s been a loooong while since I did any JavaScript. Like 20 years, or so. But I’ll see what I can do.

With just a quick look, there are a few improvements that I can immediately see, which could be made to the existing code.

Like where you’re calling createnewbox multiple times in a row, you could use a for loop and call createnewbox the required number of times.
E.g.
JavaScript:
for(let i = 0; i < 18; i++)
    createnewbox()

You may want to consider using an array to keep track of your boxes too.

Also, try to use meaningful variable names. I don’t know what v1, v2, v3 etc are supposed to be. I’d have to take a much closer look at your code, to determine what each variable is supposed to be for.

In order to get them to bounce off each other, you’ll need to add some collision detection, to detect when one box hits another, then you need to alter their direction of movement.

Maybe use a class for your boxes. Each box should have a width and height property, a directional vector, to store its initial direction and speed. It should also track its x,y position. Etc.

Create an array to hold your boxes in, then on each redraw, you just need to loop through your array of boxes, update the position of each box and determine if any boxes have collided. On collision, you calculate which direction they should move in next. How you do that would depend on whether you want to simulate real world physics, or just make them reverse their original direction on one axis, or both axes, or just take a random direction. You can make it as simple, or as complicated as you like. It just depends what kind of effect you’re going for.

As I said, I’ll try to take a more in depth look tomorrow evening, if I have time!
 
With the strings I have in the program, I don't think you can loop createnewbox();, because the other function is set on a timeout feature.

Plus, it's document.getElementById(ID).style.left;. With a Math.floor() function and you have to do all eight of them per execution. LIke this: I hate typing that much.

if(Math.floor(document.getElementById(ID).style.left.split('px')[0]) > object_looking_for) {
move ... object_looking_for by how much pixels;
}
And then you have to copy and paste that 8 times, and use the number -1. And so forth. Such a bitch. I was hoping you would just be like oh yeah... forgot, all that typing is a pain in the ass.
 
I'm not a JS programmer, but I took a look and there is a lot of syntax and structural errors in your code which make it quite difficult to read / interpret correctly.

I would highly suggest learning the syntax and structural basics before attempting to do more advanced tasks as it will make life far easier for you when troubleshooting your code or asking for help from others.

Not to mention, you will have far more stable code if it's written correctly in the future.
 
With the strings I have in the program, I don't think you can loop createnewbox();, because the other function is set on a timeout feature.

Plus, it's document.getElementById(ID).style.left;. With a Math.floor() function and you have to do all eight of them per execution. LIke this: I hate typing that much.

if(Math.floor(document.getElementById(ID).style.left.split('px')[0]) > object_looking_for) {
move ... object_looking_for by how much pixels;
}
And then you have to copy and paste that 8 times, and use the number -1. And so forth. Such a bitch. I was hoping you would just be like oh yeah... forgot, all that typing is a pain in the ass.
What are you talking about?
You’re already making 18 calls in a row to the createnewbox function in the main scope of your script. Calling createnewbox 18 times inside a for loop isn’t going to cause any problems. You were just saying about not wanting to type so much. A for loop there allows you to use two lines of code to call the function 18 times, instead of using 18 lines of code, to manually call the function 18 times!

Also, the timeout doesn’t come into play until your movenewbox function is actually called. And that doesn’t happen until after the 18 calls to createnewbox have been made.

In other words changing this:
JavaScript:
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();
createnewbox();

to this:
JavaScript:
for(let i =0; i<18; i++)
   createnewbox();

Is going to clean up your code a little bit.

From what I can see, all your script is doing is adding more and more boxes. They initially appear black. The bizarrely named addthirdrecording function changes the color to green. But even that looks a bit janky, because it’s adding a new green div on top of an existing black one…. Surely you just want to change the colour of an existing box to green, instead of putting a green box on top of a black one?

Again, the intention behind most of your code is not immediately clear. As it stands, it’s a jumbled mess. I’d strongly recommend re-thinking what you’re trying to do and to try to restructure and rewrite your code in a more logical fashion.

Also. use more meaningful names for your variables. v1, v2, v3 etc just do not cut it. Use variable names that describe the use of the variable.

For example:
v2 is an array - at the moment, you’re not populating it with anything. If this is going to keep track of your boxes, you could call it something more meaningful like boxes, or allboxes, or myboxes etc.

v3 appears to be a counter variable, which seems to be tracking the number of new boxes created.
Perhaps call it numberOfBoxes?

Using meaningful variable names might involve a bit more typing, but it makes your code more readable/understandable and also makes the logic/intention behind your code a lot easier to understand. Which makes it easier for others to find bugs in your code and fix it.

At the moment, only you know what you’re trying to do in your code. And you may know what v1, v2 etc mean - but other people looking at your code do not.

Personally, I’d use a class for each box object. Create a set number of boxes on the page to start with. Use an array to keep track of all of them.

After you’ve created your initial boxes, use setinterval to run a function that will run on each frame, which will iterate through the array of boxes, change the colour of any black boxes to green, update the position of each box, check for collisions with other boxes and deal with the consequences of any collisions. Etc.

I’ll make an attempt at this later this evening if I get a chance!
 
Last edited:
As I mentioned in my initial post, I haven't done any javascript for an extremely long time. So I did a bit of research into creating animations with javascript this evening, just to see what the current state of play is WRT animation using HTML5, CSS and javascript.

And looking again at what you're doing - is there any particular reason that you're adding tons of tiny divs to the page and manipulating them? Animating in this way looks like it will be extremely awkward.
The techniques you're using there are more for simple animations, moving divs and other page elements around. For example, if you want to slide images around the screen, or panels of text.

But for more complicated animation, what you're using isn't really ideal. If you're trying to create a more complex graphical animation/simulation, you might be better served using the HTML5 canvas element instead.

The HTML5 canvas element is the so-called "Flash killer". It was the reason that Adobe's much reviled Shockwave Flashplayer browser plugin could finally be laid to rest. It makes it a lot easier to create animations and games just using HTML5 and javascript.

With that, you should be able to find a much cleaner and more sane way of trying to do what you're doing.

There's a pretty decent looking canvas tutorial from Mozilla here:

Their 'Object building' tutorial might interest you too:

That one creates a bunch of randomly sized, randomly coloured balls, placed at random parts of the screen, which fly off at random angles/velocities and bounce around, changing colour when they collide with each other.

Convert the balls to squares/rectangles and you've pretty much got what you had before.

After looking at those tutorials - I'm considering having a go at porting some of my old Flash/Actionscript3 games to HTML5/javascript if I can find any surviving backups of my old source files.
 
Last edited:
I'm considering having a go at porting some of my old Flash/Actionscript3 games to HTML5/javascript if I can find any surviving backups of my old source files.

I believe there are tools, including Adobe's Canvas, that will automate this with varied degrees of success.
 
I believe there are tools, including Adobe's Canvas, that will automate this with varied degrees of success.
For the purpose of updating my JavaScript knowledge, I’ll do it manually. No need for any Adobe nonsense.

Besides, what are the chances of anything from Adobe ever running natively on Linux?!
 
Besides, what are the chances of anything from Adobe ever running natively on Linux?!

I think it happens all online, in your browser.

But, learning new JS will be fun. I did some tinkering with Java (not JavaScript) in the past.
 
I think it happens all online, in your browser.

But, learning new JS will be fun. I did some tinkering with Java (not JavaScript) in the past.
Yes, I used Java at a previous job.

I’ve also tinkered with several other Java/JVM based languages like groovy, scala, kotlin, clojure and even impractical/novelty ones like ArnoldC - where you make programs using nothing but Arnold Schwarzenegger quotes. Ha ha!

I miss my days as a flash developer though. That was a really fun time.
I’ve been meaning to revisit JavaScript for a while. But I’ve been put off by all of the huge JavaScript frameworks that have popped up in the last decade or so. This thread just renewed my interest though!
 
So when I was writing a JavaScript program to take pictures of the left side of a beer can and the front of them then measure the distance between it and the right side of the table, to direct geometry using an algorithm, I could've just used HTML5 the whole time?
 
So when I was writing a JavaScript program to take pictures of the left side of a beer can and the front of them then measure the distance between it and the right side of the table, to direct geometry using an algorithm, I could've just used HTML5 the whole time?
Technically, what I was advocating for was using the JavaScript api for the HTML5 canvas element, in order to display things in your application.

So you’re still using JavaScript for your application.
You’re just not clumsily moving a bunch of tiny divs around the page, you’re displaying graphical and geometric information in a HTML element that can deal with more complex, procedurally-generated graphics and animations/simulations.

If you break your application down properly and use a more object oriented approach, using classes, the canvas API gives you a much more elegant way of scripting complex graphics and animations than the approach you were originally using.
 
Last edited:
Here's how to draw a triangle in JavaScript.

Code:
<html>
 <head>
  <title>NTD</title>
  <style>
BODY { font-family: Verdana; font-size: 11px; color: #000; }
  </style>
 </head>
 <body>

<input type="text" size="32" id="in2" value="triangle" /> <input type="submit" value="Submit" onclick="drawstuff();" />

<script>
try {
offst = 300;
function creatediv(b, c) {
 a = document.createElement('div');
 a.style.position = 'absolute';
 a.style.width = '1px';
 a.style.height = '1px';
 a.style.left = b + 'px';
 a.style.top = c + 'px';
 a.style.background = '#000';
 a.style.innerHTML = '&nbsp;';
 a.style.overflow = 'hidden';
 document.body.appendChild(a);
}
in2 = document.getElementById('in2');
function drawstuff() {
 if(in2.value.toLowerCase() == 'triangle') {
  for(d = 1;d < 100;d++) {
   setTimeout('creatediv(' + offst + ', ' + (d + offst) + ');', 0);
   for(h = 1;h < 100;h++) {
    setTimeout('creatediv(' + (h + offst) + ', ' + offst + ');', 0);
   }
    for(g = 1;g < 100;g++) {
     setTimeout('creatediv(' + ((g + offst) * 2) + ', ' + offst + ');', 100);
     setTimeout('creatediv(' + offst + ', ' + (g + offst) + ');', 100);
    }
  }
 }
}
}
catch(errmsg) {
 alert(errmsg);
}
</script>

 </body>
</html>

Also... htat' an HTML file.
 
I didn't say your original code wasn't working - You were asking about animation and collision detection. I just stated that it was difficult to work out what you were trying to do in your code because it was badly written. As in it was badly organised, with bad variable names and with questionable logic.

To alter your code, to animate each of the boxes and perform collision detection on them would be extremely tricky with your original code. I haven't done any javascript for a long while, so I looked into Javascript/html5 animation and I recommended re-writing your code to use the HTML5 Canvas element and it's corresponding javascript API. I also posted some links to some tutorials using the canvas element. One of which would have given you a good starting point for re-creating your original animation.

Incidentally - I've just put the above code into a html file and ran it in firefox and I see two sides of the triangle on the page, but the hypotenuse for the triangle is appearing as a horizontal dotted line drawn some distance away from the two sides of the triangle. It's NOT connecting the other two sides of the triangle. So it could be argued that your code isn't exactly working.

Also - you're still using meaningless variable names like a,b,c,d etc and you’re using individual 1 pixel divs to draw with.

To clarify - this is what I see when I run the HTML page with your most recent script (I'm using Firefox BTW):
Triangle_RC.png


Now here's my simple attempt at drawing a randomly coloured triangle, using the HTML5 Canvas element:
HTML:
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <script type="text/JavaScript">
function main() {
   // Get the canvas element from the page and its drawing/device context:
    var canvas = document.getElementById('canvas');
    if(canvas.getContext) {
        var ctx = canvas.getContext('2d');
        // Use the centre of the stage for the start position
        var xPos = Math.floor(canvas.width/2);
        var yPos=Math.floor(canvas.height/2);
        // Size of the triangle
        var size=100;

        // function to generate random number within a range
        function random(min,max) {
          const num = Math.floor(Math.random()*(max-min)) + min;
          return num;
        };

        // function to generate a random RGB color value
        function randomRGB() {
          return `rgb(${random(0, 255)},${random(0, 255)},${random(0, 255)})`;
        }

        // Draw a randomly coloured triangle, roughly centred over the centre of the stage
        ctx.fillStyle = randomRGB();
        var path = new Path2D();
        path.moveTo(xPos + size, yPos+Math.floor(size/2));
        path.lineTo(xPos, yPos - Math.floor(size/2));
        path.lineTo(xPos - size, yPos+Math.floor(size/2));
        path.lineTo(xPos + size, yPos+Math.floor(size/2));
        ctx.fill(path);
    }
}
        </script>
        <style>canvas{
            width: 400px; height: 400px; border: 5px solid blue;
        }
        </style>
    </head>
    <body onLoad="main();">
        <div align="center">
            <canvas id="canvas"/>
        </div>
    </body>
</html>

NOTE: I've de-indented the actual Javascript part of the page, to fit more of the code into the code-box. generated by the code tags.

In the above:
  • The first thing to do is ensure we can find the Canvas element and get its drawing/device context.
  • Then I've declared a couple of functions. random() generates a pseudo random number within a given range, randomRGB generates a random RGB colour, using the random() function.
  • I've set up some variables.
xPos is the initial x position of the triangle. Set to half the width of the stage.
yPos is the initial y position of the triangle. Set to half the height of the stage.
size is the size of the triangle. Set to 100.

- I create a path to hold the geometry for the triangle and I use the drawing context to draw and fill the triangle.
For the triangles points, I've used a bit of simple maths to ensure that the triangle is roughly centred around the initial x,y position. I probably didn't need to add the final point, but that was to ensure that the shape was properly closed. if we wanted to stroke the path as an outline, we wouldn't get a complete outline if we didn't add the final point to the path.


Which yields this:
triangle_Canvas.png


With the above code, I could easily expand on it, to create a Triangle class that could take an initial x,y position, a size and a colour. That would encapsulate the creation and drawing of a Triangle.
Allowing me to easily create multiple Triangles on the screen.

Once I've got a Triangle class I could even expand further, to assign additional properties to each Triangle, like an initial x,y velocity - to allow it to be animated to move around the screen. I could add code for collision deteection, to check for collisions with the boundaries of the canvas, or with other Triangles. I could even add other properties like mass, density, gravity and then animate using simple physics simulations via basic Trigonometry and various physics equations and easing algorithms.. Either by manually adding them, or by using a third party javascript library.

Once again, try using the HTML Canvas element and its Javascript API.
 
Last edited:
Adding a triangle class:
HTML:
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <script type="text/JavaScript">
function main() {
    var canvas = document.getElementById('canvas');
    if(canvas.getContext) {
        var ctx = canvas.getContext('2d');
        var stageWidth=canvas.width;
        var stageHeight=canvas.height;

        // function to generate random number within a range
        function random(min,max) {
          const num = Math.floor(Math.random()*(max-min)) + min;
          return num;
        };

        // function to generate random RGB color value
        function randomRGB() {
          return `rgb(${random(0, 255)},${random(0, 255)},${random(0, 255)})`;
        }

        // Shape class
        class Shape {
          constructor(x, y) {
            this.x = x;
            this.y = y;
          }
        }

        // Triangle class
        class Triangle extends Shape {
          constructor(x, y, fillColour, outlineColour, size, outlineWidth) {
            super(x, y);

            this.fillColour = fillColour;
            this.outlineColour = outlineColour;
            this.size = size;
            this.outlineWidth = outlineWidth;
            this.exists = true;
          }

          draw() {
            ctx.beginPath();
            ctx.fillStyle = this.fillColour;
            var path = new Path2D();
            path.moveTo(this.x + this.size, this.y + Math.floor(this.size / 2));
            path.lineTo(this.x, this.y - Math.floor(this.size / 2));
            path.lineTo(this.x - this.size, this.y + Math.floor(this.size / 2));
            path.lineTo(this.x + this.size, this.y + Math.floor(this.size / 2));
            ctx.fill(path);
            ctx.strokeStyle = this.outlineColour;
            ctx.lineWidth = this.outlineWidth;
            ctx.stroke(path);
          }

        }

        // Draw a randomly coloured, equilateral triangle in the centre of the stage
        var triangle = new Triangle(Math.floor(stageWidth/2), Math.floor(stageHeight/2), randomRGB(), randomRGB(), 100, 3);
        triangle.draw();
    }
}
        </script>
        <style>canvas{
            width: 400px; height: 400px; border: 5px solid blue;
        }
        </style>
    </head>
    <body onLoad="main();">
        <div align="center">
            <canvas id="canvas"/>
        </div>
    </body>
</html>

Now we have a basic Triangle class, derived from a Shape class.
So now all we have to do is create a new Triangle and then call its draw function.
We're using the middle of the stage/Canvas as the x,y for the triangle, We're using random colours for the fill colour and the stroke colour, we have a size of 100 and a width of 3px for the outline.
I've added an outline colour and an stroke-width for the outline.
So now we get a randomly coloured triangle, with a randomly coloured outline.

Yielding this:
triangle_Canvas2.png



The Shape class is a base-class that can hold generic data for all derived shapes. Perhaps I aught to move some of the colour related properties of Triangle into the base class. Because other shapes will almost certainly have an outline a fill colour and a stroke-width.

The Shape class can now act as a common base for creating classes for other shapes - Rectangles/Squares, Circles, or any other shapes that you might want to add.

So the next step may be to add some extra shape-types, or consider adding some animation.
So perhaps the next iteration could create a bunch of smaller triangles, or other shapes and move them around the screen?! Perhaps with some collision detection?!

The code is getting quite big now, so we could even consider putting certain elements into their own separate javascript files. Doing this makes things more modular and allows you to re-use things that you've already created on other pages. So for the next iteration, I'll probably put the Shape class in it's own file, the Triangle class in it's own file, perhaps even the main script.

Organising the code in this way makes it easier to build upon what you already have. And as I've already mentioned, it makes it easier to re-use javascript code that you've already written.

I guess we'll see where this goes?!
 
Last edited:
Dude yer awseome, but how long did it take that program to run?

Also so can you rotate the triangle?
 

Members online


Top