Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Ranzear
Jul 25, 2013

Lumpy posted:

Calculate all future steps and put them in an array so you can time travel through them with BLAZING FAST PERFORMANCE.

No, wait, that's a terrible idea. OR IS IT???

Something I never got around to with SuperTanks.

Deterministic simulations are awesome though.

This was cribbed and heavily improved from some now dead site, but I wayback machine'd it and found some other cool stuff apparently by the same guy, just not the original tank simulation (it tries, but the tank.js is gone):

https://web.archive.org/web/20150517214008/http://matt.stumpnet.net/tanx.html
https://web.archive.org/web/20150907131835/http://matt.stumpnet.net/hexdb.html

Ranzear fucked around with this message at 22:16 on Mar 6, 2018

Adbot
ADBOT LOVES YOU

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

Ranzear posted:

Something I never got around to with SuperTanks.

Deterministic simulations are awesome though.

This was cribbed and heavily improved from some now dead site, but I wayback machine'd it and found some other cool stuff apparently by the same guy, just not the original tank simulation (it tries, but the tank.js is gone):

https://web.archive.org/web/20150517214008/http://matt.stumpnet.net/tanx.html
https://web.archive.org/web/20150907131835/http://matt.stumpnet.net/hexdb.html

Ha! That's my stuff. New links here:
http://www.mseymour.ca/tanks.html
http://www.mseymour.ca/tanx.html
http://www.mseymour.ca/hexdb.html

Edit: Also I like what you've done with tanks.js, the debris looks cool

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
Double buffering is the right answer

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.
So here is a weird one guys.

You can use a string in a for...in loop. I learned this today. I also learned you can acceess a specific part of a string but treating it like an array. However the weird loving thing is, when you do this:

code:
let x = 'foo';
for(const index in foo) {
   console.log(typeof index);
}
The index is a string of numbers, specifically if you cosnole log index out during hte loop you would see: '0', '1', '2'

... what the gently caress?

PleasureKevin
Jan 2, 2011

Is it possible to steal some React components that are on a site's window element? They have their UI components on like window.somethingawful.GUI. So for example this works in the console.

code:
const target = document.getElementsByClassName('aol-pranks')

