Teach your app to beat you at Tic-Tac-Toe

As part of the Front-End Development curriculum for FreeCodeCamp.com I was required to build a Tic-Tac-Toe web app. I worked and worked on it adding responsive web design and a simple user experience. Using the common languages that are taught in the course HTML, CSS, Boorstrap, javaScript, and JQuery, I built a functioning app. Recently, I was proudly displaying my work, but got the feedback that the app was too easy to beat and I realized I never incorporated any A.I. to the code. Logic!!! Seriously, my favorite part of putting together any app. I was determined to find a solution to this flaw in my app and I came up with a working system.

tic-tac

Note: While putting together this post, I found the minimax algorithm. This solution to the tic-tac-toe app is not an explanation of it, it is my logic. A result of the light bulb going off in my head. 🙂

Interface

The main idea here is to use the grid system that comes with bootstrap to put together a set of boxes to serve as your nine position board.

boardDiv

In order to later access each of the boxes in the grid, I gave each spot their corresponding position as the “ID” name, allowing me to use JQuery to get the element id an parse out the the numbers for use with later logic.

00 , 01 , 02
10 , 11 , 12
20 , 21 , 22

getID

Logic

When a user clicks a location on the board, they are choosing that location as their move. Then, it is up to my logic to work its magic.

A two dimensional array with the value of five in all locations is initialized when the game starts. Anytime a location is chosen, the corresponding array location is updated with a boolean value, True or False.

array

Here, the script checks if the user’s move was a win. This is done after every move, user and pc. If, the move is not a win, the pc chooses its next move.

Next, the logic scores all combinations and stores the results in an array. In Tic-Tac-Toe, there are eight sub arrays that are possible wins, three horizontal lines, three vertical lines, and two diagonals.

Score = 15    sub-array has combination of        5 , 5 , 5

Score = 10    sub-array has combination of        5 , 5 , False

Score =      sub-array has combination of        5 , False , False

Score = 11    sub-array has combination of        5 , 5 , True

Score = 7      sub-array has combination of        5 , True , True

Score = 6      sub-array has combination of        5 , True , false

arrays

The numbers to look for for are five and seven because they represent sub-arrays that are one play away from a win. The logic loops through an array that has the scores called arrsums. If the array has a score of five or seven, the pc plays the location that has the open spot, or the location with the value of five. The logic also checks if the play is a win for itself and that play is obviously given preference.

Again, this is not using the MIniMax algorithm. I’ll try to build the next version using that algorithm. Also, I am always open to suggestions.

Play my finished product here:

http://natrivera.com/tic-tac-toe/

check out the code here:

Advertisements

Get the Weather with this Java App

This slideshow requires JavaScript.

My latest creation will show you the weather in your current location using your public ip, or you can enter a zip code and it will return the forecast for that location.

I used a variety of tools including:

Let’s go through the logic as briefly as possible.

  • Get current location using the IP API via the user’s ip address
  • From the location results, extract the latitude and longitude in xml format
  • Use this latitude and longitude to run a weather api request also in xml
  • Extract information, including the forecast for the next five days
  • Display information on the gui.
  • If user enters a zip code, do same as above but with zip code

The project includes three classes, WeatherApp, WeatherUtility, and Forecast.

  • WeatherApp holds the gui jform as well as the main method.
  • WeatherUtility is where all the work is done.
  • Forecast is used to create an object of each of the results obtained from the weather api.

View the source files on Github.

Download the app from http://natrivera.com/WeatherApp.jar

Create a Bank Account Application in Java

 

Capture

Figure-1

This application will simulate a simple bank transaction terminal with a graphical user interface. You will be able to load multiple bank accounts and view their account holder’s name, account number, account open date, and account balance. With only these four pieces of data we will simulate depositing money, withdrawing money, and transferring money to another account. The withdraw function should only work if the bank account has enough money to withdraw a requested amount. The transfer function carries a $2 fee given that the account has enough money to transfer out and the balance is less than $10,000. Otherwise, the app will warn the user about the error information.

For this project, I will assume that you are using the NetBeans IDE and that you are familiar with object-oriented programming concepts. Also, that you can create a from using NetBeans’ GUI Builder. I will also assume that you are comfortable reading from and writing to files using java reader and writer APIs.

 


