Connect Four game vs life challenges


It’s been a long break in writing. Throughout the past three weeks, a lot has happened. A week after publishing my last post, I flew to Poland to take an honorable role of the best man at my friend’s wedding. I have also visited my family. The start of my trip made me distressed as I couldn’t code my game due to lack of spare time – seemed like there was constantly something going on – meeting brothers, father, driving far for the wedding, etc. I felt I had to let go the thinking about the course to enjoy the time with the dearest one. So that’s how a very long break started in my coding. Moreover, Mastermind’s AI class I was working on became very tough to crack . This problem was waiting for me while holidays clearly didn’t give any opportunities to ease it out – situation started draining my energy. After coming back to Dublin, it took me about a week to slowly get back into the routine and sorting out this procrastinated problem from my code. It took another number of days to crack it and get into the flow back again. Nothing pleasant.

I am happy to be here now – starting new lessons and challenges, refreshed, having rested and with growing motivation again. This little crisis helped me to cut other small pieces from my daily routine. Having spoken to some of the other students at Viking, it became apparent to me that the week plans I was practicing were not working. Now, instead of having 2-4hours Mon – Fri and 5-6h Sat-Sun, I am having Tue and Wed totally off, while having at least 4 hours of concentration on other days. Thanks to that, pressure is off, I can call anyone I want to or go to the city, meet friends, etc. on those days without any guilt and the outcome is still about 24 hours a week – at the smaller effort.

I am currently digging deeper in RSpec and instead of testing my code like before, I am building tests and gems. A lot of new stuff to learn and new projects are approaching. This subject, however, I will continue next time. Also, in a moment of being stuck, I am working on creating my website portfolio.

I would like to share my experience from creating Connect Four game. It’s as complex as nothing else I did so far. I had to rearrange the whole code a good few times completely. I think I spent about 30 hours to make it work, but now finding solutions to bugs are so quick to me as never, objects very familiar. I have also learned to clean my code better and keep methods smaller. On the top of that, I understood better traversing 2D arrays, detecting the state of complex objects, toggle players, building simple strategy AI player, etc.

So connect four game is a version of tic tac toe with a board six by seven and rules forcing a player to connect four pieces instead of three. The code, as always is available in my GitHub repository. The game works in Command Line. It allows playing against another player or a computer. The computer is an AI, whose goal is to put piece wherever it has already three pieces on the board. If it’s not the case, AI is meant to block any three pieces of its opponent, otherwise to choose a random place.

Needless to say, the most challenging part of the game was to make it look for diagonal four pieces or three pieces in various positions, i.e.,. piece_piece_space_piece – so third space can be filled to win. This role is taken by the PegSystem class in my game which is responsible for detecting relationships between different pegs/pieces.I am still learning from other people’s solutions, and still see a lot I can improve. In order to improve these skills I am reading now three little chapters every day from Rus Olsen book “Eloquent Ruby” – there is a good part of very minimalistic clean code included and practices in order to  improve my code in next challenges.

Screen Shot 2016-11-20 at 15.24.23.png

The code above is just a snippet out of the main game class. There ar five classes overall. Here we see my PegSystem class mentioned above that checks situation on the board and can be used by computer AI class to get messages about where are three pegs belonging to the opponent so he can block or three pegs of his so he can win when adding his own there in the next move. I have all included in  loop which is broken only when player makes the right decision about who he wants to play with… so I excluded situation where he enters ‘w’, as the only choices are C and U (I added extra method to make it capital even if player types small c as we know how players are 🙂 ). This method sets the main objects for the game as board object was initiated at the beginning. I am happy to start new challenges now  – need a break. I am going back to building my Rspec tests. Till next time.



Mastermind game

This is my first Object Oriented game in Ruby. I have recently finished it after working on it over few evenings. I felt excitement when played it during testing phase or just when I was looking for a bug. It brings some nostalgia for games I played in early 90’s. Games such as Arkanoid or Tetris and even some of the games like Wheel of Fortune which one could play in DOS environment, with no graphical interface. It was just a black screen with white letters describing scores, questions, answers, etc.

Here I am, a “creator” of a reproduction of the one of the most successful games in the ’70s – Mastermind. My code as usually is available in my Github repository.  I wished to be able to present it in the form of game anyone can play on my blog. Unfortunately, this is something t come in the later part of the course. This game can be run in Command Line environment where Ruby was setup beforehand. Here are few screenshots of the gameplay: screen-shot-2016-10-18-at-20-29-33