window.somethingawful.ReactDOM.render(
  window.somethingawful.React.createElement(window.somethingawful.GUI.Button, { children: 'THINGS HAVE SURE CHANGED SINCE 9/11' }),
  target
)
I've been looking around in the source code for where these components are attached to the window object, but I'm pretty sure 99% of this minified confetti code is for placing ads and mining a cryptocurrency made by inflation fetishists (you try tell them it's a bubble and they get visibly turned on).

Anyhow, any hints on how I can jack this React UI library they got and use it in my own code? It's not actually to steal their intellectual property or make a phishing site. Thank you.

geeves
Sep 16, 2004

Knifegrab posted:

So here is a weird one guys.

You can use a string in a for...in loop. I learned this today. I also learned you can acceess a specific part of a string but treating it like an array. However the weird loving thing is, when you do this:

code:
let x = 'foo';
for(const index in foo) {
   console.log(typeof index);
}
The index is a string of numbers, specifically if you cosnole log index out during hte loop you would see: '0', '1', '2'

... what the gently caress?

A String is "technically" an array of chars. So index would be the char position.

Are you perhaps trying to do this:

code:

let x = 'foo';
for(const index in x) { // not foo
   console.log(typeof index);
   console.log(index);
   console.log(x[parseInt(index, 10)]);
}
console.log(typeof index);

Prints "string" because it is

console.log(index)

Prints 0, 1, 2

console.log(x[parseInt(index, 10)]);

Prints "f", "o", "o"

https://jsfiddle.net/3vupnvko/14/

geeves fucked around with this message at 07:19 on Mar 7, 2018

Suspicious Dish
Sep 24, 2011

2020 is the year of linux on the desktop, bro
Fun Shoe

Knifegrab posted:

So here is a weird one guys.

You can use a string in a for...in loop. I learned this today. I also learned you can acceess a specific part of a string but treating it like an array. However the weird loving thing is, when you do this:

code:
let x = 'foo';
for(const index in foo) {
   console.log(typeof index);
}
The index is a string of numbers, specifically if you cosnole log index out during hte loop you would see: '0', '1', '2'

... what the gently caress?

The [] syntax in JavaScript accesses an object's properties by string. This is true for all objects, including arrays, which have special properties with names "0", "1", "2", etc. for each element they contain. Strings act the same way.

code:
>> Object.keys(["a", "b", "c", "d"])
Array(4) [ "0", "1", "2", "3" ]
For those wondering, no, this isn't slow. All JavaScript runtimes ever built, including the historic Netscape-era interpreter, have fast paths where the index is kept an integer and never converted to a string. But according to the spec, you are accessing a property by name, not by integer.

Happy Thread
Jul 10, 2005

by Fluffdaddy
Plaster Town Cop
Wouldn't a for...of loop rather than a for...in loop be the easiest way to iterate through a string's characters?

Knifegrab
Jul 30, 2014

Gadzooks! I'm terrified of this little child who is going to stab me with a knife. I must wrest the knife away from his control and therefore gain the upperhand.

Dumb Lowtax posted:

Wouldn't a for...of loop rather than a for...in loop be the easiest way to iterate through a string's characters?

It would. I was using this to eliminate uniques. I guess I am just suprised the index is a string and not just numbers.

But I suppose its always strings for keys in Objects.

Knifegrab fucked around with this message at 09:43 on Mar 7, 2018

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



PleasureKevin posted:

Anyhow, any hints on how I can jack this React UI library they got and use it in my own code? It's not actually to steal their intellectual property or make a phishing site. Thank you.

Browser debuggers will pretty-print minified code to make it easier to read. Chrome's has a button that looks like { } (under Sources) and you can just copy+paste that out and save it. From there, you have to be good at inferring what's going on based on context and the strings and properties that can't be minified to single letters.

HappyHippo posted:

Ha! That's my stuff. New links here:
http://www.mseymour.ca/tanks.html
http://www.mseymour.ca/tanx.html
http://www.mseymour.ca/hexdb.html

Edit: Also I like what you've done with tanks.js, the debris looks cool

Oh good these aren't gone forever! I do have a copy of tanks somewhere I was rewriting as an experiment but tanx is gr8

Ranzear
Jul 25, 2013

HappyHippo posted:

Ha! That's my stuff. [...]

Edit: Also I like what you've done with tanks.js, the debris looks cool

I think it was the xkcd IRC channel that showed me matt.stumpnet.net way back. Abusing your code taught me a lot.

I can't even really list what all I did from Tanks into SuperTanks because it was over the course of like ... eight years:

Collision
    Everything has radial collision and I think there's also ramming damage.

Seeded RNG
    Encodes field size into the seed, so almost perfectly deterministic.

Drop shadows
    Just a CSS drop shadow, but then a bunch of small drawing changes and selective use of it makes a huge difference. Alters the offset to give 'height' to debris and artillery shots.

Stereo sound
    Back when the Audio object would redownload sounds each play, the solution was to base64 encode them and embed them directly into the page. I made stereo sound by having left channel and right channel of each sound separately and panning is just playing both at inverse volumes.

Expansion bases, Factories, Airfields
    Expansion bases have less production rate, and production rate is also affected by number of producers in general. Factories spawn bigger tanks, Airfields spawn planes. Most spawns also temporarily raise the spawn rate of their 'counter', so lots of planes surviving in the air prompts more air defenses.

Fake 3D debris
    These are still my favorite 2D trick, because they're just a single line being varied sinusoidally in width and length to make a 'flipping rectangle' look. I plan to reuse this in Godot's particle systems to do some really cool debris butts.

Smoke changes
    Smoke can cast shadows, is generated by explosions, and also does the visible shockwave on large explosions.

Heavily improved AI
    Tanks have vision range and don't automatically know of threats when friendlies are hit by them, they just drive in that direction until they find a target. Tanks also 'spot' targets whenever they shoot at them, letting those with longer range than sight find a target.

Bomber nerfs, also Scale = Mutation
    All the planes use the same drawing calls, they just mutate in shape as their base scale changes. I understood this to be a rudimentary shape key later on. Planes also have a 'munitions' system so much go back to an airfield to rearm ... or crash if they don't have one. Added interceptors and CAS planes too.

Veteran/Combat pips
    Stat improvements for tanks/planes that have either survived a long time or make lots of kills. Inherited on kill too. Usually leads to Macross Missile Swarms.

Damage effect texture
    I think this was the last major thing I added. It's a texture that gets applied in successive stages of damage, but it was really laggy to do constantly so only updates periodically. I think it came with prerendering tanks on a second canvas to be able to apply the texture and then storing the result for reuse, much how https://caliber.online does everything.

Nuclear Proliferation
    :v: The nuclear flash is actually just a recolored smoke particle. Every nuclear bomber that spawns raises the chance of more nuclear bombers temporarily, and every nuke launched raises that chance permanently.

Ranzear fucked around with this message at 21:24 on Mar 7, 2018

HappyHippo
Nov 19, 2003
Do you have an Air Miles Card?

Munkeymon posted:

Oh good these aren't gone forever! I do have a copy of tanks somewhere I was rewriting as an experiment but tanx is gr8

Thanks! This is what I get for hosting stuff on my friend's domain

Ranzear posted:

I think it was the xkcd IRC channel that showed me matt.stumpnet.net way back. Abusing your code taught me a lot.

I can't even really list what all I did from Tanks into SuperTanks because it was over the course of like ... eight years:

...

That's an impressive list of mods
Seems people really like to play around with it. I've seen a few other mods

Ranzear
Jul 25, 2013

Oh, and it also taught me the value of broadphase :eng101:

Dominoes
Sep 20, 2007

Hey dudes. Dove back into an old webapp project that uses React. When I first set it up, I was learning React; looking for feedback on these two styles of component hierarchy I've been using:


A: Store state in the top-level component, which is class-based as 'this.state'. All state modification is done from methods in this component, that you tie in with this.fname = fname.bind(this) boilerplate. Pass relevant state values and these functions to components, down the chain.

+: Simple for small projects; component input+output is entirely handled by arguments, so no side effects.
- Argument (prop?) lists and subcomponent calls become long and repetative, especially when using Typescripts {arg1, arg2}: {arg1: Type1, arg2: Type1} syntax.

B: Use React-Redux. Everything is a functional component. Comps ref and modify the state on their own without passing args up and down.

+: Avoids argument hell. Seems like the better approach for all but the simplest pages.
- A bit more set up; state can be mofied from any component instead of centralized.

Dominoes fucked around with this message at 16:33 on Mar 13, 2018

Ahz
Jun 17, 2001
PUT MY CART BACK? I'M BETTER THAN THAT AND YOU! WHERE IS MY BUTLER?!

Dominoes posted:

Hey dudes. Dove back into an old webapp project that uses React. When I first set it up, I was learning React; looking for feedback on these two styles of component hierarchy I've been using:


A: Store state in the top-level component, which is class-based as 'this.state'. All state modification is done from methods in this component, that you tie in with ] this.fname = fname.bind(this) boilerplate. Pass relevant state values and these functions to components, down the chain.