Using the following (<>) delimited data.

1231<>2012/2/3<>Jack Williams<>168.0

1232<>2012/2/3<>Lily Makki<>532.89

1233<>2012/2/4<>Peter Hansen<>58.10

1234<>2012/2/4<>Cathy Johns<>750.04

1235<>2012/2/4<>Paul Davis<>946.11

1236<>2012/2/5<>Michael Lopez<>223.06

1237<>2012/2/5<>John Anderson<>597.21

1238<>2012/2/5<>Ming Chen<>259.04

1239<>2012/2/5<>Sijun Zhang<>623.12

The first column contains the account number

The second column contains the account open date

The third column contains the account holder’s name

The fourth column contains the account’s balance

For this project, we will create five classes named:

            AccountApp, AccountUtility, AccountContants, Account, ChechingAccount

AccountApp class: This class contains the code for the jform that will serve as the gui for the app. Also, it is the manager of the app calling the necessary methods as the app deems necessary.

AccountUtility class: This class will be where most of the work is done for the app. Including reading the file, writing to file as you modify the account balance, as well as create accounts that will contain data as long as the app is running and used to retrieve data to be written to the file.

AccountConstants class: This class will only contain two constants and will be extended by the Account class, there the constants will be used to check if conditions are met in the accounts.

Account class: This class will define the characteristics of every account you create while working with the app. For instance, every account will have number, date, name, and balance. These variables will also need get and set methods to access the instance variables from outside the account class.

CheckingAccount: This class extends the Account class and contains the code to transfer money between accounts.

Now that we have an idea of what it should look like, we can start building the app.

  1. Open Netbeans and create each of the five classes listed above.
  2. Following the example on Figure-1 create a jform in the AccountApp class and add the necessary buttons and text fields. Remember to give your buttons and text field meaningful names, this will make it easier to add code to it later. ie… exitButton
  3. Easy peasy part here code your exit button to close the app.
  4. Work with your Account class,
    1. Create the instance variables listed above.
      1. String number
      2. String name
      3. GregorianCalendar date
      4. Double balance
    2. Create a constructor that takes two strings, a date, and a double and set those to the instance variables in the Account class.
    3. Create a get method that returns each of the four instance variables for the class.
    4. Create a set method that sets a given input to the instance variable of the Account.
    5. Create a method that takes a double as an input and adds it to the balance of the current account.
    6. Create a method that takes a double as an input and subtracts it to the balance of the current account, return true if the transaction completes.
  5. Work with the AccountConstants class: Here create two constants to be used in the app to subtract a transfer fee and check threshold of checking accounts.
  6. Work with CheckingAccount:
    1. Remember to extend the Account class
    2. Create a constructor similar to that of Account class that uses the super keyword.
    3. Create a method that takes a double and a CheckingAccount that will subtract that double amount from the current account and adds it to the given account. Be sure that your logic checks that current account has enough to transfer, also checks if current account has more than threshold.
      1. Return 0 if transfer was completed without a transfer fee.
      2. Return 1 if transfer was completed with a transfer fee.
      3. Return -1 if transfer was not completed because balance is less than transfer amount and transfer fee.
      4. Return -2 if transfer was not completed because balance is less than transfer amount.
  7. Work with AccountUtility:
    1. This class will have two instance variables
      1. File with a relative file path that will have your data.
      2. A hash map that will take a String (account number) as a key and CheckingAccount as the value.
    2. Create a blank constructor for this class.
    3. Create a method that will read your file, creates a CheckingAccount for each line and store each account to the hash map with the account number as a key.
    4. Create a method that gets the text from the dropdown and returns the corresponding CheckingAccount.
    5. Create a method that takes a string as an argument and returns true if that string is a key in the hash map, in other words a CheckingAccount with that account number exist.
    6. Create a method that loops though each of the CheckingAccounts in the hash map and prints them to your file in the same format as our original file but with the new altered data.cap1Figure-2
  8. Work with AccountApp:
    1. First instantiate an instance of your AccountUtility class.
    2. Load the data from your file by running the method you created in AccountUtility.
    3. Loop though your hash map that contains the CheckingAccounts and print the number strings to the dropdown of the jform.
    4. Create a method that fills the form using the current CheckingAccount loaded on the dropdown.
  9. Still working with AccountApp but now each of the action buttons. For this section you will need to use jOptionPane to get additional user input and to output error messages. (ShowMessageDialog and ShowInputDialog)
    1. withdrawAction
      1. Get account number from dropdown.
      2. Ask user to enter a double amount to withdraw
      3. Withdraw if appropriate.
      4. Write to your file using the updated CheckingAccount information.
      5. Load data to your jfrom.
    2.   depositAction
      1. Get account number from dropdown
      2. Ask user to enter a double amount to deposit
      3. Deposit.
      4. Write to your file using the updated CheckingAccounts information.
      5. Load data to your jform.
    3. transferAction
      1. Get current account from dropdown
      2. Ask user for transfer amount
      3. Ask user for transfer account
      4. Complete transfer if appropriate.
      5. Display appropriate output message using the returned integer from the transfer method.
      6. Write to file using the updated CheckingAccount information.
      7. Load your data to the jfrom.cap2Figure-3

