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
geeves
Sep 16, 2004

Squashy Nipples posted:

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?

Because we're not writing PHP. :haw:

I still use str / int / dbl as a prefix sometimes when stubbing out methods until I figure out a better name. I especially did this in my earlier days when my methods would be stupidly huge and cumbersome.

Adbot
ADBOT LOVES YOU

Polidoro
Jan 5, 2011


Huevo se dice argidia. Argidia!

Zaphod42 posted:

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 :/

After a couple hours with wireshark turns out the server had trouble sharing the session with other servers in the cluster and instead of saying something it decided to be a dick.

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Arcane generics/inheritance typing question:

Java code:
public class Scratch {
    public static void main(String... args) throws Exception {
        final Generic<Generic<Object>> noExtend = null;
        final Generic<Generic<? extends Object>> doesExtend = null;

        doThing(noExtend); //Generic<Generic<Object>> cannot be converted to Generic<Generic<? extends Object>>
        doThing(doesExtend);
    }

    public static class Generic<T> {};

    public static <T> Object doThing(Generic<Generic<? extends T>> arg1) {
        return null;
    }
}
Why can't List<List<Object>> be converted to List<List<? extends Object>>?

FateFree
Nov 14, 2003

Is there a reason you are doing double generics? List<List<Object>> doesnt really make any sense. List<Object> means a list of objects, List<List<Object>> means a list of lists of objects. But List<Object> defeats the points of generics anyway because you should have a list of specific types. Anyway your code compiles without all the double generics:

code:
public class Scratch {
    public static void main(String... args) throws Exception {
        final Generic<Object> noExtend = null;
        final Generic<? extends Object> doesExtend = null;

        doThing(noExtend); //Generic<Generic<Object>> cannot be converted to Generic<Generic<? extends Object>>
        doThing(doesExtend);
    }

    public static class Generic<T> {};

    public static <T> Object doThing(Generic<? extends T> arg1) {
        return null;
    }
}

Gravity Pike
Feb 8, 2009

I find this discussion incredibly bland and disinteresting.
Yeah, I was trying to simplify this to a "toy"-level problem. In actuality, I've written a library function

Java code:
class CompletableFutureUtils {
  public static <T> CompletableFuture<List<T>> allSuccessful(List<CompletableFuture<T>> futures) {
      final CompletableFuture[] futuresArray = futures.toArray(new CompletableFuture[futures.size()]);
      final CompletableFuture<Void> allDoneFuture = CompletableFuture.allOf(futuresArray);
      return allDoneFuture.handle(
                (v, t) -> futures.stream()
                                 .map(future -> future.isCompletedExceptionally() ? null : future.join())
                                 .collect(Collectors.<T>toList())
    );
  }
}
A coworker helpfully rewrote this to expand the contract to
Java code:
public static <T> CompletableFuture<List<T>> allSuccessful(List<CompletableFuture<? extends T>> futures)
but it broke a bunch of code, and I'm not quite sure why.

Edit: vv Thanks!

Gravity Pike fucked around with this message at 23:47 on Oct 6, 2015

Sedro
Dec 31, 2008
The variance of the inner type is not somehow transitive to the outer type. You have an inner type Generic<? extends T> which is covariant in its type parameter and an outer type Generic<Generic<...>> which is invariant in its type parameter.

Given some types Sub extends Base, then Generic<Sub> extends Generic<Base> is only true if Generic is covariant.

If Generic is covariant then you need to say so in every instance, e.g. doThing(Generic<? extends Generic<? extends T>> arg1)

geeves
Sep 16, 2004

Gravity Pike posted:

Arcane generics/inheritance typing question:

Java code:
public class Scratch {
    public static void main(String... args) throws Exception {
        final Generic<Generic<Object>> noExtend = null;
        final Generic<Generic<? extends Object>> doesExtend = null;

        doThing(noExtend); //Generic<Generic<Object>> cannot be converted to Generic<Generic<? extends Object>>
        doThing(doesExtend);
    }

    public static class Generic<T> {};

    public static <T> Object doThing(Generic<Generic<? extends T>> arg1) {
        return null;
    }
}
Why can't List<List<Object>> be converted to List<List<? extends Object>>?

I think the problem was that your Scratch class doesn't reference a Record object or have a wikiWikiWiki() method :colbert:

FieryBalrog
Apr 7, 2010
Grimey Drawer

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.

At the same time, it is a bit annoying that I end up with a bunch of variable, method and class names that literally look like the following:

EquilendSettlementToAutoborrowTransformerConcrete { }
processParsedSharedTradeTicketMessages()
etc.

I do it anyway, but sigh a little inside.

Squashy Nipples posted:

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?

This is terrible (hungarian notation), don't do this. You can literally mouse over the variable in an IDE and know the type instantly, it's a strongly typed language. On top of that my mind would explode if I had to prefix (super long variable name) with (super long class name) every time, it's already bad enough that you have to write:

code:
List<JavaClassNameThatIsWayTooFuckingLongForItsOwnGood> listOfStuff = new ArrayList<JavaClassNameThatIsWayTooFuckingLongForItsOwnGood>();

FieryBalrog fucked around with this message at 17:22 on Oct 7, 2015

ExcessBLarg!
Sep 1, 2001

FieryBalrog posted:

it's already bad enough that you have to write:
You don't as of Java 7. Or Java 6 with Guava (Lists.newArrayList).

FieryBalrog
Apr 7, 2010
Grimey Drawer

Gravity Pike posted:

Arcane generics/inheritance typing question:

Java code:
public class Scratch {
    public static void main(String... args) throws Exception {
        final Generic<Generic<Object>> noExtend = null;
        final Generic<Generic<? extends Object>> doesExtend = null;

        doThing(noExtend); //Generic<Generic<Object>> cannot be converted to Generic<Generic<? extends Object>>
        doThing(doesExtend);
    }

    public static class Generic<T> {};

    public static <T> Object doThing(Generic<Generic<? extends T>> arg1) {
        return null;
    }
}
Why can't List<List<Object>> be converted to List<List<? extends Object>>?

This took me a while to get, but basically I think the reason is this:

(1) List<? extends Object> means a list that can be read as an object but can't be written to as an object
(2) List<Object> can be read or written to as an object
(3) List<List<? extends Object> means a list that can have lists of type (1) written and read to it
(4) List<List<Object> means a list that can have lists of type (2) written and read to it

But type (1) is not type (2) (for compile time purposes, obviously the run-time type is the same.), even if type (1) can be assigned from type (2) (in this case, by removing the ability to write to (1)). Anything you add to a List<Object> is guaranteed to be readable as an object for the case of (1). That's why this is allowed, because (1) is not writeable.

However, (3) is writeable, it's not List<? extends T>, it's List<T>.

If (3) could be assigned from (4), that means you could add an unwriteable list of type (1) to (3) that is not compatible with the contract of (4) which guarantees that the Lists you get from it are writeable and readable (i.e., they are List<Object> and not List<? extends Object>. Or, conversely, it would mean that you couldn't add something of type (1) to (3) even though the contract of (3) specifies that you can.

TLDR: It's the same reason List<Object> can't be assigned from List<String>. If it were allowed, one of the two contracts would have to be violated:
a) you would have to prevent adding stuff to the List<Object> (since this could break List<String>)
or
b) you would have to prevent reading stuff from List<String> (since otherwise you could read a non-String that was added via List<Object>.

However, you can instead do:
(5) List<? extends List<Object>>, because this can be assigned from type 4 in the same fashion that 1 is assigned from 2.

That's why you can do the following:
code:
        List<Object> listObj = new ArrayList<Object>();
        List<? extends Object> listExtendsObj = listObj;
        List<List<Object>> listOfListObj = new ArrayList<List<Object>>();
        
        List<List<? extends Object>> listOfListExtendsObj = listOfListObj; //compile error
        
        List<? extends List<Object>> listExtendsListOfObj = listOfListObj; //no error

	List<Object> o = new ArrayList<String>(); //not allowed for similar reasons

FieryBalrog fucked around with this message at 18:21 on Oct 7, 2015

pepito sanchez
Apr 3, 2004
I'm not mexican
I'm creating a simple card game. A single game can consist of three players, and they all share observers. Once a game reaches three players, the game commences and cards are given to each player in the collection in the UI's game object. Up to here everything is fine. Every player gets his random shuffle of cards from a single game deck object. The UIs share behavior updating the list of players when someone joins or leaves, so observer is working just fine.

The problem I ran into is with rendering cards to each player's separate JFrame. At the moment I'm attempting to solve this with a foreach loop, and setting icons based on the player's hand. However... this only updates the UI of the last player to join.

I'm thinking this might have something to do with a UI having a single game object, and I feel like perhaps I'm missing some link between a player and their individual UI, but I don't want to break separation of logic from presentation, either. Any ideas would be helpful.

This is my method for drawing the icons right now. It only renders to a single game's Frame:

code:
private void renderCards() {
    for (Player p : game.getPlayers()) {
        icoCard1.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(0).getImage())));
        icoCard2.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(1).getImage())));
        icoCard3.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(2).getImage())));
        icoCard4.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(3).getImage())));
        icoCard5.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(4).getImage())));
        icoCard6.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(5).getImage())));
        icoCard7.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(6).getImage())));
    }
}
How can I reference each JFrame's JButton icons separately from each other? I'm still pretty new using Swing, and I have no idea how big or small or a thing I'm not understanding here.

