Fool’s Mate Friday?

Fool’s Mate Friday is going to take a little detour, as I work on learning a new programming language.

If you have followed my blog at all, you will notice that I’ve made a bit of a shift away from Android. When I was working with Android, I was heavily invested in Java programming, both for games and app, as well as making custom ROM’s. I’ve come to realize though, that while Java is cross platform, it is a bit of a niche these days.

Java is used by Android, but rarely used by other computer operating systems. True, it CAN be run on just about any OS, but usually ISN’T. Most browsers have dropped Java applet support, and most OS’s don’t include Java support without installing some form of JRE (Java Runtime Environment).

As I’ve switched (at least temporarily) from Android to Ubuntu Touch (UBPorts), I’ve seen a real need for more robust apps for that platform. Unfortunately, UT doesn’t support Java natively, and that left me out in the dark.

But, God gave us brains, and I’m always trying to use mine to learn new things, or master things I already know. So, I’ve decided to take up a new programming language. Obviously, if you read the title, you already know that I picked C++.

It can be hard to just “learn” something new by reading a book, or looking at code. One of the things that helped me a lot when learning how to make Android games was to sign up for a class on Udemy by Rob Percival. He made the course fun and dynamic by making little creative games or applications to teach the student new concepts or ideas. With that in mind, I jumped back on Udemy and snagged a course (during the $10 site-wide sale) called “Beginning C++ Game Programming“. It focuses on teaching a complete noob how to program in C++ by creating 3 simple games.

One of the perks to this programming style is getting to see something get created from start to finish, and have a graphically playable product when I’m done. It uses the SFML library (which sounds like a dirty acronym, but really is an open source library – Simple and Fast Media Library) for handling the graphics, and it seems to be really intuitive and straightforward. It also seems to be very similar to using libGDX that I was using with Android, so that make working with it easy for me to learn.

Since Java and C++ are both object oriented languages, the concepts of each are the same, which is helping me in the learning process. Although I still try to type things the Java way, so that may take a while to get used to. Either way, I’m having fun with the course, and while I’ve only completed about 15% of the course, it has been interesting and fun.

sfml_timber_1

The course does use Microsoft Visual Studio, however, I’m just using Geany to type and compile my programs. Other than one or two little snags about include files being different from Windows and Linux, I haven’t had any trouble doing things my way. Hopefully you’ll enjoy hearing about the journey!

Linux – keep it simple.

Advertisements

Video to Gif Command Line Conversion

This is really just a side note for myself. I tend to do something only once in a blue moon, and then consequently forget how to do that again later. So, I’m writing this one down for my own future reference. Hopefully you will find it useful too.

Of course, I am using WordPress for this technical blog. And, because I am “resourceful” (a fancy term for frugal or cheap) I can’t upload videos to my free blog. Maybe someone else has this problem also, and has wondered how to get around it.

Most often, I don’t need a video for the things I post, but occasionally, I can’t show something with just a picture. Thus, I’ve found a good “cheat” is to convert the video into an animated gif file instead.

Previously, I was using online tools, such as ezgif.com, or others. But that takes up an excessive amount of internet, as you upload a video, burning my limited internet allotment (yes, there are still places on the planet where internet is not unlimited). Then you have to download the gif, only to find an issue with the settings, or a tweak you want to do, which starts the process over again.

So, I decided to do some research, and while this is nothing new, here is how I’ve found is a good way to make the conversion on your Linux computer:

~/Downloads$ ffmpeg -i autostart.mp4 -vf scale=320:-1 -r 10 -f image2pipe -vcodec ppm – | convert -delay 8 -loop 0 – output.gif