I am including a downloadable version of this app if you would like to try it out. Simply download from the link below and extract the folder.

http://natrivera.com/bank-app.zip

 

How to import a project in NetBeans

So, you received a java project from a fellow student, a professor,  or just another JAVA enthusiast and you don’t know how to open it in NetBeans. Well, you have come to the right place.

I put together this tutorial that will guide you to import projects to NetBeans in 8 simple steps.

  1. Locate the zip file. In my case, it is saved on the desktop.
    • locate zip file
  2. Open NetBeans IDE
    • open netbeans
  3. Click “File”, then “Import Project”, then select “From ZIP…”
    • import project
  4. Click “Browse” and lookup your zip file. Once you find your file, select it and click “Open”.  
    • lookup
    • lookup
  5. You may get a message saying, “No NetBeans projects added”, but that’s not a problem.
    • no file found
  6. Click “File”, then click “Open Project”
    • open project
  7. Your imported project should appear in your NetBeans Projects folder. Select it and click “Open Folder”.
    • look for folder
  8. You should now see your imported project on your project list in NetBeans.
    • folder imported

Check out my site for more projects

NatRivera.com

Your Data SElFie

Here it is, a screenshot of my Data Selfie.

Nat Rivera Data Selfie

While you are on Facebook the extension is tracking what you look at, how long you look at something, what you like, what you click on, and whatever you type.

-Data Selfie Video

This chrome extension uses machine learning and natural language processing to track your Facebook habits, it then gives you a command-line-like representation of that data. I found the extension via lifehacker, link to their article here.

Everyone knows that social media companies are collecting our information to in order to sell to advertisers and even political campaigns, but to actually get a glimpse of how the data looks is scary. After only one week of usage, the extension has shown insight about how I use Facebook and even started predicting my personality, religious, and political orientations.

The fields of data science and machine learning are capturing my interest more and more as I find discover different ways companies and government agencies are using tools similar to this. Stories like the one of Robert Mercer, who was written about today in this article on the Guardian, show how he has used data to influence public perception.

Michal Kosinski, the centre’s [Cambridge Analytica] lead scientist, found that with knowledge of 150 likes, their model could predict someone’s personality better than their spouse. With 300, it understood you better than yourself.

-excerpt from Guardian article

We give up tons of information about ourselves in what has been described as our digital exhaust. With every like, share,  and post we offer and more information about our lives. With this chrome extension you can get a hint of what is happening behind the scenes.

Update: 2/28/2017

Another look at my data selfie…

Machine learning is used to make inferences about my preferences using information about what I have typed.

screenshot-2017-02-28-08-23-50

 

 

Nat Rivera
Student of Business Administration at California State Polytechnic University, Pomona
NatRivera.com

This American Life

 

Driving in my car, waiting for my next class to start, or resting at home after a long day there’s a good chance that I’m also listening to an episode of This American Life. Throw on some earbuds or plug in the auxiliary cord and get introduced to a wide range of topics. If you are the type of person that enjoys listening to human interest stories, who doesn’t by the way, you’ll also enjoy this show. This American Life with its varying list of contributors, engaging acts, and huge influence on the industry is a must listen on your way to work or while waiting for your next class to start.