+: Simple for small projects; component input+output is entirely handled by arguments, so no side effects.
- Argument (prop?) lists and subcomponent calls become long and repetative, especially when using Typescripts {arg1, arg2}: {arg1: Type1, arg2: Type1} syntax.

B: Use React-Redux. Everything is a functional component. Methods ref and modify the state on their own without passing args up and down.

+: Avoids argument hell. Seems like the better approach for all but the simplest pages.
- A bit more set up; state can be mofied from any component instead of centralized.

I think the Redux way is one of those things that while a bit of work upfront, it's pretty easy to get into the flow as you go and pays for itself quite easily on your initial project and future projects are all gravy with your gained knowledge and pre-existing patterns.

I think a hybrid approach is pretty reasonable where you decide on how tightly coupled your data is to certain components and which data is more global in nature. Basically important poo poo goes in the redux store and checkboxes sit in component state.

Roadie
Jun 30, 2013

Dominoes posted:

Hey dudes. Dove back into an old webapp project that uses React. When I first set it up, I was learning React; looking for feedback on these two styles of component hierarchy I've been using:


A: Store state in the top-level component, which is class-based as 'this.state'. All state modification is done from methods in this component, that you tie in with this.fname = fname.bind(this) boilerplate. Pass relevant state values and these functions to components, down the chain.

