Dota 2 DPS Calculator with Alpine

As promised, today I will show you how to create Alpine.js Dota 2 DPS Calculator. I’m a fan of Dota 2, but I’m noob. That’s why I want to improve by making DPS (Damage per Second) Calculator. Basically damage is (# of attack per second) * (damage per hit). However in Dota, the game doesn’t show you the total damage. They show you base damage + bonus damage. Why do they do it that way? Who knows. It has some implication in mechanics like double damage, but let’s not talk about the game.

I want my site to be usable from mobile phone. I can’t just use HTML input tag and hope that my phone supports numeric input (my phone doesn’t btw). So let’s make numpad on the web app itself.

Demo App

The app can be seen on https://priv.softwarejourney.my.id/dota2-custom/index.html. Please take a look on the source code as well while reading my explanation. The app consists of 3 part as usual. HTML, JS, and CSS. I won’t explain the CSS in this article.

HTML Part

The only new thing used here is we utilize x-for with template tag to generate the button 1, button 2, until button 9. This really reduces copy pasting similar code for each buttons for the numpad.

Javascript Part

Instead of defining data as string inside x-data, this time I decided to put it in javascript file for better editor support. You define the data with Alpine.data method. However, it is only defined after some initialization. To be sure it already existed, you should call it on alpine:init window event. Notice the dps field is a computed property here which is computed everytime the field changes.

I implemented focus by using selectedInput field. When an input is focused, I put red border on it. Once an input is focused, I can start using the numpad. It supports decimal number. To implement delete button, I have to be creative and use number outside of 0 to 9. Here I choose 10 for delete button, but I render it as Del.

The selectedInput will affect getCurrentVal and setCurrentVal which is used when inputNumber method is called. Once we know which field to operate on, handling the number input is relatively straightforward. For regular number, just append the last digit to the back of the number. For delete operation, we just remove the last digit (rightmost). The math can be seen on the code.

Conclusion

It’s super easy to build a Dota 2 DPS Calculator which can be used on phone. The app is:

  1. Lightweight
  2. Respond without need to press calculate button

All of this with 48 LoC for HTML and 43 LoC for Javascript.

I hope seeing is believing, and wish you have a great time using Alpine to sprinkle interacvity to your website.

Related
Alpine