How do I allow two players to play at once using only one keyboard?

I tried recreating pong and it went pretty well … except the part where you actually play the game.

It doesn’t work with keyPressed() because I would need at least two instances of the key variable running at the same time, since i want the two players to be able to press and use multiple keys at the same time.

//yrect and yrect2 are the y positions of the two players
//rectspeed is the rate at which the players move along the y axis when a key is pressed

//controls for player 1
void control()
{
  keyPressed();
  
  if (keyPressed&&keyCode==UP)  
  {
    yrect2-=rectspeed;
  } 

  if (keyPressed&&keyCode==DOWN) 
  {
    yrect2+=rectspeed;
  }
  
}
//controls for player 2
void control2()
{
  keyPressed();
  if (keyPressed&&keyCode==SHIFT)  
  {
    yrect-=rectspeed;
  } 

  if (keyPressed&&keyCode==CONTROL) 
  {
    yrect+=rectspeed;
  }
  
}

So I answered a question kind of similar to this, and well this is what I would personally do when it comes to handling multiple key presses. The only problem in your case, is that I do not know necessarily how many maximum keys will be pressed at one time, so you would have to work that out (and we could help out of course if need be).

The question is here:

And maybe you can take a look at that and see if it works? Now, as far as I know, technically you can’t really expect for two players to be able to play at the same time. I have made a two player pong game before, and had one player use the keyboard and the other uses the mouse. There might be a way to use two separate keyboards and switch between them but that’s just me being hypothetical :smiley: As far as I know, it’s not ideal trying to get two players to use the same keyboard.

Hopefully that helps,

EnhancedLoop7

2 Likes

i actually started off by controlling the rectangle with the a mouse but since i wanted to make a two player version of this, i thought it would be a good idea if both players had equal opportunity. Now that i think about it though, I could buy an arduino and set up two potentiometers,one for each player.
Just like this guy did:

I don’t think I’ll be trying to do this on a keyboard anymore, but still, thanks for the help ^-^

Shameless self-promotion: check out the “handling multiple key presses” section of this tutorial:

Basically, you want to create your own variables that track the keys, then set them in the keyPressed() and keyReleased() functions.

1 Like

That’s great! And an awesome solution :smiley:

1 Like