pepito sanchez fucked around with this message at 21:24 on Oct 7, 2015

Polidoro
Jan 5, 2011


Huevo se dice argidia. Argidia!
Aren't you just overwriting the 7 icoCardx for each player?. Just by looking at that fragment of code looks like every player should have it's own set of cards and you should be writing to a player's own set.

That's why it only sets the hand for the last player, because the rest get overwritten by the next one to arrive.

Zaphod42
Sep 13, 2012

If there's anything more important than my ego around, I want it caught and shot now.
Yeah where is icoCard1 defined or where do you get its reference?

You should be assigning a different variable on each loop, not the same variable over and over for each player like Polidoro said.

As for how to access the different panels, well that's gonna depend upon how you set them up.

So its a single application with different frames for each player's cards, so its like a hot-seat type game?

crimedog
Apr 1, 2008

Yo, dog.
You dead, dog.

FieryBalrog posted:

This is terrible (hungarian notation), don't do this. You can literally mouse over the variable in an IDE and know the type instantly, it's a strongly typed language. On top of that my mind would explode if I had to prefix (super long variable name) with (super long class name) every time, it's already bad enough that you have to write:

Is it bad that my variables for Lists always have List at the end?

code:
List<String> lastnameList;

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

crimedog posted:

Is it bad that my variables for Lists always have List at the end?

code:
List<String> lastnameList;

I wouldn't call that egregious, but you could probably get away with List<String> lastNames in that specific case as long as there wasn't something very similar (like a string of space-separated last names that you were converting to a list or something.) It's all about being easy to understand.

pepito sanchez
Apr 3, 2004
I'm not mexican

Zaphod42 posted:


So its a single application with different frames for each player's cards, so its like a hot-seat type game?

it's going to be online. this is just to get observer down. i don't know what hot-seat type game means. and i still have no idea how to get those references to different frames for the players.

e: really, do I have to give each player his own panel with cards or something? bring players to the front-end in a UI class shared with a JPanel? i think i'm just giving up until tomorrow, because i'm feeling really burned out by this.

e2: i don't think i'm explaining myself well enough to anyone i've sought help from. it feels like i'm just doing something fundamentally wrong.

With a login screen the player is simply authorized. He's passed to the shared game screen.

Lots of translating from spanish. Sorry if I missed something:
code:
public class partidaUI extends javax.swing.JFrame implements Observer{