First, let me explain just what the show is all about, This American Life is an hour long weekly podcast that also airs on National Public Radio across the country. It usually provides three or four stories, which the show calls acts, that hover around a central topic. These acts can be anything from a fictional short poem to a long form journalistic report on a given subject. Ira Glass, the show’s creator and host, introduces each act and then hands the show off to a contributor. This is where the magic happens, we then get to hear a well put together recounting of a story from award winning journalist and authors. In the article “Why You NEED to Listen to This American Life.” Pete Strauss added, “Every narrative on the show, both the fictional and non-fictional, is constructed masterfully with a meticulousness that makes it near impossible to resist becoming emotionally invested in the stories.” In other words, you will become immediately addicted and will be impressed by the way they cover many topics.

What’s so special about this show is that it can tackle giant topics like the global economy or tiny stories like a family’s play toy and still capture your interest in the same way. My favorite is an episode from 2008. In this episode Alex Blumberg came and gave the best explanation of what exactly took down the global economy in 2007. Hint, it was collaterized debt obligations. We got to hear from the bankers who took part in selling trounces of risky mortgages, and the borrower who took out a loan he knew he couldn’t pay off. In a more recent episode we were taken back in time to a small town in the heart of America where one family with several children built a wooden ship to play on in their front yard. The narrator explains how this ship served as entertainment, babysitter, and lesson on responsibility for the children.

Another important piece to the winning recipe is the wide range of characters that add to the show. Comedians like Tig Notaro who came on the show and shared the story of a set she did moments after being diagnosed with cancer. Also long form journalist like the team from Propublica, who has teamed up on occasion with the show. The more you listen to the show the more you will begin to recognize the voices and look forward to their style of storytelling. In the article “Ira Glass, Storyteller.” James Rainey said, “Glass and crew have won our loyalty via a certain alchemy of subject, point of view and tone that can turn the mundane into the magnetic.” This is a great way to summarize how the contributors are a big piece of the show’s success and because of it the show has had a ton of influence on the industry.

Now let’s discuss the influence this show has on the podcast industry, movies, and beyond. This American Life is constantly on the top of iTunes podcast list and it also broadcast to nearly 600 stations. Mike Birbiglia along with Ira Glass made a movie based on an act on the show. In this act Mike explained how he discovered he was sleepwalking and getting into dangerous situations in his sleep. Sleepwalk with Me, the movie, won the 2012 Audience Award at Sundance Film Festival. Another example is a longtime Georgia Judge Amanda Williams who lost her job. A story about her corrupt practices aired on an episode in 2011 titled “Very Tough Love”. Eventually, she was forced to step down from her post. A hugely popular podcast Planet Money got its start on This American Life; they were the main contributors on the episode on “The Global Pool of Money.” In 2014, Sarah Koenig launched a widely successful spinoff of the show called Serial. It was a national sensation. Serial took the recipe of incredible story telling from This American Life and stretched it out to twelve episodes that were like candy for your ears.

Even given all these reasons to listen to the podcast, I still get blank stares when I encourage friends to listen. Many argue that listening to a talk radio show is old fashioned or dead. I run into this objection all the time when I recommend the show. People prefer to listen to music when they turn on the radio or put in some earbuds. Others argue that the acts on the show tend to go long or that are long winded. Another objection is that you can get all your news from the local 6 o’clock broadcast. However, podcasts are very popular around the world; they give more people the ability to tell their stories without having to compete for air time with large television networks. Acts on the show go into every subject in depth covering all possible angles of the story; sometimes causing them to be longer a than a normal news report. Very often they get firsthand accounts of the events from both sides. Even if you think an act is not to your liking, there is an archive with 20 years’ worth of stories to go over. I began listening a few years ago and thanks to this giant archive I still have not run out of episodes to listen to.

It’s no secret that I’m a big fan of the show. If you take my advice and add it to your weekly routine, you will also love it. Every chance you get you’ll be recommending it to your friends and family. The way the stories are told make it easy to become emotionally invested on the people being reported on. You will also find yourself checking Google to see if there have been updates to the story. Week after week the producers of the podcast This American Life give a unique look on a wide range of topics delivered in engaging acts. Their work has been felt across the industry, and influenced the next generation of podcasters.