+: Simple for small projects; component input+output is entirely handled by arguments, so no side effects.
- Argument (prop?) lists and subcomponent calls become long and repetative, especially when using Typescripts {arg1, arg2}: {arg1: Type1, arg2: Type1} syntax.

B: Use React-Redux. Everything is a functional component. Comps ref and modify the state on their own without passing args up and down.

+: Avoids argument hell. Seems like the better approach for all but the simplest pages.
- A bit more set up; state can be mofied from any component instead of centralized.

Also, C: wait for the new React context to be ready (in 16.3) and use that for data passed down to subcomponents that doesn't matter for intermediate components.

PleasureKevin
Jan 2, 2011

Roadie posted:

Also, C: wait for the new React context to be ready (in 16.3) and use that for data passed down to subcomponents that doesn't matter for intermediate components.

if this is a think it will change my life.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

PleasureKevin posted:

if this is a think it will change my life.

It may be a think: https://medium.com/@baphemot/whats-new-in-react-16-3-d2c9b7b6193b

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

From the Coding Horrors thread:

https://github.com/auchenberg/volkswagen

quote:

If you want your software to be adopted by Americans, good tests scores from the CI server are very important. Volkswagen uses a defeat device to detect when it's being tested in a CI server and will automatically reduce errors to an acceptable level for the tests to pass. This will allow you to spend less time worrying about testing and more time enjoying the good life as a trustful software developer.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

Having just finished that episode of Dirty Money the other day, I approve of this cross post.

Capri Sun Tzu
Oct 24, 2017

by Reene

Thermopyle posted:

From the Coding Horrors thread:

https://github.com/auchenberg/volkswagen

quote:

If you want your software to be adopted by Americans, good tests scores from the CI server are very important. Volkswagen uses a defeat device to detect when it's being tested in a CI server and will automatically reduce errors to an acceptable level for the tests to pass. This will allow you to spend less time worrying about testing and more time enjoying the good life as a trustful software developer.
Nothing says "trustful software developer" like cheating on your tests

qsvui
Aug 23, 2003
some crazy thing

Capri Sun Tzu posted:

Nothing says "trustful software developer" like cheating on your tests

:thejoke:

mystes
May 31, 2006

I guess they're hoping VW will be too embarrassed to send a cease and desist notice?

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


More that they'll listen to their lawyers when they say it'd be a bad idea to do that.

huhu
Feb 24, 2006
I've got two dropdowns I'm building from API data for a React component.

code:
    const CategoryItems = Object.values(categories).sort((a,b)=>{ return a.name > b.name }).map(c => {
      return <MenuItem value={c.id} key={c.id} primaryText={c.name}/>
    });

    const SkillsItems = Object.values(skills).sort((a,b)=>{ return a.name > b.name }).map(s => {
      return <MenuItem value={s.id} key={s.id} primaryText={s.name}/>
    });
The number of CategoryItems is 10, the number of SkillsItems is about 30. Both dropdowns render with categories being sorted but skills are not. The data model for the two is the same:
code:
[
  {
    name: 'Foo',
    id: '1',
  },
...
]
My thought is that the sorting for the categories completes in time but the skills does not. Am I right in this assumption? Perhaps I should be doing the sorting somewhere else?

