#Multi-Threading Needed :3

1 messages ยท Page 1 of 1 (latest)

spring jayBOT
#

<@&987246399047479336> please have a look, thanks.

#

While you are waiting for getting help, here are some tips to improve your experience:

Code is much easier to read if posted with syntax highlighting and proper formatting.

If nobody is calling back, that usually means that your question was not well asked and hence nobody feels confident enough answering. Try to use your time to elaborate, provide details, context, more code, examples and maybe some screenshots. With enough info, someone knows the answer for sure.

Don't forget to close your thread using the command </help-thread close:1027500463647621170> when your question has been answered, thanks.

#

Here is an AI assisted attempt to answer your question ๐Ÿค–. Maybe it helps! In any case, a human is on the way ๐Ÿ‘. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.

#

cards. I need to implement multi-threading in my game to handle the following tasks concurrently:

  1. Distributing the cards: Each player should receive their cards from their respective deck. This task can be done concurrently for all players.

  2. Playing the game: Each player should be able to play their turn simultaneously. This includes choosing a card to play and updating the game state accordingly.

  3. Checking for a winner: After each turn, the game should check if any player has won by having all four cards of the same rank.

To implement multi-threading in your game, you can use Java's ExecutorService and Callable interface. Here's a possible approach:

  1. Create a class Player that implements the Callable interface. The call() method will handle distributing cards and playing turns for each player.

  2. In your main class, create an instance of ExecutorService using Executors.newFixedThreadPool(numOfPlayers). This will create a thread pool with a fixed number of threads equal to the number of players.

#
  1. Create a list of Player objects, one for each player in your game.

  2. Submit all players to the thread pool using executorService.submit(player). This will start executing each player's task concurrently.

  3. Implement the logic for distributing cards inside the call() method of the Player class. You can use synchronization mechanisms like locks or semaphores to ensure that each player receives their cards from their respective deck without conflicts.

  4. Implement the logic for playing turns inside the call() method as well. Each player should choose a card to play and update the game state accordingly using synchronization mechanisms if necessary.

  5. After each turn, check if any player has won by having all four cards of the same rank.

  6. Once all players have finished playing their turns, call executorService.shutdown() to gracefully shut down the thread pool.

By implementing multi-threading in your game, you can distribute cards, play turns, and check for a winner concurrently, making the game more efficient and responsive.

glacial plover
#

I guess start with ChatGPTs suggestion?

next jay
#

imma be real with you, i have

#

not helpful tbh

#

i implemented some of the changes but the issue still was there

dense stream
#

show your code please

next jay
spring jayBOT
next jay
# dense stream show your code please

im really not sure what im missing tbh, i added synchronized to both draw and discard so im confused why its not working. I didnt output that "notify player x that player y has won "
next line
"play x exit" but i doubt its helpful

dense stream
#

@next jay so first off, why are Deck and CardGame Threads ?

next jay
dense stream
#

?

#

you never start any Deck or CardGame

next jay
#

yeah , look at the end of cardgame, i ran all the threads

#

player.start()

dense stream
#

that's Player

#

you never start Deck or CardGame

next jay
#

oh

dense stream
#

yet they extend Thread

next jay
#

yeah but i need to synchronize the add and discard functions in deck

dense stream
#

it doesn't matter

#

if you never call start

#

then they shouldn't be threads

next jay
#

is that the problem?

dense stream
#

Don't know

#

but that's a problem for sure

next jay
#

i assumed i had to synchronize addcard() and removecard() in deck

dense stream
#

I am struggling to see how is this game supposed to work

next jay
#

oh

dense stream
#

so what are the rules ?

next jay
#

basically, player form a ring topology right , every player will draw from their left deck to their hand.
and discard from their hadn to their right deck when its not a preffered card number (player 1 wants card1's , player 2 will want card 2's)

#

each player is inbetween 2 decks

dense stream
#

form a ring topology right

#

wdym

#

is it turn based ?

next jay
#

round robin fasahion

dense stream
#

๐Ÿค”

next jay
#

ah

dense stream
#

is it turn based ?

next jay
#

well its concurrent so no

#

maybe

dense stream
#

it's yes or no

next jay
#

no

dense stream
#

so from what I understand

#

a player will draw from left deck

#

and put on right deck

#

then do it again

next jay
#

not they will put it in his hand

dense stream
#

I mean

#

they will draw one card from left deck, put another card on right deck

next jay
#

and when they have a card that isnt what they want, its discarded to deck on the right

dense stream
#

and how many times do they do that ?

next jay
#

until winner

dense stream
#

which is ?

#

when ?

next jay
#

4 cards same with the same value of the playerNumber

#

so player 1 = 1,1,1,1 WIN

dense stream
#

ah I see

#

so

next jay
#

yeah

#

took me a while to understand lol

dense stream
#

can a player draw a card from left deck, put it on right deck, then do that 10 times before the left player has time to do it once ?

next jay
#

nope , left deck -> **hand **, then **hand **-> *right hand *only

dense stream
#

huh

#

use ``

next jay
#

?

dense stream
next jay
#

draw from left deck to players hand , discard a card from hand to right deck

dense stream
#

yes

#

but I am asking

#

can you do that 10 times while another player did it only once ?

next jay
#

nope

dense stream
#

so it's turn based ?

next jay
#

well

#

yeah youre right

#

i apologize

dense stream
#

then using threads don't make any sense

next jay
#

how so?

dense stream
next jay
#

hmm

#

good point

#

thank you good sir

dense stream
#

also

#

I wont fix the threads since well, you will delete them anyway

#

but I'll fix the rest

#

hmm

#

which version of java are you using ?

#

and is this an assignment ?

#

@next jay

next jay
#

hi no its okay bro , i really appreciate the help but i was just stuck on the threading part thisisfine

dense stream
#
                stream.forEach(line ->{
                    Card card = new Card(Integer.parseInt(line));
                    pack.add(card);
                });

This is a bad use of a stream, you should do

pack.addAll(stream.map(line -> new Card(Integer.parseInt(line)).toList());
#

actually

#

this whole loop can be simplified

next jay
#

how so>

dense stream
#

like you are reading the file twice for no reason

#

not only that

#

but the first time, you are using a good approach of Files.lines, but the second time you are manually reading it with a BufferedReader ???

next jay
#

yeah i need to change a bunch of stuff lmao

dense stream
#

Also, don't hide exceptions

#

and don't catch it just because java told you to

#

there is a reason for why java asks you this

#

it's not just catching for the sake of catching

#

if the exception is fatal ie the program cannot work if it happens, then you should rethrow it as an unchecked exception

next jay
#

im a little baby right now

#

but one day

#

ill make it

dense stream
#
    public void initualiseFile(){
        File file = new File(fileName);
        try{
            file.createNewFile();
        } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
        }
        //Clears contents of file
        try{
            FileWriter writer = new FileWriter(fileName);
            BufferedWriter buffwriter= new BufferedWriter(writer);
            buffwriter.write("");
            buffwriter.close();
        }catch(IOException e){
            e.printStackTrace();
        }
        

    }

Like this one, if you get an exception here, pretty sure the only option is to crash

#

speaking of this

#

please don't use File

#

use Files and Path, you used it above, so you should know it

#

and

#

you just used Files and Path

#

why are you using FileWrriter ???

#

and you just used a try-with-resources above, why are you then using a regular try + manually closing ? you are not even closing correctly, there is a leak

#

same for all the other place without a try-with-resources

next jay
#

ah i did not know that

dense stream
#

you didn't know what ?

#

also

#

Don't create a random each time

#

it's not really random then

next jay
#

okay

dense stream
#

and you are abusing syncronized and notify, no way it would work, but since you will get rid of the thread, then you will get rid of that anyway

#

and, also

#

don't write to a file at each turn

#

I mean

#

why can't you write when it's over ?

#

and a method called result() should write to a file

#

and don't omit @Override when you override

next jay
#

okay sir

dense stream
#
    private static int numOfPlayers;
    //private static String filePath;

    public InputPackValidator(int numOfPlayers/* , String filepath*/){
        this.numOfPlayers=numOfPlayers;
        //this.filePath=filepath;
    }

shouldn't be static

next jay
#

just private?

dense stream
#

yes

#

but

#

this class should be deleted anyway

dense stream
#
        String str="";
        for(Card card : deckContents){
            str=str+Integer.toString(card.getValue())+" ";
        }

        return str;

use a StringBuilder, StringJoiner or Stream here

next jay
#

will do

dense stream
#
        for(Player player : playerList){
            player.initualHand();
            if (player.isWinningHand()){
                System.out.println("Game Over");
                player.result();

                break;
            }
         // Threads started //
            player.start();
        
        }

Also, how is the game supposed to be over before it even started ?

#

i think that's all