Where:

  • ffmpeg is the program
  • -i autostart.mp4 is the input file video name
  • -vf scale=320:-1 scales the video to a 320 by whatever video to preserve aspect ratio. Note that you can use 640, or whatever scaled size you desire.
  • -r 10 is the frame rate. Most cell phone video is recorded at 30 fps, so choosing 15 would be every other frame, or in this case 10, every third frame.
  • -f format and pipes, redirecting to the convert tool.
  • -delay 8 is the number of milliseconds between frames. This sets the flow and speed of the gif.
  • -loop 0 is the setting for continuous loop, however, most modern browsers use a continuous loop anyways, unless you specify something else.
  • – output.gif is the name of the output file.

The output at the console will look something like this:

~/Downloads$ ffmpeg -i autostart.mp4 -vf scale=320:-1 -r 10 -f image2pipe -vcodec ppm – | convert -delay 8 -loop 0 – output.gif
ffmpeg version 2.8.14-0ubuntu0.16.04.1 Copyright (c) 2000-2018 the FFmpeg developers
built with gcc 5.4.0 (Ubuntu 5.4.0-6ubuntu1~16.04.9) 20160609
configuration: –prefix=/usr –extra-version=0ubuntu0.16.04.1 –build-suffix=-ffmpeg –toolchain=hardened –libdir=/usr/lib/x86_64-linux-gnu –incdir=/usr/include/x86_64-linux-gnu –cc=cc –cxx=g++ –enable-gpl –enable-shared –disable-stripping –disable-decoder=libopenjpeg –disable-decoder=libschroedinger –enable-avresample –enable-avisynth –enable-gnutls –enable-ladspa –enable-libass –enable-libbluray –enable-libbs2b –enable-libcaca –enable-libcdio –enable-libflite –enable-libfontconfig –enable-libfreetype –enable-libfribidi –enable-libgme –enable-libgsm –enable-libmodplug –enable-libmp3lame –enable-libopenjpeg –enable-libopus –enable-libpulse –enable-librtmp –enable-libschroedinger –enable-libshine –enable-libsnappy –enable-libsoxr –enable-libspeex –enable-libssh –enable-libtheora –enable-libtwolame –enable-libvorbis –enable-libvpx –enable-libwavpack –enable-libwebp –enable-libx265 –enable-libxvid –enable-libzvbi –enable-openal –enable-opengl –enable-x11grab –enable-libdc1394 –enable-libiec61883 –enable-libzmq –enable-frei0r –enable-libx264 –enable-libopencv
libavutil 54. 31.100 / 54. 31.100
libavcodec 56. 60.100 / 56. 60.100
libavformat 56. 40.101 / 56. 40.101
libavdevice 56. 4.100 / 56. 4.100
libavfilter 5. 40.101 / 5. 40.101
libavresample 2. 1. 0 / 2. 1. 0
libswscale 3. 1.101 / 3. 1.101
libswresample 1. 2.101 / 1. 2.101
libpostproc 53. 3.100 / 53. 3.100
Input #0, mov,mp4,m4a,3gp,3g2,mj2, from ‘autostart.mp4’:
Metadata:
major_brand : mp42
minor_version : 0
compatible_brands: isommp42
creation_time : 2018-04-20 14:05:43
Duration: 00:00:25.96, start: 0.000000, bitrate: 6103 kb/s
Stream #0:0(eng): Video: h264 (Baseline) (avc1 / 0x31637661), yuv420p, 1280×720, 6448 kb/s, SAR 1:1 DAR 16:9, 29.88 fps, 30 tbr, 90k tbn, 180k tbc (default)
Metadata:
rotate : 90
creation_time : 2018-04-20 14:05:43
handler_name : VideoHandle
Side data:
displaymatrix: rotation of -90.00 degrees
Stream #0:1(eng): Audio: aac (LC) (mp4a / 0x6134706D), 48000 Hz, stereo, fltp, 48 kb/s (default)
Metadata:
creation_time : 2018-04-20 14:05:43
handler_name : SoundHandle
Output #0, image2pipe, to ‘pipe:’:

Metadata:
major_brand : mp42
minor_version : 0
compatible_brands: isommp42
encoder : Lavf56.40.101
Stream #0:0(eng): Video: ppm, rgb24, 320×569 [SAR 5121:5120 DAR 9:16], q=2-31, 200 kb/s, 10 fps, 10 tbn, 10 tbc (default)
Metadata:
handler_name : VideoHandle
creation_time : 2018-04-20 14:05:43
encoder : Lavc56.60.100 ppm
Stream mapping:
Stream #0:0 -> #0:0 (h264 (native) -> ppm (native))
Press [q] to stop, [?] for help
frame= 39 fps=0.0 q=-0.0 size= 20805kB time=00:00:03.90 bitrate=43700.4kbitsframe= 80 fps= 80 q=-0.0 size= 42676kB time=00:00:08.00 bitrate=43700.4kbitsframe= 121 fps= 80 q=-0.0 size= 64548kB time=00:00:12.10 bitrate=43700.4kbitsframe= 159 fps= 79 q=-0.0 size= 84819kB time=00:00:15.90 bitrate=43700.4kbitsframe= 200 fps= 80 q=-0.0 size= 106690kB time=00:00:20.00 bitrate=43700.4kbitsframe= 241 fps= 80 q=-0.0 size= 128562kB time=00:00:24.10 bitrate=43700.4kbitsframe= 245 fps= 80 q=-0.0 Lsize= 130696kB time=00:00:24.50 bitrate=43700.4kbits/s dup=0 drop=483
video:130696kB audio:0kB subtitle:0kB other streams:0kB global headers:0kB muxing overhead: 0.000000%
~/Downloads$

Hopefully that is a tidy explanation. Keep in mind, the higher the -vf, the bigger the gif appears, but also the larger the file. The -r value will make the gif smoother as it goes up, but will also increase the gif size in MB!

Linux – keep it simple.

Fool’s Mate Friday: Bobby Fischer Teaches Chess

While looking at a few old chess programs for some ideas about my current programming lull, I stumbled across a rather useful old DOS program: Bobby Fischer Teaches Chess. Of course, I knew it originally was a book, but I did not know that it was later turned into a chess program.

The interface is a bit clunky, running in DosBox. Of note, the taller pieces, like queens or kings, often obscure smaller pieces like pawns, due to the board orientation. You might also have noticed that the first pic is our infamous Fool’s Mate! (I just couldn’t help but include it here!)

I went through the first chapter, 1 of 6. If you want to try it out, be prepared for long chapters! It appears to save bookmarks, so I suppose that you could come back to it later.

One thought that this gave me was that of using the JustChessEngine or JustChess interface for instructional purposes…. Perhaps some sort of “find the mate”, or “defend from mate”. Not sure, but it is an idea. I’ll have to think on it.

Linux – keep it simple.

BlueFruit Project: Stage 1 Relays!

autostart

Blinking lights! Yes, the first prototype of the first stage relay setup for my home made autostart is assembled. As you know, a small 3 to 5 vdc BlueFruit Feather can’t crank an engine starter. That’s just too much current to flow through such a small board. To make this work, I have to step up through relays in stages to get to the big relays that can actually do the work.

So, stage 1 relays are actually Latching Relay Featherwings that are joined to the BlueFruit feather via soldered wire connections. These latching connections only need about 10ms of signal to turn on or off the 3.3 vdc relays, which will hold the 12 vdc power supply to the stage 2 relays.

The stage 2 relays will then use minimal current at 12 vdc to drive the vehicle relays that actually engage things like the key on and cranking power. Don’t worry, at the end of the project I will follow this up with a diagram and parts list. Looks like the overall price is about $60 worth of material, pending finding a used container or box for free.

Linux – keep it simple.

Fool’s Mate Friday: LaserChess

Okay, so this may seem a bit off topic, but I was exploring old chess games for some inspiration. While this didn’t inspire me that much, it certainly was interesting to play Laser Chess, a DOS game circa 1994.

laserchess

The premise of the game is simple. There are 18 pieces per side, most of which are able to move in a similar fashion to regular chess pieces. However, unlike chess pieces, you don’t capture the enemy pieces. Instead, you maneuver your pieces into place, and then fire a beam from your laser cannon.

Each piece appears to have some unique attribute as to what happens to the laser beam. It also matters which way your piece is facing. Think of a series of beams, reflectors, splitters, and prisms. The beam gets redirected off of your pieces, and possibly your opponents pieces, until it comes in contact with something that is not reflective, split, or pass through. Then it obliterates that object.

And I thought Fischer Random was hard. This game is insane.

If you want to try it out, download DosBox, and head over to the dos games section of my GitLab miscellaneous files folder. Good luck!

Linux – keep it simple.

Moving from GitHub to GitLab!

gitlab

I’m really not a conspiracy theorist. I don’t truly believe that Microsoft embodies all things evil. But after the announcement of GitHub’s purchase by Microsoft, I still decided to move away from GitHub and copy all my repositories over to GitLab.

I had several choices when making the move from GitHub, but I felt that GitLab’s open source platform was best in keeping with my goals as an (unskilled but learning) open source programmer. I also appreciate that you can download the GitLab software and run it yourself on your own server, which is something that I may look into in the future.

I have already copied all of my repositories to GitLab, and they have the same name and kept all of the commit history as well, thanks to GitLab’s great import tool. Over the next few weeks, I will be considering how to appropriately close and/or mark my GitHub repositories so that people will use the GitLab issue tracker and look to GitLab for updates. Thank you for your patience.

Going forward on this blog, I will be using GitLab and not GitHub. However, due to the volume of old posts I cannot take the time to change all of the old posts links. If you are looking for something older, and you can’t find it on GitHub, then try looking at GitLab, where the same repositories, issue trackers, and history of commits reside. I do apologize for any inconvenience that may cause.

In any event, agreed or not, you can still check out all of my work at https://gitlab.com/alaskalinuxuser , and thanks for reading my post.

Linux – keep it simple.

BlueFruit Project: Time Out!

Zip created at /tmp/arduino_build_587243/sketch_dec29a.ino.zip
Using library Bluefruit52Lib at version 0.7.5 in folder: /home/alaskalinuxuser/.arduino15/packages/adafruit/hardware/nrf52/0.7.5/libraries/Bluefruit52Lib
Using library nffs at version 1.0.0 in folder: /home/alaskalinuxuser/.arduino15/packages/adafruit/hardware/nrf52/0.7.5/libraries/nffs
Sketch uses 59352 bytes (35%) of program storage space. Maximum is 167936 bytes.
Global variables use 4852 bytes (9%) of dynamic memory, leaving 46220 bytes for local variables. Maximum is 51072 bytes.
nrfutil –verbose dfu serial -pkg /tmp/arduino_build_587243/sketch_dec29a.ino.zip -p /dev/ttyUSB0 -b 115200
Upgrading target on /dev/ttyUSB0 with DFU package /tmp/arduino_build_587243/sketch_dec29a.ino.zip. Flow control is disabled.
Starting DFU upgrade of type 4, SoftDevice size: 0, bootloader size: 0, application size: 59764
Sending DFU start packet
Sending DFU init packet
Sending firmware file
######################################################################################################################
Activating new firmware
#
DFU upgrade took 11.5461740494s
Device programmed.

Time out! Well, not really, but it sounds catchy! Timing is really important. And that is what I had to adjust with this commit. I had a 500 ms delay between program runs, which takes about 500 ms to run. So, each run of the program takes roughly 1 second, which is great for setting the timing of the program.

Here’s the interesting part: the relays that I am using are the latching relay featherwings. They only need the power applied to set or unset the relay for 10 ms, then they will hold their last position. This is great for power savings. In my program, I want to capitalize on this power savings by having the outputs off all the time, when they are not specifically latching the relays.

2923-00

To make that happen, at the beginning of the loop of my program, I added a few lines to set all of the output pins low (15, 16, 7, and 11). While this will cut down on the power the board puts out (saving electricity, but also saving wear and tare, as well as making the code cleaner, since the state of the pins will always be known), it may cause me a slight issue. I don’t want it to cut down on the actually needed signal for when the outputs should be high to latch or unlatch a relay.

Confused yet? Well, let me explain. Here is how the program looks functionally:

  1. Set all pins low.
  2. delay 500ms.
  3. run program, like setting some pins high.

As you can see, there is actually no time between running the program and setting all the pins back to low. I needed to ensure there was at least 10 ms after the program sets the pins high before the loop sets them all low again. I thought I could swap 1 and 2, making the delay first, but then there was no time between the setting of low pins and running the program. So I edited it like this:

  1. delay 250 ms.
  2. set all pins low.
  3. delay 250 ms.
  4. run program, like setting some pins high.

Now there will always be at least 250 ms (1/4 of a second) for the relays to latch before given a command to set the pins low. Conversely, after being set low, there is 250 ms before the program runs, allowing me to keep my (roughly) 1 second timing on the circuit. Probably a little overkill for what I need, but at least I know this will work, making the program more robust.

Linux – keep it simple.

Fool’s Mate Friday: Where to, Governor?

Today’s update is pretty basic. Just cleaning up and filling in some blanks on my JustChess app. While I wont bore you with the whole commit, you are welcome to check it out.

jc9

Basically, I just added an about and settings page. Both pages are pretty basic, but the settings page does have a cool star strength indicator for the computer engine strength. I thought it wise to add it so people could play against the JustChessEngine at lower strengths. It seems a bit funny, since it is currently so weak that I doubt this would be needed. However, it seemed to me, that when making a full fledged app of this sort, one would include some sort of slider or adjustment for the engine strength, so there it is.

This does beg the question of where to go next. As is, my goal was to learn more app making skills and increase my java strength by creating a chess app in which I made my own engine, and one that you could play against a person or a computer. To God be the glory, this app has met that goal. With pass’n’play mode, you could play a friend in a room, or with single player, you can play as black or white against your phone.

But the road forks here.

On the one hand, I could pursue the avenue of making the game playable with someone who was not in the same room, via email, text, online server (parse comes to mind, as I set one of those up for a different app). On the other hand, I could focus on the engine and try to make it stronger.

And yet the road forks again….

One of the big problems is that of programming language. As I delve deeper and deeper into java, I have found only one place that it is applicable, Android. As I’m sure you have seen from my blog, I’ve switched to using Ubuntu Touch on my phone. But Ubuntu Touch doesn’t support java naively (or perhaps at all). As I continue to apply time to learning java, I continue to limit myself to just one application. Perhaps it would be better to learn c++, java-script, or some other language that has a broader application?

So, I sit at the cross roads. What to do next? Hopefully I can figure it out before the next Fool’s Mate Friday!

Linux – keep it simple.

BlueFruit Project: Analog and Digital Detection (Code Name ADD)

From the post last week, you can see that I ran into a snag with the BlueFruit Feather board. It should be able to read the analog inputs separate from one another, but for some odd reason, taking a 3.3vdc reading on A0 would return 3.3vdc on A0 and ~1.4vdc on A3, and vice versa when reading the other way. This is problematic, as I have A3 as the battery indicator and A0 as the brake light indicator.

The A3 battery indicator tells the circuit if the truck has started, due to the alternator kicking in and the voltage climbing over 14vdc. The A0 brake light indicator tells the circuit to shut down, because the user pushed the brakes. Can’t have both. I jumped onto the Adafruit Forums, and found some really helpful people there. However, I wasn’t able to find a reason for my dilemma.

Thus, I created a work around.

auto

I really need to know what voltage the battery is, however, I don’t need to know the voltage of the brake lights, just that the brake lights were pressed. So the battery voltage needs to be a fine tuned analog signal. The brake lights just need to answer the question of on or off, true or false, 1 or 0. Wait! 1 or 0 is binary, which is digital! What if I just had a digital representative for the brakes?

I’m currently re-working my schematics, but here is the gist of what I want to do with the brakes (only the relevant part of the circuit is shown):

brakelights

This will indicate high on the digital circuit, which usually needs above 3 vdc to read high. Test runs were good on my desk, so I’m going to press forward with it. You can check out the full commit on my GitHub, but here is the relevant portion:

// read the input on digital pin 30:
int sensorValue = digitalRead(30);
// print out the value you read:
if (sensorValue == 1) {
Serial.println(“Pin 30 HIGH “);
// Brakes have been pushed, shut down all autostart circuits.
// This will not affect actual engine run circuits, just the autostart
// ones. So the engine will stay running if the key is in and on.
digitalWrite(16, LOW);
digitalWrite(15, LOW);
digitalWrite(7, HIGH);
digitalWrite(11, HIGH);
crankTimer = -1;
startTimer = -1;
runTimer = -1;
startAttempts = -1;
Serial.println(” Kill All – Brakes pressed. “);
}

Just about done with the BlueFruit programming! Now I need to work on the app programming and iron out and construct the electronics portion.

Linux – keep it simple.

Fool’s Mate Friday: Check or Stale Mate?

Apparently, in 1988, World Champion Gary Kasparov accidentally stalemated his opponent during a blitz tournament in Canada. Mr. Kasparov had a king, queen, and a bishop against Kiril Dimitrov Georgiev’s lone king. The problem Mr. Kasparov was facing was that of time running out. In his efforts to move quicker, he forced a stalemate when he had every advantage and reason to win!

I will probably never be as great as Mr. Kasparov, so I certainly mean no disrespect when bringing this up. My point being is that even world champions can stalemate. How does this apply to my JustChess app? Well, it seems to me that it is pretty important to clarify when the opponent can’t move, if they are in stalemate, or checkmate.

Fortunately, I figured out how to do just that.

jc8

The code wasn’t particularly grueling, it turned out the hard part was figuring out the order of play for pass and play verses playing against the computer. The time which you need to look for a checkmate or stalemate actually changes between those two. Here’s the important snippet, but as always, you can check it out on my GitHub.

    moveOptions="";
    if (!wTurn){
        moveOptions= terminal("suggestMove,black");
    } else {
        moveOptions= terminal("suggestMove,white");
    }
    if (moveOptions.isEmpty()) {
        staleOrCheckMate();
    }

} // End clicked piece.

public void staleOrCheckMate() {
    String status = terminal("checkmate");
    if (status.equalsIgnoreCase("1")) {
        status = "checkmate!";
    } else {
        status = "stalemate!";
    }
    String turnIs = "";
    if (wTurn) {turnIs="White is in ";} else {turnIs="Black is in ";}
    new AlertDialog.Builder(this)
            .setIcon(android.R.drawable.ic_dialog_info)
            .setTitle(turnIs + status)
            .setMessage(
                    "Would you like to play a new game?")
            .setPositiveButton("View Board", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    // Do nothing.

                }
            })
            .setNegativeButton("New Game", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                    // First you define it.
                    Intent myintent = new Intent(MainActivity.this, IntroActivity.class);
                    myintent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                    // Now you call it.
                    startActivity(myintent);

                }
            })
            .show(); // Make sure you show your popup or it wont work very well!

}

The longest part of this project was actually testing it against the computer! It’s easy to checkmate it right now, but I found it was a pesky bugger to stalemate! Be sure to give it a try, my GitHub has all of the updates of the app already built for you to download and test out!

Linux – keep it simple.