Doom Mathematic
Sep 2, 2008
With JavaScript sorting the comparator needs to return -1, 0 or 1 depending on whether a should come before b, they are the same, or b should come before a respectively. However, your comparator returns false, false and true respectively in these three cases, which coerce to 0, 0 and 1. This causes the sorting algorithm to proceed incorrectly and return unsorted data.

Although, testing manually, it looks as if the algorithm coincidentally returns the right answer for smaller inputs!

Try: .sort((a, b) => a.name.localeCompare(b.name)).

huhu
Feb 24, 2006

Doom Mathematic posted:

With JavaScript sorting the comparator needs to return -1, 0 or 1 depending on whether a should come before b, they are the same, or b should come before a respectively. However, your comparator returns false, false and true respectively in these three cases, which coerce to 0, 0 and 1. This causes the sorting algorithm to proceed incorrectly and return unsorted data.

Although, testing manually, it looks as if the algorithm coincidentally returns the right answer for smaller inputs!

Try: .sort((a, b) => a.name.localeCompare(b.name)).
So, this works. Thank you so much. Could you clarify though, I don't quite follow how sorting is done incorrectly.

necrotic
Aug 2, 2005
I owe my brother big time for this!
The sort function must return -1 for "a is first", 0 for "a and b sort the same", and 1 for "b comes first". False coerces to 0, true to 1, and your sort comparison is returning a Boolean from the greater-than operator.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

localeCompare is a built-in way to lexographically compare and sort strings. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

Doom Mathematic
Sep 2, 2008

huhu posted:

So, this works. Thank you so much. Could you clarify though, I don't quite follow how sorting is done incorrectly.

Array.prototype.sort assumes that the function you supply is indeed a comparator function which consistently behaves in the -1/0/1 way which we just discussed. It's not possible for the JavaScript engine to detect/verify that it actually behaves in this way, so unfortunately for us no error gets thrown if, as in your case, it doesn't. What happens instead is that the "comparator" function gets plugged into the sorting algorithm as normal, and the array gets permuted in a fairly unpredictable way.

LP0 ON FIRE
Jan 25, 2006

beep boop
How do you avoid JS security policy errors, but with Mac OS Automator AppleScript???

https://stackoverflow.com/questions/49500920/security-policy-errors-with-automator-running-javascript-with-safari

LifeLynx
Feb 27, 2001

Dang so this is like looking over his shoulder in real-time
Grimey Drawer
So I'm trying to reduce my dependency on jQuery and learn some real Javascript. How would I write these jQuery scripts in Real Javascript (tm)?

code:
$(window).on('scroll', function() {
	var headerfixer = $("#asttop").height();
    var y_scroll_pos = window.pageYOffset;
    if(y_scroll_pos > headerfixer) { $("#asttop").addClass('scrolledpast'); }
	if(y_scroll_pos < headerfixer) { $("#asttop").removeClass('scrolledpast'); }
});
code:
$("#mobilenavtoggle").click(function(){
	$("#mobilenavigation").toggleClass("mobilenavactive");
	$("#mobilemenu").slideToggle("fast");
});

Munkeymon
Aug 14, 2003

Motherfucker's got an
armor-piercing crowbar! Rigoddamndicu𝜆ous.



LifeLynx posted:

So I'm trying to reduce my dependency on jQuery and learn some real Javascript. How would I write these jQuery scripts in Real Javascript (tm)?

code:
$(window).on('scroll', function() {
	var headerfixer = $("#asttop").height();
    var y_scroll_pos = window.pageYOffset;
    if(y_scroll_pos > headerfixer) { $("#asttop").addClass('scrolledpast'); }
	if(y_scroll_pos < headerfixer) { $("#asttop").removeClass('scrolledpast'); }
});
code:
$("#mobilenavtoggle").click(function(){
	$("#mobilenavigation").toggleClass("mobilenavactive");
	$("#mobilemenu").slideToggle("fast");
});