    private Game game;
    private Player player;
    private UIDeck deck = new UIDeck();

public gameUI(Player p) {
        initComponents();
        this.setVisible(true);
        this.setTitle(j.getNombre());
        player = p;
        player.setBalance(player.getBalance() - Config.BET.getValue());
        game = GameFacade.getInstance().getNext(this); //returns game found without enough players or instantiates a new one, adding an observer.
        player.addObs(this); // adding observer to player, then adding him to this game's list of players
        game.addPlayer(player);
        game.setPot(game.getPot() + Config.BET.getValue());
        player.notifyObs(); //setChanged() and notifyObservers(), this just updates the UI for now
        
        waitPlayers();
    }

public void esperarUsuarios(){
        
        if (game.getPlayers().size() == Config.MAXPLAYERS.getValue()) {
            startGame();
        }
    }

public void startGame(){
        
        for (Player p : game.getPlayers()) {
            while(p.getMano().size() < 7){
                p.getHand().add(deck.getACard());
            }
        }
        renderCards();
    }
I hope this is clearer with my intentions? Then the code I posted is called. I guess it must only make sense to dumb me.

pepito sanchez fucked around with this message at 22:31 on Oct 7, 2015

FieryBalrog
Apr 7, 2010
Grimey Drawer

crimedog posted:

Is it bad that my variables for Lists always have List at the end?

code:
List<String> lastnameList;

It's totally fine if it helps you understand what the variable is for...

That's why I think this is pointless:
code:
String strLastName = "Obama";
Integer intDistinctValueCount = 8;
and, by corollary, any rule that requires adding str for String or int for Integer and so on is dumb and pointless and occasionally downright detrimental.

But of course there's a huge number of situations where yeah, the type might be useful in the name because it helps you use the object.
code:
Date currentDate = Calendar.getInstance().getTime();
TradeOrderResponse tradeOrderResponse = new TradeOrderResponse();
Random rand = new Random();
DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd", Locale.ENGLISH);

Polidoro
Jan 5, 2011


Huevo se dice argidia. Argidia!

pepito sanchez posted:

it's going to be online. this is just to get observer down. i don't know what hot-seat type game means. and i still have no idea how to get those references to different frames for the players.

e: really, do I have to give each player his own panel with cards or something? bring players to the front-end in a UI class shared with a JPanel? i think i'm just giving up until tomorrow, because i'm feeling really burned out by this.

I don't know enough about your design to tell you what to do. But from the method you posted I can tell you it'll never work to update the same objects in a loop.
If by it's going to be online you mean you plan to separate it into clients and server in the future you should do that right away to avoid confusion.

pepito sanchez
Apr 3, 2004
I'm not mexican

Polidoro posted:

I don't know enough about your design to tell you what to do. But from the method you posted I can tell you it'll never work to update the same objects in a loop.
If by it's going to be online you mean you plan to separate it into clients and server in the future you should do that right away to avoid confusion.

i can't because i don't know how yet :) it's a learning exercise to keep logic as separate from the UI as possible, to make that transition smoothly on the "online" part of it. i'm thinking of going back to the drawing board on this one. i don't mind.

edit: the game has a collection of players though. it's not just one player object in there i'm looping through. it's really only the "starting the game" part that would loop at all, to deal cards out to each player - and setting their icons - before moving to a first turn. after this it should be easy with a notification method on each dude when he's made a play, or just quit, or anything.

pepito sanchez fucked around with this message at 22:37 on Oct 7, 2015

Zaphod42
Sep 13, 2012

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

pepito sanchez posted:

it's going to be online. this is just to get observer down. i don't know what hot-seat type game means. and i still have no idea how to get those references to different frames for the players.

e: really, do I have to give each player his own panel with cards or something? bring players to the front-end in a UI class shared with a JPanel? i think i'm just giving up until tomorrow, because i'm feeling really burned out by this.

e2: i don't think i'm explaining myself well enough to anyone i've sought help from. it feels like i'm just doing something fundamentally wrong.

I hope this is clearer with my intentions? Then the code I posted is called. I guess it must only make sense to dumb me.

No you're not explaining yourself well enough and yeah, you're probably doing something fundamentally wrong. The problem is we can't judge what's fundamentally wrong from code snippets, we either need you to explain how the program is organized and what its doing, or we need you to just post the entire code on pastebin so we can look at it and tell you "this is wrong" specifically.

Where do you create icoCard1? Where is that reference stored? That's the problem. Those objects are being accessed by renderCards() wrong, but I can't even see in the other code you posted where you create or store those objects, so I can't tell you how to fix renderCards() because I don't even know what you're doing yet.

Zaphod42
Sep 13, 2012

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

pepito sanchez posted:

edit: the game has a collection of players though. it's not just one player object in there i'm looping through. it's really only the "starting the game" part that would loop at all, to deal cards out to each player - and setting their icons - before moving to a first turn. after this it should be easy with a notification method on each dude when he's made a play, or just quit, or anything.

What? :psyduck:

"Its not just one player object there I'm looping through" - Yes you are. That's the problem we're trying to point out for you. That loop appears INTENDED to loop through all players, BUT IT DOES NOT. The code is wrong. It is looping over the same objects over and over and over which does nothing. That's what we're trying to tell you. That is broken. And the way to fix it requires us to understand how you set up your other players.

"Its really only the starting the game part" - What? Who cares? Its broken. You posted:

pepito sanchez posted:

The problem I ran into is with rendering cards to each player's separate JFrame. At the moment I'm attempting to solve this with a foreach loop, and setting icons based on the player's hand. However... this only updates the UI of the last player to join.

How can I reference each JFrame's JButton icons separately from each other? I'm still pretty new using Swing, and I have no idea how big or small or a thing I'm not understanding here.

If it doesn't work it doesn't work and you need to fix it. Who cares if its only the "starting the game part" ?? You asked for help with it, and now you seem to be acting like starting the game works fine and doesn't need to be fixed? which is it?

Squashy Nipples
Aug 18, 2007

FieryBalrog posted:

This is terrible (hungarian notation), don't do this. You can literally mouse over the variable in an IDE and know the type instantly, it's a strongly typed language. On top of that my mind would explode if I had to prefix (super long variable name) with (super long class name) every time, it's already bad enough that you have to write:

code:
List<JavaClassNameThatIsWayTooFuckingLongForItsOwnGood> listOfStuff = new ArrayList<JavaClassNameThatIsWayTooFuckingLongForItsOwnGood>();

Well, for stuff like that, I usually just use "obj" as a prefix. Everything that's not a primitive data type is an Object, right? ;)

(I'm not saying this is the correct way to do it, just that it works for me in the reporting engines I build for work)


So, the kids and I are making a "Guess my Pokemon" game. His original concept was sort of funny, ask the user 7 questions (Region, Type, Egg Type, Ability, and some other poke-poo poo I don't recall) stored in the variables, a b c d e f, of course. And then he made a set of string arrays for the possible answers to each array... and then he said "I'm just going to use nested IF statements to do the logic". :psyduck:

I don't know how man pokemans there are, but I know that even a small number of options by factorial 7 is a HUGE loving NUMBER. I told him we needed to start by making a 2D array, so that at least the different values are related to the correct pokemon .

Squashy Nipples
Aug 18, 2007

If I did want to make a Tic Tac Toe game, what classes do you use for graphical output?

(I'm just looking for some names to start googling, I have zero experience with graphical output that's not in Excel or Powerpoint)

Zaphod42
Sep 13, 2012

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

Squashy Nipples posted:

So, the kids and I are making a "Guess my Pokemon" game. His original concept was sort of funny, ask the user 7 questions (Region, Type, Egg Type, Ability, and some other poke-poo poo I don't recall) stored in the variables, a b c d e f, of course. And then he made a set of string arrays for the possible answers to each array... and then he said "I'm just going to use nested IF statements to do the logic". :psyduck:

I don't know how man pokemans there are, but I know that even a small number of options by factorial 7 is a HUGE loving NUMBER. I told him we needed to start by making a 2D array, so that at least the different values are related to the correct pokemon .

Wouldn't it make more sense for "guess my pokemon" to work the other way around?

Like the computer would tell you region, type, egg type, ability, and other poo poo, and then you'd have to guess "that's picachu!" and it'd be like "nope that's charmander you're wrong".

Like as is, what you described is more like a pokemon lookup, a cheap pokedex. You just punch in region and type and egg type and then it spits out "picachu", where's the guessing in that? I guess you're doing it like that 20 questions bot that guesses what you're thinking of? That's pretty tricky.

Yeah the naive approach is just a ton of nested conditionals but like you said 7! is 5,040 so.... wow.

Luckily another fairly naive approach is much simpler; just store the data for each pokemon as objects, and then do a brute force search through each pokemon to find one that matches all the strings. If you find a match, you stop, if you get through the whole list with no match then you say that one of the fields was wrong or nothing matched those conditions. If you find multiple matches you could pick the first or pick randomly from the matches.

Then if you wanted to improve the performance you could look into more advanced schemes for sorting them based on the fields, indexing them, etc.

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Squashy Nipples posted:

If I did want to make a Tic Tac Toe game, what classes do you use for graphical output?

(I'm just looking for some names to start googling, I have zero experience with graphical output that's not in Excel or Powerpoint)

Swing or JavaFX are GUI libraries and you could probably make a TicTacToe game out of GUI components, but Graphics2D is for the custom drawing. I think JavaFX might have its own custom drawing libraries, but I'm not familiar with it so someone else can talk about that.

Zaphod42
Sep 13, 2012

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

Squashy Nipples posted:

If I did want to make a Tic Tac Toe game, what classes do you use for graphical output?

(I'm just looking for some names to start googling, I have zero experience with graphical output that's not in Excel or Powerpoint)

Honestly I would start by doing Tic Tac Toe using co-ordinates and ASCII output. Its not the most elegant but its nice and simple, and writing a method to print the board can be a little bit of fun work with formatting strings.

So you'd type in where to put the X or O like you were playing battleship, (0,0 or 3,1 or whatever) and then after each input the computer would print the current board state, and then declare a winner when somebody makes three in a row in any angle.

If you want to mess with graphics, there's a lot of libraries. Swing is pretty standard java GUI stuff and you could make a Tic-Tac-Toe game using Swing components if you wanted. Kinda like Visual Basic? Find a nice IDE that lets you use a GUI Designer to save lots of work. (Eclispe and Netbeans can both handle that gracefully)

As for a proper game graphics library, LWJGL (lightweight java game library) is pretty cool, as well as things built on it like LibGDX or Slick.

I make games using LibGDX and its pretty great for doing Mario type stuff, but it might be a bit of a headache to learn all the things to start throwing pixels at the screen, while just doing something in Swing could probably get you going much faster.

Squashy Nipples
Aug 18, 2007

As always, great responses, guys. thank you!

For reference, we are using NetBeans.

Zorro KingOfEngland
May 7, 2008

Zaphod42 posted:

Honestly I would start by doing Tic Tac Toe using co-ordinates and ASCII output. Its not the most elegant but its nice and simple, and writing a method to print the board can be a little bit of fun work with formatting strings.

So you'd type in where to put the X or O like you were playing battleship, (0,0 or 3,1 or whatever) and then after each input the computer would print the current board state, and then declare a winner when somebody makes three in a row in any angle.

This is exactly what we did. If you're not planning on focusing on GUI stuff for the real project it's probably best to keep it simple in that regard. At the very least you can always do graphics output later as an enhancement (just like the real world!)

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

Another thing you could do with your pokeymons is hold a Map for each trait category, and have an entry for each trait (like a Region map and then an entry for each region), and map that to a Set of pokeymons. So you'd have something like

code:
regions
[start town] -> Set(Pikachu, Buttz, Faartz)
[Ice Land]   -> Set(Icehole, Snowjoke)
and do the same for every trait. So whenever you add a new pokemon, you add it to a global Set of all pokemon (if you like), and then add it to the relevant sets depending on the traits it has.

Then when you come to look one up based on filtering by traits, you can use Java's Set operations to work out which pokeymons are common to each set you pull out. You could copy the set of all pokemon and then apply retainAll(setOfIceLandPokemon) to whittle your set down bit by bit, or you could copy the first trait set you pick - which is more optimised but might be harder for your kids to follow if you're teaching them a bit of basic set theory.

Learning to use sets is nice, and doing it this way means you can show them 'live' how the list of pokemon is reduced as they add new filters and shrink the set. You could also use Strings for the key names in the maps, and that way when you list all the possible options for Region, you're just listing the keyset - simplifies your code a bit, so long as it doesn't cause complications if you need those names elsewhere!

Squashy Nipples
Aug 18, 2007

That sounds like a good way to go with future iterations!

OK, organization question:
I built myself a simple function, pass it a Double and get back a formatted string.

I stuck this in my Class below my Main Method, and it works like a charm.

code:
    private static String FormatForLong(double inputNum){
        if (inputNum == (long)inputNum){
            return String.valueOf((int)inputNum);
        } else {
            return String.valueOf(inputNum);
        }
    }
But is it wise to keep all of my functions in a separate class? Why or why not?

If so, how do I call the function from my Main code? I tried putting it into it's own class, but then I get a "cannot find symbol" error.

Do I need to set a reference to the class I'm putting my functions in?

Sedro
Dec 31, 2008
If you move the function to another class, you will have to qualify it, e.g. MyOtherClass.FormatForLong(...). If the other class is in a different package then you will also have to import it.

But you should leave the function where it is. Consider moving the function to another class if it becomes complex enough (say, 20 lines of code) or if you need to call the function from somewhere else.

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 it's in another class, you'll need to qualify it with the class name - OtherClass.formatForLong() or whatever. Because it's a static method you can call it on the class itself (since they belong to the class), otherwise you'd need an actual instance of OtherClass so you can call myOtherClass.formatForLong(). But if you want to call that method from outside that class, you need to change it from private to something the calling class can see.

How you organise it is up to you, other people will probably have some better advice... I think it's fine to keep a basic function in the same class, but having it in its own method is generally Cool and Good for readability and making changes easier. If that function needs to be called from outside, you have a call to make - is it a general utility function, or something tied to the class itself? Does it make sense to have everything use SpecialClass.formatForLong(), or to treat it as more 'unaffiliated'? Is it worth creating a special class or even package for this stuff? Or is it cluttering up your main class to the point where it would be nice to just shift it all out into a separate class for organisational sake?

It's really up to you and what you're doing. I'd recommend just trying it and seeing how it feels - if you get to a point where it all feels too scattered and you're having trouble remembering where things are, you can refactor it and end up with something that feels better. I think there's an art to it, but like I said people might have some more concrete style advice :3:

Squashy Nipples
Aug 18, 2007

No, that's all good, that's pretty much exactly what I wanted to hear.

The only concept I'm a little fuzzy on is what makes a Method "Static". It barked at me and told me to make my Method static, but without that prompt I wouldn't have known to add that keyword.


EDIT:
HOLY CRAP, I'm in love with Refactoring. My code is short at the moment, but it's still a timesaver.

Squashy Nipples fucked around with this message at 00:42 on Oct 10, 2015

Jo
Jan 24, 2005

:allears:
Soiled Meat
Looking for a second opinion. I'm using jBlas for a series of rather intensive matrix operations. I don't need really fancy QR decomposition or SVD, I just need multiplication (element-wise and mat/mat) to be really fast, along with addition, subtraction, transpose, inverse, and, ideally, exp. I could say "gently caress it" and write things in OpenCL, but that might be ill advised because everyone else seems to be just using GPU accelerated matrix libraries. Thoughts?

Fergus Mac Roich
Nov 5, 2008

Soiled Meat

Squashy Nipples posted:

No, that's all good, that's pretty much exactly what I wanted to hear.

The only concept I'm a little fuzzy on is what makes a Method "Static". It barked at me and told me to make my Method static, but without that prompt I wouldn't have known to add that keyword.


EDIT:
HOLY CRAP, I'm in love with Refactoring. My code is short at the moment, but it's still a timesaver.

Static is a special modifier that makes something(method, field, even a class/interface/enum, etc) live in the namespace of a class(, etc) without being attached to a particular instance of that class. So it's the difference between being able to do

code:
int mySuperImportantVariable = UsefulClass.aStaticMethodThatDoesntNeedAnInstance(anotherImportantVariable);
vs
code:
StatefulClass myClassInstance = new StatefulClass(myConfigurationParameters);
int mySuperImportantVariable = myClassInstance.anInstanceMethodMeaningItDoesntHaveStaticInFrontOfIt();
Static should be used judiciously, only in situations where there is no configuration or state being used whatsoever. Math functions like sin() and pow() are good candidates.

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

Squashy Nipples posted:

No, that's all good, that's pretty much exactly what I wanted to hear.

The only concept I'm a little fuzzy on is what makes a Method "Static". It barked at me and told me to make my Method static, but without that prompt I wouldn't have known to add that keyword.

Have a read of this
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

Think of a class as a general template, and instances are the special snowflake objects you create (say with the new keyword) that have their own internal state, like variables you set independently on each one. The class doesn't know anything about the instances you've made from it - it only knows about itself. You can give the class its own variables, by giving them the static keyword. If you change the value of that variable, it changes in the class, because that's the one place it exists.

Instances can see and change those static variables, because they know what class they came from (what their type is) so they have access to the class's details. Again, if an instance changes a static variable, it changes in the class and everything will see that change, because it's happening in one place. Non-static variables are created in the instance itself, so they each get their own independent version, and the class can't see them (because it doesn't know about the instances). So if you want to look at or change an instance's variables, you need to go through the instance itself - like referencing them directly (myObject.favourite = "bananas") or through a method on that object that does something internally (myObject.setFavourite("bananas"))

So if a method is going to implicitly refer to something in an instance's internal state, you have to call the method on an actual instance. You can't call it on the class because it doesn't have that state to work with. But if your method doesn't actually work with any instance state, and is completely agnostic about instances, you can make it a static method and call it on the class instead. Like your formatForLong() method, it just takes in *a number* and does some stuff with it and spits out *a result*. It doesn't relate to an instance of your class at all, so you can treat it as a general utility on the class itself. You can call it on an instance if you like, but if you call it from outside (like myObject.formatForLong(100)) your IDE will probably complain that you should call it on the class and be more general about it.

Static methods can work with instances and their state variables, but you have to pass them in so it can work with them internally. It can't reference anything outside itself, because it doesn't know what instance it's being called from - static methods are part of the class, they only know about the class and its static variables. Anything else needs to be handed to it explicitly.

I hope that wasn't horribly confusing... I took a few liberties with the technical details :v:

FieryBalrog
Apr 7, 2010
Grimey Drawer

pepito sanchez posted:

code:
private void renderCards() {
    for (Player p : game.getPlayers()) {
        icoCard1.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(0).getImage())));
        icoCard2.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(1).getImage())));
        icoCard3.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(2).getImage())));
        icoCard4.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(3).getImage())));
        icoCard5.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(4).getImage())));
        icoCard6.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(5).getImage())));
        icoCard7.setIcon(new ImageIcon(getClass().getResource(p.getHand().get(6).getImage())));
    }
}

