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
Squashy Nipples
Aug 18, 2007

fletcher posted:

I think you guys might be trying to be too helpful. Show Squashy Nipples how to figure it out, don't just give 'em the answer!

Um.. OK.

Actually, this is exactly what I needed to hear:


baka kaba posted:

It's a scope issue - when you define the result variable in those if blocks, it only exists within that block (and any others you create inside that block, all the way down). Once you exit the block by passing outside the closing brace, that variable's gone, baby

I thought I was having a flow issue, but it was a scope issue. Thanks, Baka!

This type of scoping is new to me. Like I said in my first post, better to just convert the result to a string, and format that as necessary. I'm used to the variable types doing the casting for me, so now I need to figure out how to format it as desired.

Adbot
ADBOT LOVES YOU

fletcher
Jun 27, 2003

ken park is my favorite movie

Cybernetic Crumb

I'm not trying to be mean! I just think it can be more beneficial when you are learning to be guided in the right direction but still have you get there yourself, rather than somebody grabbing your hand and dragging you there.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

fletcher posted:

I'm not trying to be mean! I just think it can be more beneficial when you are learning to be guided in the right direction but still have you get there yourself, rather than somebody grabbing your hand and dragging you there.

Yeah I agree and I usually do that with homework questions, but this seemed more like a fundamental misunderstanding about how variable definition works, I'm not sure any subtle clues would help!

There's formatting on the horizon so this is just the beginning :unsmigghh:

Fergus Mac Roich
Nov 5, 2008

Soiled Meat

Zaphod42 posted:

You can declare variables inside branches, but then they'll only exist within that branch because of scope, like baka kaba said.

You generally want to define the variable ahead of the branch, and then assign its value inside the branch.

You don't have to do anything ;) but if that's what the logic requires.

If the flow of the code is giving you hangups, try doing a flowchart first. Remove the confusing code part and just think out what the steps need to be and what needs to happen at each point, then translate that to code.

I used to, and still sometimes, write comments that detail step by step what needs to happen on each line in plain English, and then remove them when I'm done.

Sistergodiva
Jan 3, 2006

I'm like you,
I have no shame.

So, back again to terrorize you guys, seriously, if there is any forums upgrade you want or an avatar, just tell me, you've been a great help!

So, I have managed to load items from my JSON, draw them, texture them, they have tooltips and I can set them to do stuff when clicked.

code:
        Rectangle[] item = new Rectangle[currentItem.length];
        for(int i = 0; i < currentItem.length; i++) {
            item[i] = new Rectangle(currentItem[i].getItemLocX(), currentItem[i].getItemLocY(), currentItem[i].getItemSizeX(), currentItem[i].getItemSizeY());
        }
This is what I use to create a rectangle for each item in the game, I can then use if(item.contains(mouseNode)) to set tooltips and check if clicks are inside them etc, works great.

My only problem is that I have to create them in ever method that I use them in. So in my doTooltip() method I have to have this for loop and recreate the item rectangles again.

I must be doing this wrong somehow right?

https://github.com/sistergodiva/javagame/blob/master/Play.class

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Yeah if you ever find yourself repeating the same code, that's a good sign that you need to pull it out into a common method you can call instead. As well as cutting down on your code it makes it easier to change, since it affects everything and you won't miss one place and end up with inconsistencies

If you look at what your code is actually doing, it's just making a rectangle by calling a bunch of methods on an Item - so you could just make a getRect() method on the item and call that, and put all that calculation code in there instead. Or maybe call it getClickArea(), that way you can change the internal code in the Item class, maybe to accurately detect clicks on other object shapes, and return a more general shape object (if there's one you can use)

But that's a bit awkward, and you don't actually need the rects, right? If you just want to know if the Item was clicked, you can just make an isHere(Point) method on the Item. That way it can take the mouse position, calculate the Rect (or whatever) internally, work out if the click is within its bounds, and then return an answer. The Play class doesn't need to know these internal details, and if you did change the detection code to use other more accurate shapes, the calling object doesn't need to know about any of that - it just calls isHere() and gets a yes or no answer.

You could still have a getRect() method as well, if you ever did need the actual bounding box for whatever reason. But just being able to ask the Item a question and get a simple answer is all you need for your tooltip code etc, and it's easier to read and understand too. Not saying isHere is necessarily a good name though!

Oh also if you wanted you could cache the Rect object inside the Item, create it when you specify the item's location, that way you don't have to recalculate it each time. Because each Item is a separate object it has its own individual state, and one part of that state could be the bounding Rect. You don't have to do that - it's more a convenience/neatness thing, the tradeoff is having two different components that describe the same thing (the individual coordinates and the Rect based on those coordinates), which means you need to be careful about keeping them consistent with each other if you ever change their values. You don't want coords and a Rect that don't match, y'know?

baka kaba fucked around with this message at 15:33 on Oct 4, 2015

Sistergodiva
Jan 3, 2006

I'm like you,
I have no shame.

baka kaba posted:

Yeah if you ever find yourself repeating the same code, that's a good sign that you need to pull it out into a common method you can call instead. As well as cutting down on your code it makes it easier to change, since it affects everything and you won't miss one place and end up with inconsistencies

If you look at what your code is actually doing, it's just making a rectangle by calling a bunch of methods on an Item - so you could just make a getRect() method on the item and call that, and put all that calculation code in there instead. Or maybe call it getClickArea(), that way you can change the internal code in the Item class, maybe to accurately detect clicks on other object shapes, and return a more general shape object (if there's one you can use)

But that's a bit awkward, and you don't actually need the rects, right? If you just want to know if the Item was clicked, you can just make an isHere(Point) method on the Item. That way it can take the mouse position, calculate the Rect (or whatever) internally, work out if the click is within its bounds, and then return an answer. The Play class doesn't need to know these internal details, and if you did change the detection code to use other more accurate shapes, the calling object doesn't need to know about any of that - it just calls isHere() and gets a yes or no answer.

You could still have a getRect() method as well, if you ever did need the actual bounding box for whatever reason. But just being able to ask the Item a question and get a simple answer is all you need for your tooltip code etc, and it's easier to read and understand too. Not saying isHere is necessarily a good name though!

Oh also if you wanted you could cache the Rect object inside the Item, create it when you specify the item's location, that way you don't have to recalculate it each time. Because each Item is a separate object it has its own individual state, and one part of that state could be the bounding Rect. You don't have to do that - it's more a convenience/neatness thing, the tradeoff is having two different components that describe the same thing (the individual coordinates and the Rect based on those coordinates), which means you need to be careful about keeping them consistent with each other if you ever change their values. You don't want coords and a Rect that don't match, y'know?

Finally understood what you guys meant now. I just made a isHere method in my item class

code:
    boolean isHere(int x, int y) {

        boolean b;
        if (x > getItemLocX() && x < itemLocX + itemSizeX && y > getItemLocY() && y < itemLocY + itemSizeX) {
            b = true;
            return b;
        } else {
            b = false;
            return b;
        }
and in my doClick function in my main file I can just do this
code:
        for (int i = 0; i < currentItem.length; i++) {
            if (currentItem[i].isHere(x, y)) {
                System.out.println(currentItem[i].getItemName());
            }

        }
Now I just need a good way to tell my inventory-state what items the player has actually picked up.

I'm currently trying with a method in my inventory state, which would be called with a list array or something.
This will be way easier when I'm not dealing with rectangles.

Edit: Thinking about it, I just added a itemPicked boolean to the item class.
I can just loop through them and get which ones to not render and have in the inventory instead.
Of course, I will need to have another flag for used items, since they are not rendered but still gone from the inventory.

Sistergodiva fucked around with this message at 17:18 on Oct 4, 2015

Loezi
Dec 18, 2012

Never buy the cheap stuff

Sistergodiva posted:

code:
    boolean isHere(int x, int y) {

        boolean b;
        if (x > getItemLocX() && x < itemLocX + itemSizeX && y > getItemLocY() && y < itemLocY + itemSizeX) {
            b = true;
            return b;
        } else {
            b = false;
            return b;
        }

First remove the redundant variable b:
code:
    boolean isHere(int x, int y) {

        if (x > getItemLocX() && x < itemLocX + itemSizeX && y > getItemLocY() && y < itemLocY + itemSizeX) {
            return true;
        } else {
            return false;
        }
Then notice that you are just saying if (thing) { return true; } else { return false; } and replace the whole thing with

code:
    boolean isHere(int x, int y) {
        return x > getItemLocX() && x < itemLocX + itemSizeX && y > getItemLocY() && y < itemLocY + itemSizeX;
Next, add some newlines to make it more readable
code:
    boolean isHere(int x, int y) {
        return x > getItemLocX()
                && x < itemLocX + itemSizeX 
                && y > getItemLocY() 
                && y < itemLocY + itemSizeX;

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Yeah - the stuff in the parentheses after if evaluates to either true or false. So you can put that same stuff after the return statement, and it'll evaluate to T/F and get returned. You just don't need the parentheses (that's part of the if syntax), but you can keep them if it feels better or reads more easily

Keeping state like carried and used in Items is definitely possible, really it comes down to what makes the most sense, and if a particular way causes problems - like 'used' could be a property of a single item like a bottle of liquid, when it's drunk it's gone, or it could be some magic charm that grants each character one use, in which case 'used' is either a list of people who've used it (held in the item, its own list) or a property of each character (usedAmuletOfWow = true). It kinda depends on the set of objects you'll have and how they relate to each other, and if there are finite members of each group or you can have an arbitrary number. That might be a bit vague but OOP (to me) is about getting your head around encapsulation and how best to draw lines around things, to create useful objects with useful functions that all fit together nicely

Oh also, I don't know what you're doing with your Items and whatever, but you probably want to get familiar with the Java Collections - basically ways of holding a bunch of objects. Arrays are fine (and sometimes the right choice) but there are more useful, less restrictive containers. You have three basic kinds:

  • Lists - a group of objects in a fixed order. The same object can appear in multiple places in the list. Objects can be added or removed anywhere in the list, and the others will move appropriately - you never have to worry about gaps. You can access elements by index if you want (this is their position in the list so it can change as they move), sort them, and iterate over them with the enhanced for syntax (for (Type object : collection) iterates over collection and gives you each element in turn, in the variable object. So your item code would be:
    Java code:
    for (Item item : currentItems) {
        if (item.isHere(x, y)) {
            System.out.println(item.getItemName());
        }
    }
    
    Neat, huh? (You can do this with all the collections)
  • Sets - a group where each object can only appear once. Handy when you want to treat objects as being members (or not) of a group, and you only want to see each of them once, say for counting purposes or to perform some operation on them one time (like getting a set of all the items which have used=true, so you can delete or respawn them). Typically unordered, but there are ordered implementations if you need that functionality
  • Maps - a dictionary lookup, maps have a key and a value, which are both objects. Keys are unique, so this is a good way of mapping a particular object (say a Level) to something associated with it (say a collection of Items). This is something you could hold in the Level itself, so maps are often more useful for organising things externally, things the object itself doesn't necessarily need to be concerned with. You can also do checks to see if a particular key is in a map and return a default value if it isn't, look for a certain value and see what maps to it, all kinds of stuff

There's a couple more types and a lot of different implementations of each, but generally you'll use ArrayLists and HashMaps and HashSets (maybe SortedSets get a lot of use?). They can be a lot easier to work with than arrays - when I got started with Java I was used to using arrays for everything, I had to train myself to use Lists instead. Sometimes arrays are the right thing (lightweight, absolutely fixed sizes, fast) but often they ain't

Sistergodiva
Jan 3, 2006

I'm like you,
I have no shame.

baka kaba posted:

Yeah - the stuff in the parentheses after if evaluates to either true or false. So you can put that same stuff after the return statement, and it'll evaluate to T/F and get returned. You just don't need the parentheses (that's part of the if syntax), but you can keep them if it feels better or reads more easily

Keeping state like carried and used in Items is definitely possible, really it comes down to what makes the most sense, and if a particular way causes problems - like 'used' could be a property of a single item like a bottle of liquid, when it's drunk it's gone, or it could be some magic charm that grants each character one use, in which case 'used' is either a list of people who've used it (held in the item, its own list) or a property of each character (usedAmuletOfWow = true). It kinda depends on the set of objects you'll have and how they relate to each other, and if there are finite members of each group or you can have an arbitrary number. That might be a bit vague but OOP (to me) is about getting your head around encapsulation and how best to draw lines around things, to create useful objects with useful functions that all fit together nicely

Oh also, I don't know what you're doing with your Items and whatever, but you probably want to get familiar with the Java Collections - basically ways of holding a bunch of objects. Arrays are fine (and sometimes the right choice) but there are more useful, less restrictive containers. You have three basic kinds:

  • Lists - a group of objects in a fixed order. The same object can appear in multiple places in the list. Objects can be added or removed anywhere in the list, and the others will move appropriately - you never have to worry about gaps. You can access elements by index if you want (this is their position in the list so it can change as they move), sort them, and iterate over them with the enhanced for syntax (for (Type object : collection) iterates over collection and gives you each element in turn, in the variable object. So your item code would be:
    Java code:
    for (Item item : currentItems) {
        if (item.isHere(x, y)) {
            System.out.println(item.getItemName());
        }
    }
    
    Neat, huh? (You can do this with all the collections)
  • Sets - a group where each object can only appear once. Handy when you want to treat objects as being members (or not) of a group, and you only want to see each of them once, say for counting purposes or to perform some operation on them one time (like getting a set of all the items which have used=true, so you can delete or respawn them). Typically unordered, but there are ordered implementations if you need that functionality
  • Maps - a dictionary lookup, maps have a key and a value, which are both objects. Keys are unique, so this is a good way of mapping a particular object (say a Level) to something associated with it (say a collection of Items). This is something you could hold in the Level itself, so maps are often more useful for organising things externally, things the object itself doesn't necessarily need to be concerned with. You can also do checks to see if a particular key is in a map and return a default value if it isn't, look for a certain value and see what maps to it, all kinds of stuff

There's a couple more types and a lot of different implementations of each, but generally you'll use ArrayLists and HashMaps and HashSets (maybe SortedSets get a lot of use?). They can be a lot easier to work with than arrays - when I got started with Java I was used to using arrays for everything, I had to train myself to use Lists instead. Sometimes arrays are the right thing (lightweight, absolutely fixed sizes, fast) but often they ain't

Thanks! I was thinking about using some kind of list, but I couldn't really understand how to get at an objects variables while it was in a list. Would a list work for stuff like this?

code:
    private void doDescription() {
toolTip = "Nothing";
        for (int i = 0; i < currentItem.length; i++) {
            if (currentItem[i].isHere(xMousePos, yMousePos)) {
                toolTip = currentItem[i].getItemName();
            }
        }
    }
This is my toolTip method, cycling through all my items and seeing if any of them are under the mouse.

I read a json array straight into a array, seems to work really nice.

this.currentItem = mapper.readValue(new File(itemFile), ItemNew[].class);

I guess I could change the Json to a list or something instead.

fake edit:

code:
    private void doDescription() {
toolTip = "Nothing";
        for (ItemNew aCurrentItem : currentItem) {
            if (aCurrentItem.isHere(xMousePos, yMousePos)) {
                toolTip = aCurrentItem.getItemName();
            }
        }
    }

Apparently works for this also.




Loezi posted:

First remove the redundant variable b:

Thanks! I really need to get better at syntax.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

A List is like an array, except you never need to worry about the size of it, you can add and remove stuff etc - all those restrictions are gone. You'll typically iterate over it and look at each element in turn (since it's an ordered sequence of elements), but you can access it by index too, with get(int) and set(int) (and size() instead of .length to get your bounds)

Not sure about your JSON stuff specifically, there are tutorials about getting it to create lists automatically - it might be overcomplicating things for what you're doing here, I don't know! You can always turn an array into a list though:
http://stackoverflow.com/questions/157944/create-arraylist-from-array

Also you might want to rename your variables (using refactoring - get in the habit if you haven't already): for (ItemNew aCurrentItem : currentItem) is a little confusing, currentItem is actually a whole bunch of items. I'd call it something like currentLevelItems or something, and you can just call your looping variable item or something. You're really saying 'for each item in the currentLevelItems, do something with that item'. It'll help for when you (or anyone else) looks at this code later on, when you don't know or remember how it works, and you have to work out what each variable actually refers to

TheresaJayne
Jul 1, 2011

Loezi posted:

Still stuck in Java 1.6 land? I feel for you :smith:

We finally transitioned to Java7 for our main product this summer. If stars align we could be looking at Java8 as soon as next summer!

lucky you, I am stuck in 1.5 land at work <shudder>

Brain Candy
May 18, 2006

Squashy Nipples posted:

Um.. OK.

Actually, this is exactly what I needed to hear:


I thought I was having a flow issue, but it was a scope issue. Thanks, Baka!

This type of scoping is new to me. Like I said in my first post, better to just convert the result to a string, and format that as necessary. I'm used to the variable types doing the casting for me, so now I need to figure out how to format it as desired.

Also, there is a type that can represent floating point and integer results: Number. But! The type on the left hand side doesn't effect the value of the expression on the right hand side (except when using generics) baring some convenience conversions. So you'll need to do something else so 1 / 4 does what you want.

Brain Candy fucked around with this message at 11:24 on Oct 5, 2015

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Sistergodiva posted:

Thanks! I was thinking about using some kind of list, but I couldn't really understand how to get at an objects variables while it was in a list. Would a list work for stuff like this?

fake edit:

code:
    private void doDescription() {
toolTip = "Nothing";
        for (ItemNew aCurrentItem : currentItem) { //BAD VARIABLE NAMES!
            if (aCurrentItem.isHere(xMousePos, yMousePos)) {
                toolTip = aCurrentItem.getItemName();
            }
        }
    }

Apparently works for this also.

This is a bit of "syntactic sugar" (shorthand) known as the for-each loop. Its really loving handy when working through collections, because iterating over every element is something you're often going to need to do. So the for-each loop "for (thing : container)" just automatically iterates through each.

But since you seem to be a little confused by the List, I don't want you to feel like you have to use the for-each loop. That's just a shorthand. The direct way of accessing the elements of the List just like you would with an array looks like this, and is pretty drat similar to an array.

Check this

code:
List<Item> levelInventory = new ArrayList<items>();
// put things into the items list


for (int i = 0; i < levelInventory .size(); i++) { //using .size() method to get the number of elements
    Item currentItem = levelInventory.get(i); //using .get(...) to pull a single element
            if (currentItem.isHere(x, y)) {
                System.out.println(currentItem.getItemName());
            }

        }
See how simple that is?

Also, I know its hard, but use significant variable names. I'm gonna keep harping on about this until I see you get better about it :cheeky:

:siren: A list should never be called "currentItem", that makes no drat sense. Having "currentItem" and "aCurrentItem" is REALLY confusing. Don't do that. :siren:

The list should have a name that makes it clear its a plural collection. "inventory" or "itemList" or "levelItems" or even just "items" is better than "currentItem" which makes it sound like a single Item object instead of an Item array or list. There is not enough obvious difference between "currentItem" and "aCurrentItem" and so those are bad names. They sound like the same object and not a collection versus an object.

Zaphod42 fucked around with this message at 16:46 on Oct 5, 2015

Sistergodiva
Jan 3, 2006

I'm like you,
I have no shame.

Zaphod42 posted:

This is a bit of "syntactic sugar" (shorthand) known as the for-each loop. Its really loving handy when working through collections, because iterating over every element is something you're often going to need to do. So the for-each loop "for (thing : container)" just automatically iterates through each.

But since you seem to be a little confused by the List, I don't want you to feel like you have to use the for-each loop. That's just a shorthand. The direct way of accessing the elements of the List just like you would with an array looks like this, and is pretty drat similar to an array.

Check this

code:
List<Item> levelInventory = new ArrayList<items>();
// put things into the items list


for (int i = 0; i < levelInventory .size(); i++) { //using .size() method to get the number of elements
    Item currentItem = levelInventory.get(i); //using .get(...) to pull a single element
            if (currentItem.isHere(x, y)) {
                System.out.println(currentItem.getItemName());
            }

        }
See how simple that is?

Also, I know its hard, but use significant variable names. I'm gonna keep harping on about this until I see you get better about it :cheeky:

:siren: A list should never be called "currentItem", that makes no drat sense. Having "currentItem" and "aCurrentItem" is REALLY confusing. Don't do that. :siren:

The list should have a name that makes it clear its a plural collection. "inventory" or "itemList" or "levelItems" or even just "items" is better than "currentItem" which makes it sound like a single Item object instead of an Item array or list. There is not enough obvious difference between "currentItem" and "aCurrentItem" and so those are bad names. They sound like the same object and not a collection versus an object.


code:
    private void doDescription() {
        toolTip = "Nothing";
        for (ItemNew aLoadedItem : loadedItems) {
            if (aLoadedItem.isHere(xMousePos, yMousePos)
                    && !aLoadedItem.isItemPicked()
                    && aLoadedItem.getItemLevel() == currentLevel.getLevelId()) {
                toolTip = aLoadedItem.getItemName();
            }
        }
    }
It's just that sometimes I don't know what name is good before everything is finished.
At least it was easy to change with refraction.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
Why call it "aLoadedItem" ? Skip the a, that's just awkward. "loadedItem" is much better.

Why is the class "ItemNew" ? Is there an "ItemOld" class? this is awkward. Why not just Item? Or if Item isn't descriptive enough, if this isn't a general type of Item, then "ItemNew" isn't good either.

And obviously doDescription() is no good :cheeky: although that was probably just a placeholder.

Its a pain but trust me man, a week or two later you're going to be so loving happy that you took the time to re-name your variables to make sense. The difference between code that you can debug in 5 minutes and code that takes three hours to debug is largely stuff like variable names. Especially considering you're going to make mistakes since you're new and have to fix things, you're just doing yourself a favor to take a few minutes to rename variables to be significant.

.isItemPicked() isn't too bad; the "is__" is good because this is a method which returns a boolean, and that reminds us so. "itemPicked" is a little awkward but I get what you mean.

.getItemLevel() and .getLevelId() are both perfectly fine. Get makes it clear these are just accessing a class variable, and the rest of the name tells you which variable.

Sistergodiva posted:

It's just that sometimes I don't know what name is good before everything is finished.
At least it was easy to change with refraction.

Try to plan your code before you write it, maybe write a flowchart or some pseudocode. That'll mean you'll have less errors and then you should have a better idea of what the variables are going to be used for and so you can name them appropriately.

That said, yeah, don't be afraid to just take a pass over the code when you're starting to get it right to clean up some things.
Refactoring is pretty painless with a good IDE that can intelligently replace all the references to the variable at the same time.

geeves
Sep 16, 2004

Zaphod42 posted:

:siren: A list should never be called "currentItem", that makes no drat sense. Having "currentItem" and "aCurrentItem" is REALLY confusing. Don't do that. :siren:

The list should have a name that makes it clear its a plural collection. "inventory" or "itemList" or "levelItems" or even just "items" is better than "currentItem" which makes it sound like a single Item object instead of an Item array or list. There is not enough obvious difference between "currentItem" and "aCurrentItem" and so those are bad names. They sound like the same object and not a collection versus an object.

My coworker does poo poo like this, as well as using shortened names that are sometimes hard to decipher. I've wasted a lot of time just trying to figure out what things are when using semantic names would make things much quicker.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
Yeah, I mean you don't need to go overboard and prefix everything with hungarian notation or anything, this is Java. But using significant names versus garbage names is one of the first marks of a programmer who is starting to really get it versus somebody who is just flailing around to make it work.

I myself still do things like

Iterator itr;
Iterator itr2;

Sometimes, but its bad and I try to force myself to do better whenever I can.

Sistergodiva
Jan 3, 2006

I'm like you,
I have no shame.

Zaphod42 posted:

Why call it "aLoadedItem" ? Skip the a, that's just awkward. "loadedItem" is much better.

Why is the class "ItemNew" ? Is there an "ItemOld" class? this is awkward. Why not just Item? Or if Item isn't descriptive enough, if this isn't a general type of Item, then "ItemNew" isn't good either.

And obviously doDescription() is no good :cheeky: although that was probably just a placeholder.

Its a pain but trust me man, a week or two later you're going to be so loving happy that you took the time to re-name your variables to make sense. The difference between code that you can debug in 5 minutes and code that takes three hours to debug is largely stuff like variable names. Especially considering you're going to make mistakes since you're new and have to fix things, you're just doing yourself a favor to take a few minutes to rename variables to be significant.

.isItemPicked() isn't too bad; the "is__" is good because this is a method which returns a boolean, and that reminds us so. "itemPicked" is a little awkward but I get what you mean.

.getItemLevel() and .getLevelId() are both perfectly fine. Get makes it clear these are just accessing a class variable, and the rest of the name tells you which variable.


Try to plan your code before you write it, maybe write a flowchart or some pseudocode. That'll mean you'll have less errors and then you should have a better idea of what the variables are going to be used for and so you can name them appropriately.

That said, yeah, don't be afraid to just take a pass over the code when you're starting to get it right to clean up some things.
Refactoring is pretty painless with a good IDE that can intelligently replace all the references to the variable at the same time.

When intellij made my for loop into a for each it renamed it added an A in front of the name, I guess I should read more about how that syntax works, I though I had to prefix it with an A.

ItemNew was just me redesigning the item class and not wanting to lose the old one if I hosed up. I should really get github integration in intellij working. Probably time to just rename it item since it's been like a week since I deleted the old Item.class.

Yeah, doDescription() is just a placeholder, not sure what I should call it though. What it does is that when you mouse over an item, it sets the toolTip String to that items name so you can see what you are mousing over.

Guess itemTaken would be better.

getItemLevel is probably dumb since what it get's is the variable in Item that decides what level the Item is located in. ItemLevelLocation is probably better, but a bit long maybe.

Kuule hain nussivan
Nov 27, 2008

Sistergodiva posted:

Yeah, doDescription() is just a placeholder, not sure what I should call it though. What it does is that when you mouse over an item, it sets the toolTip String to that items name so you can see what you are mousing over.
setTooltipToItemName()?

Sistergodiva
Jan 3, 2006

I'm like you,
I have no shame.

Kuule hain nussivan posted:

setTooltipToItemName()?

I though set was reserved for setters, but yeah otherwise that's a logical one :D

Kuule hain nussivan
Nov 27, 2008

Sistergodiva posted:

I though set was reserved for setters, but yeah otherwise that's a logical one :D
Hmm, true. I might have a very loose definition of a setter (it sets something :D)

How about setupToolTip() since that's what you're basically doing. Or setupToolTipForLocation or setupToolTipForMousePosition() if you want to be even more exact.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Sistergodiva posted:

When intellij made my for loop into a for each it renamed it added an A in front of the name, I guess I should read more about how that syntax works, I though I had to prefix it with an A.

ItemNew was just me redesigning the item class and not wanting to lose the old one if I hosed up. I should really get github integration in intellij working. Probably time to just rename it item since it's been like a week since I deleted the old Item.class.

Yeah, doDescription() is just a placeholder, not sure what I should call it though. What it does is that when you mouse over an item, it sets the toolTip String to that items name so you can see what you are mousing over.

Guess itemTaken would be better.

getItemLevel is probably dumb since what it get's is the variable in Item that decides what level the Item is located in. ItemLevelLocation is probably better, but a bit long maybe.

You don't actually need to use github, you can just turn on VCS integration (Tools menu?) and choose Git and it'll make a local repository. Just back up your project folder to be safe and you'll be Gitting in no time!

The variable renaming thing is IntelliJ making some guesses about what you might want to call your variable - sometimes they're right and it's nice and quick to just highlight or click the suggestion you want. But nah, you can just type while the name is highlighted and it'll change every copy at once

And the get naming style is a personal thing - I think it's fine since your method is returning an int or whatever instead of an actual Level object, and anyone trying to use it should see that immediately. Maybe it would be bad form in a more rigid coding style though (does Java programming have manuals of style?)

Squashy Nipples
Aug 18, 2007

Zaphod42 posted:

Yeah, I mean you don't need to go overboard and prefix everything with hungarian notation or anything, this is Java. But using significant names versus garbage names is one of the first marks of a programmer who is starting to really get it versus somebody who is just flailing around to make it work.

I myself still do things like

Iterator itr;
Iterator itr2;

Sometimes, but its bad and I try to force myself to do better whenever I can.

Yeah, I'm a big fan of clear, descriptive variable names... the kids I'm trying to teach keep wanting to use single letter variable names like "a". :rolleyes:
I've tried telling them that it will come back to bite them in the rear end, but when they push back I can't give concrete reasons why... I just know from experience.

Also, its taking me a while to get used to the Java variable naming conventions, I really miss prefixing with the variable type, as it makes them stand out to me.
Like, lngRow strFileName and poo poo like that. Why do we not do that in Java?

Squashy Nipples
Aug 18, 2007

Ok, my kids and I got our little calculator running in a few different forms. Does anyone have any suggestions for similar, homework-style assignments for us to work on?

I don't have access to the robotics API yet, so we can't do any practical programming.

Zorro KingOfEngland
May 7, 2008

One of my favorite computer science homework assignments in high school was to write a tic-tac-toe program. Then after that was finished, we had to write a computer opponent for it. Because tic-tac-toe is a solved game you can write an AI that's unbeatable, which was how we got full credit for the assignment.

If you're sadistic, make them take someone else's program and write the AI for their implementation so they understand the importance of good variable names and extensible code. If nothing else, it'll teach them to hate their teammates. Just like the real world!

Kuule hain nussivan
Nov 27, 2008

Squashy Nipples posted:

Ok, my kids and I got our little calculator running in a few different forms. Does anyone have any suggestions for similar, homework-style assignments for us to work on?

I don't have access to the robotics API yet, so we can't do any practical programming.
How about a small database app? Do either of them collect stuff?

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Sistergodiva posted:

When intellij made my for loop into a for each it renamed it added an A in front of the name, I guess I should read more about how that syntax works, I though I had to prefix it with an A.

getItemLevel is probably dumb since what it get's is the variable in Item that decides what level the Item is located in. ItemLevelLocation is probably better, but a bit long maybe.

Yeah, definitely read up on the for-each syntax. Its just (class objectName : containerObject). The syntax is all that has to be there, the naming is totally up to you. Like I said, that's just fancy syntactic sugar so feel free to skip it if its loving with you. Its more important that you understand the basics than the fancy poo poo right now. Just do a for(int i=0; i<container.size(); i++) loop instead for now so you don't get mixed up by it.

Yeah something like getLevelID() maybe? Sounds good to me.

Squashy Nipples posted:

Yeah, I'm a big fan of clear, descriptive variable names... the kids I'm trying to teach keep wanting to use single letter variable names like "a". :rolleyes:
I've tried telling them that it will come back to bite them in the rear end, but when they push back I can't give concrete reasons why... I just know from experience.

Also, its taking me a while to get used to the Java variable naming conventions, I really miss prefixing with the variable type, as it makes them stand out to me.
Like, lngRow strFileName and poo poo like that. Why do we not do that in Java?

Its just generally considered too verbose and a pain in the rear end. Java is really strongly typed so if you're using a modern IDE its pretty easy to mouse over a variable or whatever to see what class or PDT that variable is, so Hungarian Notation fell by the wayside and isn't used in Java. The same is true of most other modern, high-level strongly-typed languages like C#.

With C its much more important because you can pass around object pointers or function pointers and things that you need to not mix up the class of, but with Java you're not even allowed to access pointers, its all handled by the language. You just pass object references around and everything is more strongly typed at compile time.

But yeah, significant variable names are still really important. And you see exactly that, lots of new programmers just don't want to have to type in much so they pick variable names like "a" "o" etc. which are obviously horrible.

Then a few hours later they're debugging their program and they have no idea why it isn't working, but its because they're doing while( e < 10) instead of while( a < 10) or something, which would be much more obvious if it was like while( counter < 10) instead of while(age < 10) or something.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Squashy Nipples posted:

Ok, my kids and I got our little calculator running in a few different forms. Does anyone have any suggestions for similar, homework-style assignments for us to work on?

I don't have access to the robotics API yet, so we can't do any practical programming.

A simple chat app can be a fun way to learn network programming. Write a chat client and a chat server and actually run them on two computers, and then send messages back and forth! Its something that'll introduce them to something new (networking, internet, connectivity, etc.) but its not anything insanely complicated, and the results are very real and demonstrable (you can actually see the text pop up on somebody else's computer!)

Another thing that's fun is a simple text-adventure or single player MUD style game, like Zork.

You know "you are in a dark hallway, obvious exits are: east, west"
"go west"
"you are now in a dark room, there is a flask on the floor"
"get ye flask"

Stuff like that. Building a network of rooms and having game logic to move you between them, read their descriptions, and pick up items which you use in other rooms to solve puzzles is basically as simple as a videogame can get. (no graphics!) Its still a good bit of work but its much simpler than trying to program Super Mario or something.

And if you do both of those things (chat app, text-based game) you can combine them to make a proper multi-player MUD!

Or for that matter other simple games like card games, poker, blackjack, etc. can be made into very simple text-based computer games too.

Kuule hain nussivan posted:

How about a small database app? Do either of them collect stuff?

Eh, I dunno about that. Databases are super boring, they're little more than efficient spreadsheets. I don't think kids would really appreciate a small database app. Databases are super useful things to learn for modern applications but as a student project I dunno. Well, I guess it depends how old the kids are. But I would probably put off databases until like, college. Useful, but highly academic.

I mean you could so a similar thing without a proper database, I guess. Just like storing a bunch of strings into a data file and then reading it back? Something to catalog all your pokemon cards? :cheeky:

Zaphod42 fucked around with this message at 16:19 on Oct 6, 2015

Squashy Nipples
Aug 18, 2007

Can't one argue that a lot of modern games are just GUI's for a database?
I've never done any game development, so how else does one store game details? A bunch of constants and variables?

(professionally, I do a lot of data analysis, so perhaps I'm a little too RDB-centric in my thinking.)


Great explanations and ideas, thanks to all.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Squashy Nipples posted:

Can't one argue that a lot of modern games are just GUI's for a database?
I've never done any game development, so how else does one store game details? A bunch of constants and variables?

(professionally, I do a lot of data analysis, so perhaps I'm a little too RDB-centric in my thinking.)

No, most games actually don't use a proper database. I mean some definitely do, MMOs absolutely must by definition, and a few other games with gigantic worlds like Skyrim or X3 I could see using a database format maybe, or maybe they don't.

But most games its just a giant binary or text file with a bunch of variables and constants that are read from disk, nothing too fancy. When you think about it most videogames barely use probably like a few megabytes of game data. Its absolutely infinitesimal compared to all the textures and models that make up the art data. If you can break that data up into "levels" then you've got even less data to worry about for the game state at any one time, you could just be reading in a few dozen numbers and that's it. Player health, weapon positions, weapon damage values, monster spawning points, stuff like that, but not a whole lot to it.

Again, it depends upon the game though.

I definitely wouldn't call games "GUIs for a database" though, because almost all games are largely a ton of special game-logic. That's the meat of the game and its not DB or GUI related at all. These days modern games have a ton of code for rendering, but there's still a ton of game logic. Compared to rendering and logic the UI and DB stuff is minor or even non-existent, although I guess you could roll the rendering into the "UI" side of things depending upon how you look at it. But no, the game logic part can't be overlooked.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
Lets take Mario as a case study.

For the "DB" side of things, you have to read in the world state. So you could have a database or you could have a text file or whatever, but all it has to do is describe what blocks go where for world 1-1. It says there's a brick here, a pile of bricks there, a fire flower here, a mushroom there, and some goombas here, ending with a flagpole. Not really a ton of data, you could store it all in a single int or char array even, with mapping each int or char to a certain brick or enemy type. It'd be a pretty big array, like 100x2000 or something (I have no idea how many tiles are in 1-1) but still, its just a single array. That's all you need for the first level, other than I guess like the default player lives count and the time left to finish the level, but those can even be hard-coded.

For the "UI" side of things, Mario has very little. You render the score, the world number, the lives count, and the timer.

For the full rendering, you have to draw the background and all the tiles, and then the mario sprites and the enemy sprites, by reading them from memory. This takes a bit of doing but its really not too bad once you've worked it out.

For the game logic, you need to do a ton of special case things.

Is mario small, big, or does he have fire-power? Is the user pressing A or B? Is mario on the ground, or in the air? Is mario touching an enemy? Did mario fall on the enemy, if so kill the enemy. Did the enemy touch mario from the side? If so Mario loses his powers down a level, unless he was small in which case now you need to play the death animation. Is mario pressing down on top of a pipe? Is this a warp pipe or a normal pipe? If so teleport him to the other screen. Speaking of pipes, make sure to calculate the up-down movement of piranha plants every tick, unless they're under the pipe in which case you have to time how long they have to wait, unless mario is on top in which case they will wait until he leaves. Is mario pushing left? Move him left, unless he's at the left side of the screen. Is he pushing right? Move right, if he approaches the right side move the camera to the right. Also make sure to update goomba and koopah logic on every tick, goombas move left until they hit a wall and then move right, koopas do the same, if they walk off a tile then they need to start falling with gravity, also mushrooms have their own movement every tick but flowers do not, and calculate every tick if mario is touching one of the powerups and if so change mario's state, don't forget to calculate the movements of any fireballs that are in the air every tick because they need to move, oh and if mario touches a coin remove that coin from the game and increase the score, also the score needs to be updated for each enemy kill and each pickup....

etc. etc. etc.

We haven't even gotten into things like Mario's momentum and acceleration, changes to physics underwater, logic of new enemies like Bowzer or bullet-bill or bloopers, or a million other things.

Game logic is where the magic happens.

Zaphod42 fucked around with this message at 17:08 on Oct 6, 2015

Squashy Nipples
Aug 18, 2007

Wow, that's all fantastic! I'm going to steal it and subject the students to it.

Vidya games are a good way to communicate with them... last week, when we were talking about different ways to add comments, one of the kids added a comment block with ASCII art for the Aperture Science logo, and he was shocked/thrilled when I recognized it.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
Yeah games are great because you actually get something out of it. Making some esoteric programming challenge is okay, but making a fun thing is way more satisfying.

The problem with games is that most people don't realize how much work they are. Even a simple 2D game can be thousands of lines of code.

That's why I suggested starting with something text-based like Zork or Poker. Then you can work your way up to Pong and using graphics in a simple one-screen game way, then do something slightly more advanced like Tetris, and only then move to multi-screen or scrolling-screen games like Mario. And only after THAT do you even attempt 3D games. :cheeky:

Polidoro
Jan 5, 2011


Huevo se dice argidia. Argidia!
I'm having a weird Tomcat issue. It randomly sets status 500 to correct responses on static files. For example, the browser sends a request for somefile.css and the response is the contents of somefile.css but with an Internal Server Error instead of a 200 OK. This causes the browser to not use the file so I get a broken page.

The weirdest part is that there's not a single error in the logs, the only thing I can see is that the 500 answer is in the access logs, but the rest of the logs are clean.

Anyone seen anything like this?

Pie Colony
Dec 8, 2006
I AM SUCH A FUCKUP THAT I CAN'T EVEN POST IN AN E/N THREAD I STARTED

Zaphod42 posted:

But since you seem to be a little confused by the List, I don't want you to feel like you have to use the for-each loop. That's just a shorthand. The direct way of accessing the elements of the List just like you would with an array looks like this, and is pretty drat similar to an array.

Not to nitpick but this isn't entirely accurate, if you have a List and iteratively call .get() on it, it could wind up being a lot more inefficient if the implementation isn't an ArrayList. A for-each loop is more like accessing the list's iterator.

I would also argue that you should use syntactic sugar all the time wherever possible.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

Pie Colony posted:

Not to nitpick but this isn't entirely accurate, if you have a List and iteratively call .get() on it, it could wind up being a lot more inefficient if the implementation isn't an ArrayList. A for-each loop is more like accessing the list's iterator.

I would also argue that you should use syntactic sugar all the time wherever possible.

That is nitpicking but fair enough. You could use an iterator and iterator.next() and then the performance should be the same, right? So you still don't have to use the for-each.

I would argue against using syntactic sugar all the time, such as when you're a new student learning the language for the first time :cheeky:

That's also a good time to not give a gently caress about performance at all. Premature optimization is the devil and its very unlikely that calling .get() iteratively is going to be an issue for any data sets that a newbie is working with.

But yeah.

Polidoro posted:

Anyone seen anything like this?

I have not and that's definitely weird that its still returning the .css file while giving error code 500. Good luck! I assume you've already googled around :/

langurmonkey
Oct 29, 2011

Getting healthy by posting on the Internet

Squashy Nipples posted:

Ok, my kids and I got our little calculator running in a few different forms. Does anyone have any suggestions for similar, homework-style assignments for us to work on?

I don't have access to the robotics API yet, so we can't do any practical programming.

How about some fun with graphics? Maybe an etch-a-sketch with a few buttons that moves a line drawing point left right up and down, and one to clear. You can then use it to experiment with other things like changing colours, saving images etc.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.

langurmonkey posted:

How about some fun with graphics? Maybe an etch-a-sketch with a few buttons that moves a line drawing point left right up and down, and one to clear. You can then use it to experiment with other things like changing colours, saving images etc.

If they're really kids that are learning java for the first time that probably works better if you get a Turtle style library for them and then let them experiment with the drawing code, rather than trying to implement the etch-a-sketch itself from the ground up. I don't know what skill level this class is at but it sounds pretty basic and graphics can be awfully tricky.

Adbot
ADBOT LOVES YOU

Squashy Nipples
Aug 18, 2007

For reference, here is the robot from last year:

https://www.youtube.com/watch?v=WYB9sYa98eY

the kid who programmed it is in college now, which is why I'm developing new talent.

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