You're looking for https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector https://developer.mozilla.org/en-US/docs/Talk:DOM/element.addEventListener and https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

.height() is probably more complicated and you can read https://developer.mozilla.org/en-US/docs/Web/API/CSS_Object_Model/Determining_the_dimensions_of_elements to find out why.

I'd also suggest checking the jQuery source for things you want to replace because it often boils down to a check to see if the browser has the equivalent functionality exposed in one DOM method followed by a call to that method (and then a fallback branch that calls some helper code to paper over the deficiency, but you're already deciding to throw that away, so ignore it).

Munkeymon fucked around with this message at 16:25 on Mar 27, 2018

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Yeah, over the years I've found the jquery and lodash source to be surprisingly approachable and informative.

Lumpy
Apr 26, 2002

La! La! La! Laaaa!



College Slice

LifeLynx posted:

So I'm trying to reduce my dependency on jQuery and learn some real Javascript. How would I write these jQuery scripts in Real Javascript (tm)?

code:
$(window).on('scroll', function() {
	var headerfixer = $("#asttop").height();
    var y_scroll_pos = window.pageYOffset;
    if(y_scroll_pos > headerfixer) { $("#asttop").addClass('scrolledpast'); }
	if(y_scroll_pos < headerfixer) { $("#asttop").removeClass('scrolledpast'); }
});
code:
$("#mobilenavtoggle").click(function(){
	$("#mobilenavigation").toggleClass("mobilenavactive");
	$("#mobilemenu").slideToggle("fast");
});

JavaScript code:
// second example
const navToggle = document.getElementById('mobilenavtoggle')
navToggle.addEventListener( 'click', () => {
  navToggle.classList.toggle( 'mobilenavactive' );
// for this, you might use CSS animation to do the same thing as jQuery's code
  navToggle.classList.toggle( 'someAnimClass' );

});
For the first, you do the event handler like so:

code:
window.addEventListener( 'scroll', event => {
   // code here... use el.classList.add / remove and so on
});
And make sure you debounce the scroll handler!

duz
Jul 11, 2005

Come on Ilhan, lets go bag us a shitpost


Someone in another thread linked this site for replacing jQuery with regular JavaScript http://youmightnotneedjquery.com/
One catch I noticed is that jQuery is more graceful about passing in the wrong data type where as that will cause an error in normal JavaScript.

Also, for that scroll binding, see if you want position: sticky instead if that class is to make it visible.

Doom Mathematic
Sep 2, 2008

duz posted:

One catch I noticed is that jQuery is more graceful about passing in the wrong data type where as that will cause an error in normal JavaScript.

I can't even count the number of times I've been bitten by $('.this-element-sure-as-heck-does-not-exist').click() just silently succeeding when it really, really would have been more helpful if it failed noisily.

I mean, why would anybody want that? To click on nothing? In what universe is that the desired behaviour?

Thermopyle
Jul 1, 2003

...the stupid are cocksure while the intelligent are full of doubt. —Bertrand Russell

Just don't make mistakes and then that won't be a problem.

Ape Fist
Feb 23, 2007

Nowadays, you can do anything that you want; anal, oral, fisting, but you need to be wearing gloves, condoms, protection.
I'm here to shout about how you should be using TypeScript for everything like a wild man on a busy street corner with a sign related to God or God's judgement.

Roadie
Jun 30, 2013

Ape Fist posted:

I'm here to shout about how you should be using TypeScript for everything like a wild man on a busy street corner with a sign related to God or God's judgement.

:yeah:

Adbot
ADBOT LOVES YOU

geeves
Sep 16, 2004

Ape Fist posted:

I'm here to shout about how you should be using TypeScript for everything like a wild man on a busy street corner with a sign related to God or God's judgement.

Will your sign have the JavaScript equivalent of dead fetuses on it?

"'var' and 'for... in' cause cancer!" https://www.flickr.com/photos/geeves/199629113/

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply