Menu, Anyone?

Today I added some menu buttons with a cool-ish wiggle affect when they get clicked.

This commit is a bit complicated, but essentially I added four menu buttons that you can click on. When you do click on one, it wiggles before the screen goes to that option. If you “hover” over a button, then it gets bigger. These are a few things that I believe would be needed for any game, so I was adamant to include them here.

Consider this, in any game you play, a button may be there, but dimmed out because it is not available. Or perhaps it will toggle to a different color or shape. These are pretty important things in a game’s arsenal, so I wanted to work with and on them here.

I wont bore you with all the code, but you can check out my GitLab for all the details. However, earlier, when making the water drum bobble, I said that I could have just made a separate sprite for the different halves of the drum, and moved the top half instead of making separate sprites to show the motion. Well, to put that to practice, I did that here with these buttons.

Watch what happens when you click one:

if (m_Active) {

// Since the button was pressed, let’s do some motion!
m_Motion = m_Motion + elapsedTime;
float motionCount = m_Motion;

if (motionCount == 1) {
m_Position.x = m_Position.x + 2.5;
m_Position.y = m_Position.y + 2.5;
m_Sprite.setPosition(m_Position);
} else if (motionCount <= .15) {
m_Position.x = m_Position.x + 2.5;
m_Position.y = m_Position.y + 2.5;
m_Sprite.setPosition(m_Position);
} else if (motionCount <= .30) {
m_Position.x = m_Position.x – 5.0;
m_Position.y = m_Position.y – 5.0;
m_Sprite.setPosition(m_Position);
} else if (motionCount <= .45) {
m_Position.x = m_Position.x + 5.0;
m_Position.y = m_Position.y;
m_Sprite.setPosition(m_Position);
} else if (motionCount <= .60) {
m_Position.x = m_Position.x – 5.0;
m_Position.y = m_Position.y + 5.0;
m_Sprite.setPosition(m_Position);
} else if (motionCount <= .75) {
m_Position.x = m_Position.x + 2.5;
m_Position.y = m_Position.y + 2.5;
m_Sprite.setPosition(m_Position);
} else if (motionCount <= .90) {
m_Position.x = m_Position.x;
m_Position.y = m_Position.y -5.0;
m_Sprite.setPosition(m_Position);
} else {
m_Position.x = m_Position.x;
m_Position.y = m_Position.y;
m_Sprite.setPosition(m_Position);
}
} else {

// What else do we need to do with this?
}

As you can see, I am using the accumulative time (given in fractions of seconds, sent every frame) to control the direction and movement of the button. As it sits now, the button goes up and right, down and left, to the right, up and left, down, and then back to center before it is done with it’s “pressed” function. You could make this random, or what every you like, I just kept it simple with a set pattern.

Interesting to note, the button doesn’t always end up perfectly back at the start this way. Why is that? Well, because every frame may take different lengths of time, it may do more frames in the up and to the right section than the number of frames it takes for the down and to the left section.

A good clean up for this would be to set the button back to it’s original position when done, rather than letting it end where it was. However, after clicking the button, the screen changes, so I didn’t need to worry about that.

Be sure to check out the game! Freestyle is more or less playable at present. Just drumming around!

Linux – keep it simple.

Advertisements

SFML error: ‘string’ was not declared in this scope

2018-06-11-115438_1280x1024_scrot

In the memory game, a large right hand gives you a demo of the drum order for the round.

Work continues on my water drumming game. I’ve been learning a lot by creating this game, which was outside of the scope and tutorials found in my beginner C++ class. I’m pretty sure that my code looks as ugly as the artwork, but it is functional, which is a great feeling!

One error that I ran into confused me for a bit:

DrumGame.cpp:130:5: error: ‘string’ was not declared in this scope
string demoMode = “”;

But I have used string before and had no issues. Specifically, it came down to the fact that I’m using sfml. For some reason, there is a sf::String, and std::string. Notice the capitalization. According to SFML’s documentation:

Utility string class that automatically handles conversions between types and encodings.

sf::String is a utility string class defined mainly for convenience.

It is a Unicode string (implemented using UTF-32), thus it can store any character in the world (European, Chinese, Arabic, Hebrew, etc.).

It automatically handles conversions from/to ANSI and wide strings, so that you can work with standard string classes and still be compatible with functions taking a sf::String.

So, you either need to use String, so you can use SFML’s String, or you need to append std:: to the front of string so you can used the standard string.

Either way, the latest commit is up, where you can select “memory” from the menu, and it will demonstrate the pattern you need to repeat. Right now, since you can’t play back the pattern by clicking, it only shows you the pattern of one. The idea is once you complete that pattern, it adds another drum to your pattern for you to play next.

Stay tuned for part 2 where I will *hopefully* finish the memory mode.

Linux – keep it simple.

Some Wobble To Your Bobble?

In the continuing efforts to make a fun game that tests my (very limited and basic) skills as a C++ programmer, as well as to further the bounds of SFML, I am expanding the Water Drum Game. You should check out my latest commit to see how I put some wobble into the water drum bobble!

wiggle_drum

The overall code is fairly simple, but comes in two main parts. Here is some relevant code from the WaterDrum.cpp:

void WaterDrum::update(bool stillActive, float elapsedTime, float sResolution) {

if (stillActive) {

m_Motion = m_Motion + elapsedTime;
float motionCount = m_Motion;

// Update the sprite if struck.
if (motionCount == 1.75) {
m_Sprite = Sprite(TextureHolder::GetTexture(
“graphics/waterdrum_still.png”));
} else if (motionCount <= .25) {
m_Sprite = Sprite(TextureHolder::GetTexture(
“graphics/waterdrum_1.png”));
} else if (motionCount <= .5) {
m_Sprite = Sprite(TextureHolder::GetTexture(
“graphics/waterdrum_2.png”));
} else if (motionCount <= .75) {
m_Sprite = Sprite(TextureHolder::GetTexture(
“graphics/waterdrum_3.png”));
} else if (motionCount <= 1) {
m_Sprite = Sprite(TextureHolder::GetTexture(
“graphics/waterdrum_4.png”));
} else if (motionCount <= 1.25) {
m_Sprite = Sprite(TextureHolder::GetTexture(
“graphics/waterdrum_5.png”));
} else if (motionCount <= 1.5) {
m_Sprite = Sprite(TextureHolder::GetTexture(
“graphics/waterdrum_6.png”));
} else {
m_Sprite = Sprite(TextureHolder::GetTexture(
“graphics/waterdrum_still.png”));
}
} else {
m_Sprite.setTexture(TextureHolder::GetTexture(
“graphics/waterdrum_still.png”));

}

if (m_Motion >= 1.75)
{
m_Motion = 0;
m_Active = false;
}

// Apperantly we have to update the scale when we change the sprite.
m_Sprite.setScale((sResolution*.2)/500,(sResolution*.2)/500);
m_Sprite.setPosition(m_Position);

 

}

And here is the part where we call it in the DrumGame.cpp:

for (int i = 0; i < numDrums; i++) {
waterDrums[i].update(waterDrums[i].isActive(), dtAsSeconds, resolution.x);
}

As long as the window is open, on every pass of code, it will run this for loop to check and update every water drum. It passes three variables:

  1. isActive: This was set to true for each drum when it was “struck” or clicked on. After it is done “bobbling” it will be set to false.
  2. dtAsSeconds: This is a value of a fraction of a second that it took to run the code between frames. This is really important for making a realistic “flowing” graphic.
  3. resolution.x: This value is used to send the screen size x variable, so calculations can be made for scaling the art of each sequence of drum.

Once those variables are received, there are two options for the code. If it is active, then it will calculate the “bobble” by adding the time elapsed together. At designated times (which I could arbitrarily set to anything I want) the different phases of the bobble happen by replacing the graphic with another. I have decided that after being struck the water drum should bobble for 1.75 seconds total. During that time, 6 different art frames are used for the drum to create the bobble.

Note: I could have changed this to be movement of position as well, having a separate graphic for the outer and inner bowls of the drum. It could have been random as well as including different scaling to adjust the size of it. I felt this was easier, since our textureHolder class is keeping the drums in memory, we only have to load them once, and then “swap” them into these useful spots as required, but either would have worked, I think.

Once the time is up, the game sets the visual back to the still view and sets the motion time back to zero, as well as the active flag back to false. Now it is ready to start the process over.

Notice that the code for striking the drum starts this process over, not adding time in an accumulative fashion. This prevents a “forever” bobble of 15 seconds if you were to strike the drum 10 times in two seconds. It only bobbles from the last strike, so it will only bobble a maximum of 1.75 seconds after the last strike.

Either way, it is now semi-playable in a free play mode, so you are free to check it out on GitLab!

Linux – keep it simple.

Bluetooth Breakdown?

So, in the continuing saga of learning about Bluetooth, I am breaking down some transmissions of Bluetooth signal from my Android phone to the Bluetooth auto start that I built.

btauto

  1. On my Android phone, I went to Settings -> Developer Options -> Enable Bluetooth HCI snoop log. Now my Android phone was creating a dump file on the sdcard of all Bluetooth traffic.
  2. I opened my app, connected to the auto start, and promptly started the truck, and shut it down. Then I waited about 3 seconds, started the truck, and shut it down. Then I disconnected and reconnected 4 times to the auto start.
  3. I turned off the Bluetooth snoop log and then transferred the file to my computer for analysis.
  4. Finally, I opened the file with WireShark, and started reviewing the packets.

From what I understand, the ATT protocol is one that sends and receives actual commands to and from the controlling application to the BLE board itself. So, I sorted the output and looked specifically at the ATT protocol packets.

Further research has lead me to believe that I need to look for btatt.opcode, particularly 0x52, which is for the write command. I found 8 packets that held this special designation.

btauto1

In these packets are values. In order of appearance, they are:

21:42:31:31:3a
21:42:31:30:3b
21:42:32:31:39
21:42:32:30:3a
21:42:31:31:3a
21:42:31:30:3b
21:42:32:31:39
21:42:32:30:3a

Which would correspond to my bluetooth device code of:

// Buttons
if (packetbuffer[1] == ‘B’) {
uint8_t buttnum = packetbuffer[2] – ‘0’;
boolean pressed = packetbuffer[3] – ‘0’;
Serial.print (“Button “); Serial.print(buttnum);
if (pressed) {
Serial.println(” pressed”);
//bluart.print(“pressed”);
analogWrite(19, 50);
} else {
Serial.println(” released”);
analogWrite(19, 0);
}
if (buttnum == 1) {
// Turn on vehicle, by turning on accessory, fuel pump,
// and start timer to crank.
digitalWrite(7, LOW);
digitalWrite(16, HIGH);
startTimer = 5; // Delay time before cranking.
startAttempts = 3; // Number of tries to start.
} else if (buttnum == 2) {
// Turn everything off from the button.
digitalWrite(16, LOW);
digitalWrite(15, LOW);
digitalWrite(7, HIGH);
digitalWrite(11, HIGH);
crankTimer = -1;
startTimer = -1;
runTimer = -1;
startAttempts = -1;
Serial.println(” Kill All – Button pressed. “);
}
}

That’s right! Now we can interpret the signals!

21:42:31:31:3a – Button 1 pressed!
21:42:31:30:3b – Button 1 released!
21:42:32:31:39 – Button 2 pressed!
21:42:32:30:3a – Button 2 released!

That’s great! Now we can use a low level tool like gatt to send the command itself, without the whole interface! Now I just need to implement it!

Linux – keep it simple.

Water Drums With Sound!

If you take a look at my latest commit to the Water Drum Game, you’ll see that I added a few features! Notably, when in free play mode, the drums now make noise. Not only that, but they also “bobble” a little.

drumming

Hard to tell in this photo, but the middle water drum is pressed in.

The code for sound was rather easy, it goes like this:

if (hasDrummed) {

for (int i = 0; i < numDrums; i++) {

if (waterDrums[i].getPosition().contains
(mouseWorldPosition)) {

switch (i) {
case 4:
drumFive.play();
break;

case 3:
drumFour.play();
break;

case 2:
drumThree.play();
break;

case 1:
drumTwo.play();
break;

default:
drumOne.play();
break;
}

hasDrummed = false;
acceptInput = false;
waterDrums[i].struck();

}

}

}

Earlier in the code, the “hasDrummed” bool is set to true when you click the mouse left button. So, in this code, it checks to see if the mouse pointer was inside the sprite for each of the water drums. If the mouse pointer is inside one of the water drums, it uses that drum number to play the appropriate sound. Remember, while there are 5 drums, they are labeled 0-4, since 0 counts as the first number.

As an aside, since the catch all, or default, is drum one sounds, the number of drums is scale-able, but it would mean all extra drums just have the same sound as the first drum.

The code for the drums to “bobble” were a bit more complex. But, I plan to update that and add more “bobble” motions in another commit and cover it specifically in another post.

Linux – keep it simple.

Foray into Bluetooth Programming through C and C++

alaskalinuxuser@alaskalinuxuser-OptiPlex-7010:~/Documents/c++/bluetooth/cbluez$ ./simplescan
FC:58:FA:08:72:E4 CANZ
alaskalinuxuser@alaskalinuxuser-OptiPlex-7010:~/Documents/c++/bluetooth/cbluez$ ./simplescan
FC:58:FA:08:72:E4 CANZ
alaskalinuxuser@alaskalinuxuser-OptiPlex-7010:~/Documents/c++/bluetooth/cbluez$ ./simplescan
00:00:00:00:5A:AD bacon
FC:58:FA:08:72:E4 CANZ
alaskalinuxuser@alaskalinuxuser-OptiPlex-7010:~/Documents/c++/bluetooth/cbluez$

That was the terminal output from the program “simplescan”, which I got from an instructive how to guide. The program itself is rather straight forward, like so:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>

int main(int argc, char **argv)
{
inquiry_info *ii = NULL;
int max_rsp, num_rsp;
int dev_id, sock, len, flags;
int i;
char addr[19] = { 0 };
char name[248] = { 0 };

dev_id = hci_get_route(NULL);
sock = hci_open_dev( dev_id );
if (dev_id < 0 || sock < 0) {
perror(“opening socket”);
exit(1);
}

len = 8;
max_rsp = 255;
flags = IREQ_CACHE_FLUSH;
ii = (inquiry_info*)malloc(max_rsp * sizeof(inquiry_info));

num_rsp = hci_inquiry(dev_id, len, max_rsp, NULL, &ii, flags);
if( num_rsp < 0 ) perror(“hci_inquiry”);

for (i = 0; i < num_rsp; i++) {
ba2str(&(ii+i)->bdaddr, addr);
memset(name, 0, sizeof(name));
if (hci_read_remote_name(sock, &(ii+i)->bdaddr, sizeof(name),
name, 0) < 0)
strcpy(name, “[unknown]”);
printf(“%s %s\n”, addr, name);
}

free( ii );
close( sock );
return 0;
}

But I did run into an error when I executed it. Turns out, I needed to install a few libraries:

# apt-get install libbluetooth-dev

Once that was installed, the #include files could then be found. How people get so smart to put this stuff together is beyond me! But I was rather impressed. My goal is to write an app for my Ubuntu Touch phone that will control my home-made Bluetooth auto start that I put together. I already created the Android app, but now I need something for my UT phone.

simplescan

The problem is, I don’t know anything about Bluetooth from a C or C++ programming standpoint, so I am trying to learn about it by working through various guides and simple tutorials like the one above. I’m hoping to learn a lot, and really looking forward to the adventure!

Linux – keep it simple.

Water Drum Spawning?

Spawning in games is a term you usually hear for power ups, zombies, or player/characters. It is not usually a term that you hear for water drums… until now! In my latest commit for the water drum game, where I decided to make it possible to “spawn” new water drums.

wd2

Essentially, I wasn’t sure that there would always only be 5 drums, and at this early stage, it is pretty easy to write in the ability to add more drums later. Since I only have 5 water drum sounds, I thought I could write some code that would divide the number of the drum you are playing and determine which of the 5 sounds should be used for it. We’ll see how that works out!

Here’s the important part of the commit, if you don’t have time to read it in full:

delete[] waterDrums;

waterDrums = new WaterDrum[numDrums];

for (int i = 0; i < numDrums; i++) {

float y = resolution.y/7*2;

if (i%2){

y = resolution.y/7*4;

}

// Spawn the new water drum into the array

waterDrums[i].spawn(resolution.x/7*(i+1), y, i);

}

Right now, I’m working on drumming up a storm!

Linux – keep it simple.

Water drums with big hands?

hand

Okay, so the post title does sound a little weird. But it’s not. Actually, it’s really simple. What is the biggest problem with designing video games? For me personally, it is making sure that it looks exactly the way you want it too on any sized screen.

In my new water drum game, I’ve drawn a cool little hand for the mouse cursor. It is 200 x 200 pixels. On my 1280×1024 screen, that seems appropriate for this game. However, when I want to show it to my buddy who only has a 1920×1600, the size of the hand becomes disproportionately smaller than it was on my screen. On his screen it is only 1.3% of the screen size, but on mine it is doubled at 2.8% of the screen size.

What if someone tried to play the game on a 640×480 screen? Well, aside from consoling them for having such a tiny, poor resolution screen, the game could actually get a bit difficult to play as the mouse pointer would take up nearly 14%  (almost 1/6th) of the screen! What can you do? Then your game would have to be purposely designed for each screen size.

There are several options.

  1. Purposely build and distribute the game for a set screen size. You would then need to name that size as a dependency of minimum resolution, and use a window for larger screens.
  2. Build your game to check for common screen resolutions, and have multiple artwork and if/then statements to check which ones to use. (I’ve done this in the past with some Android games.)
  3. Write code to scale your images to be appropriate for the screen resolution.
  4. Some combination of the above. (My Dad always picked “D – all of the above” if it was an option, so I’m putting it in here.)

Each of these has drawbacks as well as perks. If you do the first choice, your game will look absolutely best on that resolution. This can be limiting to those with lower res systems, or will limit you to make a low res game that will look bad or tiny on hi res systems if in a window.

If you do the second, you will increase the size of your application by including bigger and better art for each resolution. Also, this gets tedious. What if you change the player icon? You now have to change it 18 times to support the change across each resolution, because currently there are 18 different “HD” resolutions. Not to mention lower res systems, which you probably just wont support anyways.

If you try the third, that of code to scale your graphics, it will always look proportional on any resolution. However, scaling may make the art look pixelated or stretched if scaled too far. Generally, this is the easiest, but may cause graphical quality problems.

I tend to think that most big games (at least on Android) use a combination of both. You select a few common screen sizes and make art for those, scaling anything in between with the closest matching resolution art.

What did I choose? Well, I chose to scale my art. I’m not too worried about quality of the art, since I drew it in a few minutes with pretty low quality to begin with. Here’s how I set the scale:

// Hide the mouse pointer and replace it with drum hand
window.setMouseCursorVisible(false);
Texture textureDrumHand;
textureDrumHand.loadFromFile(“graphics/hand.png”);
Sprite spriteDrumHand;
spriteDrumHand.setTexture(textureDrumHand);
spriteDrumHand.setOrigin(100, 100);
spriteDrumHand.setScale((resolution.x*.04)/200,(resolution.x*.04)/200);

By making the size of the hand a math problem derived from the resolution, it *should* be right on different sized screens. In theory, it should always be about 4% of the screen width. It is 4% of screen width divided by 200 (the size of the png file), which will make the scale, which is multiplied by the actual size of the png file. Mathematically, that means we can take out the divide by 200 and multiply by 200, so it will remain as 4% of the screen resolution!

Similarly, I did the same for the water drums themselves, except I want them to be 20% of the screen resolution width:

// And the water drums themselves.
Sprite spriteWD1;
spriteWD1.setTexture(textureWaterDrum_still);
spriteWD1.setPosition(resolution.x/15*2,resolution.y/7*2);
spriteWD1.setScale((resolution.x*.2)/500,(resolution.x*.2)/500);

Again, the formula is simple: (resolution.x * {desired percentage}) / {original art size in pixels}. This way it will always be a uniform size no mater what screen resolution you use!

You can check out the full commit on my GitLab if you like!

Linux – keep it simple.

C++ and water drums….

Two things that probably don’t sound like they go together. Unless, of course, you are making a video game where you play water drums and it is written in C++.

wd1

So far, there’s not much to this game. I’m really just getting started. While I don’t anticipate this game being a box office hit, I do hope that it will be fun. For the most part, this simple game is serving the purpose of allowing me to “double check” my C++ course skills.

While enrolled in the C++ basic game making course, both games were served with numerous examples of how to do each step. While I strove to make the games my own, there is always that nagging feeling in the back of my mind that I am simply copying the instructors work. This app helps to circumvent that by allowing me to build this entire game from the ground up, without any real examples to draw from.

So, the premise of the game is that there will be two distinct modes that allow you to play with water drums:

  1. Free play mode – While in free play mode, you can simply use the mouse cursor to click on each drum and make noise. I’ve found five water drum sounds that were recorded by an open source artist, so I will map each of the sounds to each of the drums.
  2. Memory mode – My thought is that the game will give you a pattern, starting with just one drum, then two, and so on, reaching some seemingly infinite number. With each “round” you must repeat the pattern in the order it was shown to you. For each correct whack, you will gain points. For each completed pattern, you will gain points. For playing, you will gain points. Pretty much a lot of whacking, water drum sounds, and points!

If you don’t know what a water drum is, you can check it out on youtube or read up on it on Wikipedia. Thus far, all that the game entails is a hand and a couple graphically rendered drums of my own making, don’t laugh, the artwork is pretty bad. Either way, you can check out my repository on GitLab if you are interested in seeing it progress from the ground up!

Linux – keep it simple.

JelloStorm: Teleportation, poison rings, and more!

sample

Okay, so I’m done with the class, but I’m still having fun! I’ve updated some of the game mechanics for JelloStorm!

Some of the improvements that I have made to my game are not really technical, but really improve the game play. First off, I added in “poison rings” around each jello, so you can see the area of collision better. It adds a nice visual touch to the game, while adding the benefit of being able to see where you should stand in relation to the jello without getting hurt.

The second addition was teleportation. In the original build, getting away from the jello blobs was easy: just run around the edge in a circle. The jello monsters would eventually all end up in the middle of the screen and you could play indefinitely. That’s no fun, but to God be the glory, I came up with the teleportation idea!

So, I fixed it by giving the jellos a chance to “teleport” to another place in the gaming area. While it isn’t intelligent (in fact it is random) it happens often enough to make you miss targets, because they disappear, and to put them in the way of where you are going!

The code looks like this:

if (specificJello % 2 == 0) {
// Give the jello an opportunity to randomly teleport!
// The if statement checks if it is even number.
// If it is, do this:

// Find the min/max of the arena area
int maxY = arena.height – 50;
int minY = arena.top + 50;
int maxX = arena.width – 50;
int minX = arena.left + 50;

// Generate our random number
srand((int)time(0) * specificJello);
int side = (rand() % 10);

switch (side)
{
case 0:
// left
m_Position.x = (rand() % maxX) + minX;
m_Position.y = (rand() % maxY) + minY;
break;
}

}

All that fancy stuff says, if it is an even numbered jello (sorry oddies, you’re left out), then it has a 10% chance of being chosen for teleportation. That’s pretty low, but remember, by round 20 there are 100 jellos, and so (in theory based on probability) 5 of them would randomly teleport every frame of the game (100 / 2 * 0.1). Since there are upwards of 30 fps on my computer, then as many as 150 teleportation events could happen in a second.

That makes the game just a little less predictable….

Be sure to check out the full commit, and download the code to give it a try!

Linux – keep it simple.