Faking mouse events with JS to win at basketball ๐
The people at caffeina made a really fun basketball game for the browser
I beat every record using this little script I made.
The goal of the game is to make 10 perfect shoots as fast as you can. You click and drag toward the hoop to throw the ball and can shoot a maximum of 3 balls at the same time.
The first thing I did was a function that simulates any kind of mouse events, using the createEvent and dispatchEvent functions
1function simulateMouseEvent(target, options, type) {23 const event = target.ownerDocument.createEvent('MouseEvents');45 const opts = {6 type: type,7 canBubble: true,8 cancelable: true,9 view: target.ownerDocument.defaultView,10 detail: 1,11 screenX: 0,12 screenY: 0,13 clientX: 0,14 clientY: 0,15 ctrlKey: false,16 altKey: false,17 shiftKey: false,18 metaKey: false,19 button: 0,20 relatedTarget: null,21 ...options22 };2324 event.initMouseEvent(25 opts.type,26 opts.canBubble,27 opts.cancelable,28 opts.view,29 opts.detail,30 opts.screenX,31 opts.screenY,32 opts.clientX,33 opts.clientY,34 opts.ctrlKey,35 opts.altKey,36 opts.shiftKey,37 opts.metaKey,38 opts.button,39 opts.relatedTarget40 );4142 target.dispatchEvent(event);43};
Next I wrote a little function that shoots a perfect hoop using the simulateMouseEvent function. The game is listening to a drag event, but a drag is basically a click with the mousedown and mouseup events in different coordinates.
1function bBall() {2 const canvas = document.querySelector('canvas');3 const x = window.innerWidth / 2;4 const y = window.innerHeight;5 simulateMouseEvent(canvas, { clientX: x, clientY: y * 0.68 }, 'mousedown');6 simulateMouseEvent(canvas, { clientX: x, clientY: y * 0.43 }, 'mouseup');7}
Then I created a function that creates an interval of 3 perfect shoots, 3 shoots is the maximum ammount of throws that the player can make at a time.
1/**2 * Creates a sequence of ball shoots3 *4 * @param {int} mainIntervalTime Time in miliseconds for the main interval5 * @param {int} ballsNumber Number of balls to shoot each interval6 * @param {int} timeBetweenBalls time in miliseconds between shootings7 * @param {int} maxShoots max ammount of shoots to make before killing the interval8 */9function bBallSequence(mainIntervalTime, ballsNumber, timeBetweenBalls, maxShoots){10 let shootCounter = 0;11 const sequenceInterval = setInterval(() => {12 for (let i = 0; i < ballsNumber; i++) {13 setTimeout(() => {14 shootCounter ++;15 shootCounter === maxShoots ?16 clearInterval(sequenceInterval) :17 bBall();18 }, timeBetweenBalls * i);19 }20 }, mainIntervalTime);21}2223// Init ball sequence24bBallSequence(1750, 3, 200, 20);
This is the function working:
And the final results: ๐
It was really fun to make this little script. Thanks to the people of caffeina for creating such a fun game ๐.