pepito sanchez posted:

The problem I ran into is with rendering cards to each player's separate JFrame. At the moment I'm attempting to solve this with a foreach loop, and setting icons based on the player's hand. However... this only updates the UI of the last player to join.

I don't know anything about Swing at all, but it looks like you're overwriting the same objects for each player... That would perfectly explain why only the last player gets UI updated.

code:
Integer[] intArray = new Integer[] {1,2,3,4};
List<Integer> integers = Arrays.asList(intArray);
String s = null;

for (Integer i : integers) {
  s = i.toString();
}
System.out.println("s: " + s);
What do you think the value of the string will be...

Squashy Nipples
Aug 18, 2007

baka kaba posted:

Have a read of this
https://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html

...

I hope that wasn't horribly confusing... I took a few liberties with the technical details :v:

Ah, I hadn't gotten that far in the trail.
But your answer was better, anyway.

One last question: early on, the tutorial makes this statement

quote:

Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming.

But what I just read is:

quote:

•public modifier—the field is accessible from all classes.
•private modifier—the field is accessible only within its own class.

In the spirit of encapsulation, it is common to make fields private.

So which is it? Is Encapsulation is optional or mandatory?

carry on then
Jul 10, 2010

by VideoGames

(and can't post for 10 years!)

Squashy Nipples posted:

Ah, I hadn't gotten that far in the trail.
But your answer was better, anyway.

One last question: early on, the tutorial makes this statement


But what I just read is:


So which is it? Is Encapsulation is optional or mandatory?

Strongly encouraged.

e: there are reasons to make certain fields public (usually in conjunction with final to make them read-only.) But the default pattern you should look to do is private fields with accessors. This has the added benefit of allowing you to do things behind the scenes if you need to, such as transforming a value or notifying an object when the value is changed.

carry on then fucked around with this message at 17:56 on Oct 10, 2015

Adbot
ADBOT LOVES YOU

FateFree
Nov 14, 2003

Squashy Nipples posted:

Ah, I hadn't gotten that far in the trail.
But your answer was better, anyway.

One last question: early on, the tutorial makes this statement


But what I just read is:


So which is it? Is Encapsulation is optional or mandatory?

Think about driving a car. You don't know or care how an engine works, all you know is theres a go pedal and a stop pedal and a steery wheel. Thats the interface to driving any car, gas, electric, whatever. Hiding complexity makes something easy to use and easy to understand. You want to take these concepts and apply them to code so that the classes you write are easy to use and easy to understand. If something doesn't need to be public, don't make it public. The entire goal of all this is to reduce complexity to make code easier to understand by you, and whoever else uses it.

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