I have created six classes for this game. The player can choose whether to be the one creating code and letting the computer to guess the secret colour combination or to be a codebreaker and let the computer create a secret colour code. The human player class asks a user for the input of specific guess, while Computer codemaker class generates simple random code. In the similar fashion, I have created Human codemaker and Computer codebreaker – where the human player creates secret code and the computer just generates random colour combination guesses. The board class is responsible for storing colour combinations (just like in the real game) or calculates the feedback scores in the form of pegs – white or black.

For the feedback, I have created simple ASCII “graphical” interface. So we have six colour pegs and two feedback pegs which will inform the player how close were his guesses. Board class also renders colour guesses and feedback pegs on the screen.

During the building process, I followed the idea of creating small blocks – objects and creating communication between themscreen-shot-2016-10-18-at-20-56-45 in a low cohesive way. This become a difficult task as many times I faced an issue of their dependability while my intention was to avoid it – lessons are best learnt on own mistakes. I tried to follow simple rules like one task per method or Tell Don’t Ask.

I have started creating the whole game from pseudocode. After that, I was gradually replacing it with more detailed descriptions. Here I started thinking that if I require a particular action (let’s say adding pegs into the board), I would try to split it into most basic actions, pack them into methods and name them in self-explanatory fashion. It made the whole debugging process much easier. Before, whenever I started coding, I had to spend few minutes to recall how a certain method work, while now I could easily see what’s going on just by looking on it.

My plan is now to review some codes written by other developers of this or similar game and copy the best practicies of coding – so my next game is, even more, OOP and cleaner. The next game I am working on is Conect Four. I can’t wait to put my hands on.

As for the life matters, I can only say that it’s easier to plan a schedule than follow it. Unforseen life circumstances took me many hours out of my schedule, among them overtimes at work, meeting friends I haven’t seen ages, leakage in the house… and some adventures in personal life. Overall I spent over 16 hours last week on coding – about 8 hours on the goal.

Multidimensional duplication method (about passing by reference)

Another week behind, another challenges done. The levels of difficulty are growing every week now. I’m learning more about Objects / Classes and how to use them in written programs. The whole idea is still new to me, but it feels that I am moving forward, slowly, however.

I am building now Mastermind game. It seems that procedural code would complicate things at this stage. I am making it with three classes and number of instance methods. I am assigning one action to one method. It requires more planning than before when I was just building one huge block of code. I will share one of the finished games soon, but today topic is different.

One of the warmup challenges was to build deep duplication method to Array class. Here is what I have learnt. Let’s follow the below code:

screen-shot-2016-10-11-at-20-39-50We have passed/ assigned values to two variables. var1 hold a sting “house” and this particular string has its house in computer, pigeon hole or allocated a place in memory if you prefer to call it. That place didn’t hold “house” after we have assigned var2 to var1. What happened next is a new place in memory was given to variable var1.. the same location that belongs to var2. I tried to add an extra string in line 006 to var2 – but this operation was not saved anywhere.

I have decided to use shovel operator adding to var2 ” is just too small!”. So var2 is “shed is too small!” Nothing suspicious. However, if we check var1, it has changed as well, it’s not “shed” anymore. This particular location id in computer’s memory explains why this has happened. In fact, when adding the string to var2, we have added a string to the object living under number 70331642254620 in computer’s memory. This is the same location that var1 was referring to. This last verb is important – “referring.” The location in memory is what counts, rather than the name under which we store a string (i.e.,. var1). I did a similar operation on line 011 but the effect is different. The difference is that I have added the string ” is too small to live!” to var2 and assigned to var2. We see now that room number 70331642254620 was not taken by this operation. This assigning process assigned new room number 70331646357140 to var2. The old room is still referred by var1.

It’s easy to imagine that in a big program with many variables, forgetting about the above referencing logic and focusing on values must cause major issues. Having operations affecting an object stored in the same piece of memory may change values of other variables referring to this object id… variables which values shouldn’t have been changed like in the above example.

The solution is dup method – duplication function which creates copy of the same object but assigns different id in memory.
screen-shot-2016-10-11-at-21-06-30Here we have code where duplication breaks this cross reference, so var1 and var2 are two separate objects although having the same value of “shed”.

There is one thing with dup method worth to remember. This nice method doesn’t go too deep. So it can create new id for the same array like: [1, 2, 3] but it won’t for the part [“a”, “b”] in array [1, 2, 3,[“a”, “b”] ].

The example of that can be tracked below:

screen-shot-2016-10-11-at-21-13-48 Here is my turn. The assignment asked to create a method which would duplicate multidimensional array… no matter how many levels of arrays there is within the main array. I got lost in recursion but with a few hints from people in Viking I present below method for duplication of the multidimensional array.



I used map method which returns an array, so returns an object with a new id number. Map method iterates through every object of the first level through the array. Here comes recursion (arr1.deep_dup) which takes care of the depth of every object.It works even on beauty like this: deeper_arr = [ [ 1, [ 2, 3 ] ], [ 4, 5, 6], [ [ 7, 8, [ 9, 10 ]], [11, 12] ] ]If we imagine a table if columns and rows, I could say that map iterates through

It works even on beauty like this: deeper_arr = [ [ 1, [ 2, 3 ] ], [ 4, 5, 6], [ [ 7, 8, [ 9, 10 ]], [11, 12] ] ]

If we imagine a table if columns and rows, I could say that map iterates through the top row of these columns… ie. [ 1, [ 2, 3 ] ],   [ 4, 5, 6],   [ [ 7, 8, [ 9, 10 ]] etc. The condition in line 4 checks if the ie. [ 1, [ 2, 3 ] ] is an Array and if it is, it calls the same function deep_dup to get to the next level: 1, [ 2, 3 ], and again iterates though 1 returns it as it is and when it gets to the  [ 2, 3 ] – realizes it’s Array and go deeper again (easier to imagine by the fans of “Inception” or “Primer” I think). Once it gets to 2,3 level, returns them as they are and map method moves on to the next column from top to bottom which will be now   [ 4, 5, 6]. All this saved each time in new memory id which is what map enumerable function does.





Object Oriented Ruby

Another intensive week behind me. I spent over 23 hours on coding and solving different challenges or reading Ruby Programming by David Black. I have finally submitted my solutions of a large RSpec challenge. Last exercises took me the most of the time – which was about 12 hours to crack the problem. The joy, in the end, paid off. I was proud of my approach as it wasn’t easy an easy ball to play with.

The last challenge I mean is again purely Test Driven Solution with Rspec file waiting. The below method is adding extra function to the Fixnum class so having “12345.in_words” will give us “twelve thousand three hundred forty five.”  I didn’t think it would be that difficult when I started. I thought about two ways of approaching this problem – either creating string or array and working with that to find a solution or by dividing and modulating numbers. I used recursion and numbers themselves. Here is my code which works for all numbers up to 999 trillions:


As I am proud bot the approach,  I am not that pleased with the code solution above. I have started getting deeper into Object Oriented Programming which makes me look at the above code as difficult to follow, consisting one God method, containing many elements that depend on each other making it difficult to change later or look for a bug (there is no bug here, however)… The above code is just not clean; I am practicing ways to change this practice.

The idea of OOP is simply beautiful. Instead of having one procedural script – so called God method which does everything,  we have class object with small little parts that are responsible for one thing, and one thing only. They are independent, and we are not bothered about what is happening inside of them. Well, we know to this minimal degree where we can say what it does, not necessarily how.

If you remember my version of Tower of Hanoi published earlier, look at it now in my repository.


It’s a class and we can make it running by loading it in IRB and instantiating a new object with i.e.,. p = and then using the method on this new object will run the game. It is almost like 3.even? or new_array.pop(). Yes, another method to an object, but now not like the one Ruby created (it is said by the way that everything in Ruby is an object), but object which mechanism I have designed and created… can feel sort of like Matsumoto’s assistand adding another piece to Ruby. This game is a big class, but it might be an object in another game which gives those answers that I thought it to give in the first place. It feels like powerful tool was handed in. However, difficult one.

Here is my another attempt on making Rock Paper Scissors game in OOP. This time, it consists of three classes – one for the human player, the other for the computer player and last is the game class. All saved in separate files. I tried to split them up as much as I could after devoting hours into building it. Having watched Ben Orenstein in action recently makes me want to master refactoring very much.

Another useful and exciting tasks were involving using Procs and Blocks to create a replica of each, inject, ma, reverse… methods, or even something useful like benchmark method to measure time at which specific block method works out a solution.

As for personal life, it was a great week. There were good news about my dad, he will get treatment this week, and new examinations brought more positive results. I started to turn off my phone during studying – helps a lot. I have filled out my google calendar with all the stuff I do in a week – helped me to focus on coding on Mon -Fri exclusively and afternoons on weekends. This week job keeps me busy as rarely, and I have some overtimes every day so fighting again to have every hour I can devote to studying.

The third (edited) stage of the road

I continue where I left off. I have made my decision – I am deferring my last year of college. It wasn’t an easy decision. It means I will be able to come back to College in 1.5 years, the structure of the program may change, and credits per each module may change as well. However, this way I can put more attention to Viking School. This is the beginning of the third stage – edited, as previously I hoped I would be able to compromise Viking with College.

Now, I plan this stage will take up to mid-February. I have already scheduled my google calendar with all activities: laundry, cleaning, work, shopping, workouts, time for friends, etc. Believe me when I say this schedule is packed pretty well. I want to spend 4 hours studying on Mon-Fri and about 5 hours on Saturday and Sunday. The fourth, following stage, will be about advanced projects with Viking and be hunting for the new opportunities – but this is enough for now about this far future.

This week was another low of my activity at Viking due to the above indecision, the evening spent at local Ruby Ireland meetup, classes at college (I wanted to see what I am losing by signing up the deferral letter), unable to succeed in the Test exercises with RSpec and bad news from my family. Going back

So I will like to go back through that list in retrospection. It occurred this week that my dad is seriously ill. The news hit me hard and instantly I felt sorrow and powerlessness. He is in the hospital now, and it will be next couple of days until I will find out if his condition allows for treatment. I am optimist nevertheless.

As for RSpec exercises, I stuck on creating an extension to Fixnum class in Ruby that would allow me to translate integers into names i.e.,. 123.in_word => “one hundred twenty-three.” I decided to go with pure integers, division, and modulus instead of using arrays and string. I think I spent about 6 hours already and can’t figure out how to change numbers above 20. I have published my problem on slack and hoped to move on tomorrow with someone’s help. I am moving slowly deeper into Object Oriented Programming.

As for college, I attended a very exciting class about web development which is about PHP and MySQL. I thought MySQL wouldn’t be that interesting. I am an advanced user of Excel which is my favourite part MS Office package and also have an experience in MS Access. It is very uplifting to see these familiar concepts in MySQL – starting from definitions and tools to how tables are created and data operated. Thankfully with Viking, these lessons are not lost.

As for the Ruby Ireland meetup, I have met nice people who helped me to make decisions this week. The main topics of the meetup were VIM – yes this old school editor and Websockets for advanced participants. I also come across this interesting comparison of VIM and Sublime Text. VIM seemed to be very unfriendly to me as a user at the beginning, but I need to admit it has its advantages.

This is it for this week.  I hope to present much more of my work in the following posts.

“Test First Ruby with RSpec 3” and life challenges

Last week I was facing ordinary life situations, and I admit – progress was not as impressive as before. I stuck for a while on the project – Test First Ruby with RSpec 3. The whole delay started on Tuesday – for about 4-5 hours I couldn’t figure out why the rake command doesn’t work. It was essential to start this small course which is another project in Viking. I was sharing on Slack various behaviours hoping someone had come across something similar. My problem puzzled everyone that tried to help me. Just before midnight, one of the engineers in Viking figured out the cause. What a bizarre bug/issue! Whenever I typed rake command, CLI spit out lines with “Loading Error.” I forked the repository correctly, I have installed rspec as instructed, I have created a hello.rb file with an adequate method in it to avoid common loading error… and still the problem prolonged. It occurred that I shouldn’t have cloned the Github project into folder: Viking Code. This seems like nothing unusual, but the spaces in the name of this folder were causing the issue. The rake command was reading the folder name till the first space in the name just as if it was folder names “Viking.” Changing the name into Viking_Code – sorted out the issue.

On Wednesday I started pushing solutions, from exercises 1 to 5. I was happy with my progress, especially sorting out the Pig Latin challenge I felt was a big success. I found myself stuck on Thursday… I realized I need to start digging into lessons about classes as it’s my weak point (classes are the next subject after the RSpec mini course). I managed to push about three more challenges after that.

Again on Friday, I paused with progress – I had to stay at work until 10 pm and help my college with large printing request. That Friday took away a lot of very precious time. I managed only to push one more exercise on Saturday; Cleaning, laundry, shopping, dinner made half a day flew in a blink of an eye. I also met few friends to “untask” the orientation of my mind.

I spent most of Sunday on reading about classes and managed to have completed 10 out of 15 exercises. Moreover, timetable in college was announced earlier last week and from now on every evening on Monday, Tuesday and Thursday I have classes at college. The outcome is pretty clear – I may not have enough time to devote to the Viking course. I can push like that, but I am asking myself – is it worth to do so much at the expense of my health?

Tonight I have just finished my first class in college – Multimedia Programming as they call it, which is mostly about coding in p5.js. It is amazing JavaScript library that one can easily create with animations on websites, graphic designs with high interactivity triggered by ie. click of a mouse, a sound or even movement in front of the camera (almost like augmented reality). It is powerful and very exciting stuff as you can see from these examples.

Overall, the truth, however, is bitter. There is too much going on. In these circumstances I have two options: I can either defer the college course or quit my job. The second is a scary scenario and very risky. It would have been easier to swallow when being able to find a non-paid internship as a junior web dev. This way I could at least feel of doing progress. The first scenario, however, means I will be able to go back to college in about a year and a half, which feels like a neverending story, but may as well upskill my Viking skills. I haven’t made final decision ye. I am still looking at my options and trying to see how I feel about it. I want to make up my mind by the next Monday. This indecisive limbo is very unhealthy.

To be continued…

My best logical game in Ruby so far

Last week was about keeping my “work – study – life” balance at risk. Nevertheless I have reached y goals. After I finished my last post a week ago, I went to DublinJS meetup, that was Tuesday. My goal was to meet some people, practice my socializing skills and … learn something new. There must have been over 100 people, 15 speakers, each of them giving a short talk for about 5 minutes – mainly about JavaScript. I will be honest here – there was a lot of stuff I didn’t understand… (I was possibly the only Ruby guy there). Some of the topics were: TypeScript, 3rd Party JS,, Web Scrapping, iframes, SVG Animation, feedback.js – the last two are the one I will add to my set of tools (more details here).

On the good side is that I met few people, some of whom, where in a very similar situation at the beginning of their road about a year ago. This was very uplifting to hear. Some of the further stages of their web dev road (where mastering socializing is first) was being one of the speakers that night. One of them that I met, wasn’t sure about the high level of her talk but was proud she got a courage to do it in front of the crowd. So overall, different people, on different learning stages with their very own challenges. Believe me, having identification with them makes more comfortable to be within this unfamiliar group (in a way). Having spoke about my situation and asking questions like “how did you start, what was your road” – trigger people to share more about them. This helps crumble the wall between me as the newcomer and the rest of the group (experienced perhaps). That day, I got home late – didn’t do much for the Viking course.

In the week, I have finished my Ruby warm up challenges. The project was to create small programs solving each of a given seven problems. The image below shows the outcome of one of them: a simple graph of occurrences of outcomes when rolling six dice about 100 times (i.e.,. 18 was a score in two rolls and 20 appeared four times). My repository.


The other were to check what are the anagrams of the given word (at the moment my solution consists of a dictionary of few words as I haven’t implemented file input at this stage). Another interesting problem was to find two days in an array of values, which are indicating the greatest profit ( the difference between two values) – very useful to some “tape reading” activities (especially when looking at stock charts is providing too much information).

Screen Shot 2016-09-12 at 21.58.59.png

The above solution, I admit, is not the most efficient. This is to my records that at this day I can create this type of code. I believe I will get better and will be able to come back here and publish a better one in the near future! My goal is now to push as much as I can for the next two-three weeks before college starts. At this stage my code is tested with various edge scenarios and answeres exactly the question set in the challenge. However, if you have any suggestions – please DO write in the comments. I appreciate any way to learn more.


One of the new skills I’m working on is debugging. I was playing with the above code and puts “DBG: value_max = #{value_max.inspect}” in the middle of it – I used it to unbug the the program as it wasn’t working straightaway the way I wanted.

Another element binding.pry – belongs to Ruby debugger and Jim Wirich gave an excellent introduction to it. One of the things I owe to Jim also is this lovely Sublime snippet:


after typing “dbg” and clicking tab, display on the screen DBG: value_max = #{value_max.inspect}” which I can instanly fill out with the variable I want to monitor.  Pry on the other hand is allowing to follow every frame of the working program and see what is going on up to the final result is given. It really helps a lot.

My great project this week is the game Tower of Hanoi. We have three rods and one of them is filled with disks (we can decide how many discs we want to use, so the more of them the more dififcult the game). I am happy I managed to create the whole program and provide output to the user in the grahical form. The example of that is presented below and in my github respository. This code is in a procedural style; classes are soon to come.


I am learning now RSpec basics and already have a bunch of challenges to solve. This is hands on Test Driven Development. After that, I head to Object Oriented Programming.

My further road will be accompanied by this baby here (whenever I find time):