Starting a new quarter

Yesterday was the first day of the winter quarter at school. I enrolled in 15 units, 4 classes, and wait listed in one class. Since that last class is full, I decided to drop it and I’ll keep my current schedule of four classes. Luckily I was able to find a schedule where I go to school only two days a week.

For the record, the classes I’m enrolled in are:

  • CIS 231 Funf of Comp Info Sys
  • CIS 310 Management Information Systems
  • BIO 110 Biology
  • MHR 301 Principles of Management

My first thoughts on these classes

CIS 231 – Looks like I’ll be working with other students building websites as well as using those skills to build a personal portfolio. I’m really happy to work on those skills, that is why I started this wordpress blog, so a plus.

CIS 310 – Using tools like excel and access from the microsoft suite I’ll learn to create business documents to be used make important budget decisions in business applications. Also, I’ll get to work on my 30-second elevator speech, that sounds interesting.

BIO 110 – This is an online only section. I’ve taken a few online classes and I feel comfortable with that format. Looks like this class will cover life science and does not look like there will any projects, just quizzes and exams. I’ll study up and be prepared.

MHR 301 – This class only meets on Thursdays, so I haven’t been to the first class.I’ll update  it when I have more information.

Edit- This class requires that I write two papers. One for a team project and another one alone. The class covers the principles of management and I hope I can learn a lot from it.

Personal goals for this quarter

Well, I will obviously be aiming for straight A’s in all my classes. Aside from that, I really want to find an internship as a research assistant. Research assistant would be a good addition to my graduate school application, specifically for a career in Data Science. Hopefully something that pays and pays well, but at least I would like to find a new source of income. Income that I can use to find a new place to move in to. I would like to find a place that I can stay while I finish both undergraduate and graduate school. Another goal is to join a student club. The CIS department has a few different options, currently it looks like either SWIFT or MISSA are the best options. I will look for the one that offers experience similar to work in Data Science. I have to prepare for and take the GWT, which is a writing test required in the junior year for all Cal Poly Pomona students. I hope that writting for this blog will serve as practice for this test.

What’s next

I stopped writing after creating my first blog post last month. I need to push myself to continue to add to this online journal. Luckily one of my classes this quarter has a section on working with websites and specifically WordPress. In the future I’ll mix up the blog format from free form, to essay format, and article style. Each of these formats has an advantage and I can see using each format in the future in my professional career.

Getting Started

Let’s state the obvious, I am not a good writer. Today I tackle this weakness in my portfolio by creating, what I hope becomes, a weekly blog. Here, I will write about my journey to become a Data Scientist. That includes, updates about school, certain projects I work on, building a professional network to get internships and jobs, as well as updates on my personal life.
As of December 2016, I have completed most of my general education requirements at a couple of local community colleges. The latest, and most influential in my academic career, being Chaffey Community College in Rancho Cucamonga, California. In the Fall quarter of 2016, I transferred to Cal Poly Pomona as a Business Administration Major with a concentration in Computer Information Systems. I was advised at Chaffey College to change from Computer Science as a major to CIS because it will be quicker to complete. Business school is turning out to be a great choice. As you can tell, I am happy that I changed my course of study. I feel that no matter what type of career you choose, a background in business will be a great asset and give you a competitive advantage when looking for promotions. Even engineers need to managed, right?
In starting this blog, I hope to achieve a few things. First, I want to become a better writer. What better way than to practice and write about the week to week life. Next, is to get some exposure to WordPress. As I progress through Cal Poly Pomona I hope to get a job as a social media manager for a small company, or help desk support IT. Working with WordPress seems like good practice for working with websites and customizing them. Lastly, I would like to look back at this project and see how I progress. I have no experience with blogs and I have not ever read a blog. So, I’m not sure what to do but I’ll pick it up as I go along.
One final note, I decided to get into the programming game a little over a year ago after leaving my job of 8 years as a satellite technician looking for something more challenging. I considered my different options like boot camps, self study, and college. I eventually decided on going to college because it seemed the safest choice. It will take me many years to complete my studies but I don’t mind the work and so far I have enjoyed being a student.