MATLAB Songs – My First M-File

Last night, I was wandering aimlessly when I found a youtube link shared by Mathwork’s facebook. The link was about a song called my first m-file and it is about creating m-file and dealing with the red text that pops up in the console window (We hate red in our console window). The song is nice and the lyrics also reminded me of my time when I was learning MATLAB and when I was stuck in my thesis debugging my code (as you probably have read on my Thesis log that was posted in this very log). So, I decided to asked the uploader via youtube comment if I can have the MP3 version of the song. Hopefully he/she’ll agree to it.

While waiting for his/her response, I decided to share his/her song here. So, here is the song of my first m-file. Hope you enjoy it.

Regards,

oX_R

Posted in Uncategorized | Tagged , | Leave a comment

Coursera and My Alibi

Wow, it has been two month since my last post. Now it’s March and I’ve finished my language training and just started my life as an ordinary salaryman in Japan by the first of this March. And yup, during these two months, no new code or new tutorial or new anything was added in this blog. Yup, I was unproductive although I have been stating in my resolution for this years that I’m going to be more productive. Well, at least I going a good reason alibi to be unproductive for this blog. So, here it is my alibi:

In order to keep from wasting my free time with movie or 9gag, I decided to take an online course from Coursera. I heard about this site from a friend 2 years ago but never have the chance to try it. Now, that I have quite free time during my language training, I decided to try to take one course in there.

For those of you who do not know what Coursera is, here is its logo.

coursera logo

And here is a brief explanation about it:

Coursera is a web-based learning site where you can take an online course from several respectable university from all over the world. The great thing a bout this website is that it is free of charge and no admission test is required to join course (which is good because there is no way I pass the admission test for these major university). There are a lot of courses on different subject in Coursera, ranging from engineering to art. For every course you take, you must watch a weekly posted video lectures, do some quiz and assignment on weekly basis, and do the final exam at the end of the course. The length of courses is relatively short, it is like around 8 weeks but might be different for each course. While it is free and no admission test , I still don’t know if I will get some kind of distinction or recognition if I pass the course, because up to now, all the courses that I took hasn’t finished yet (Well, one course almost finished, and I’ll let you know how it goes).

After looking at a very long list of courses available to take, at the end of December, I decided to take Game Theory because I thought I could learn something about making video game and so on. However, I was wrong. Although the course revolves around game playing, it is more about decision making and making some strategy. Nevertheless, it turned out to have its own interesting point and I ended up finishing the entire course (I just did my final exam and are waiting for the result now), although at first I think I may quit in the middle of the course.

In the game theory course (or should I say in most courses available in coursera), I  just downloaded and watched several video lectures that are posted weekly and did the exercise and assignment to be done every week. This turned out to be not as time consuming as I think. I just spent around 1 hour a week to watch the lectures and probably around 2 hours to do the exercise and assignment. So, somewhere in early February, I decided to take one more course.

So, once again, I looked at a long list of available courses and finally decided to take Algorithm (part 1) course. This class revolves around programming and I found the course really interesting, because it taught us to be concerned about run-time and memory when doing some programming, hence the algorithm comes into play. In this course, besides weekly exercise, there are also weekly programming exercise in Java. Then I taught this course was good for me because it will force me to learn Java, yet another programming language that I haven’t touched. Unfortunately, the programming assignment turned out to be very hard for me. Maybe it is because of my lack of fundamental in OOP, nonetheless, these programming assignments made me spent quite great deal of time to finish. Thus, become my alibi for my dormancy over the last two months.

Me Before Coursera

Me in My Free Time (Before Coursera)

Me After Coursera

Me in My Free Time (After Coursera)

Fortunately, the game theory class will end on the 10th of this month and I’ve cleared everything that I have to do. So, I will be having some free time and will start being active in this blog (hopefully).

Nevertheless, I think that Coursera is a good place for those of you who have some free time and want to learn something new and I really recommends it. It is free so you got nothing to lose. Even if they does not give any recognition or distinction or something if you pass the course, it shouldn’t be a problem because you got whole new knowledge from it. So, I recommend you to try it.

Well, that’s all that I’m gonna write for this post. After this, I’m gonna have to get back to do the weekly programming assignment (Hiks). Note that although I might seems to be pro Coursera in this post, please keep in mind that I’m not associated with Coursera in anyway. I’m just a member trying to share:D

Regards,

0X_R (not a Coursera Associate)

Posted in Uncategorized | Tagged | Leave a comment

2013 Resolution

It is almost a week in 2013. I took a quick look back at my 2012 resolution and I decided to evaluate myself in terms of my performance for this blog. So, here it is, the evaluation for each point that I made last year:

  • Master C, C#, and/or C++Yup, I was planning to learn at least C# in 2012 because of one projects. While I did learned a little bit about C#, I still haven’t master it yet and there are a lot of this that I haven’t fully understand in terms of OOP (Yeah, OOP is hard, Know I now why information engineering have always has the highest passing grade requirement). I did learned the basic of creating class and its methods and properties and managed to created one, but I still don’t know why did I have to put static or public or anything else. Sometimes the code didn’t work and I just tried putting static and it suddenly worked:D. I still don’t know why. So, for this resolution, I think I must evaluate myself as Failed.
  • Have 5-10 more code in my MATLAB Aerodynamics Toolbox. Yeah, had a plan to expand this toolbox, but it turned out that I haven’t add anything new since last year. So, without doubt, this resolution was: Failed!
  • Have 5 more code in my MATLAB Fun Toolbox. In 2012, by seeing my list of post in this year, I can see that I have posted DoodleJump, Congklak, VirusShooter, Tetris, and Bulls-and-Cows game. It was five games althought the last game (The Bulls-and-Cows) was posted one week before 2012 ended. So, for this resolution,  I can say: Barely Passed! (Fiuh, finally, something that I fulfilled).
  • Have 2 or 3 more files in mathworks file exchange (MATLAB Central). Seeing my profile page in the Mathworks website, I can see that I posted two new code in 2012. It was Congklak and VirusShooter. So, without doubt, for this resolution, I  can say: Barely Passed again! (Yeah!).
  • Finish my unfinished debt for this blog. Well, to be honest, I completely forgot that I still have a lot of unfinished job in this blog. If I wasn’t reading this, I’d probably didn’t remember at all. I have been doing nothing completely for this part. So, this one is: Failed!

Well, two pass out of five. If this was a college, I will get a D and will have to retake the subject again. Thank god it is just a blog. However, I realized that I have to change. I also realized that I posted more programming things than aerospace engineering things in 2012. This made me embaress the ‘All about Aerospace Engineering’ that I put as my blog’s tag line. So, I really need to change things around this blog. And, to do that, here is my resolution for 2013.

  • Focusing only on potential flow, remake the aerodynamic toolbox into library-based instead of individual m-file per function (This is because I’ve learned a little about OOP) and separate the library files and the individual GUI-based m-file on the Aerodynamics Toolbox to make it neater.
  • Create 2 more code for my MATLAB Aerodynamics Toolbox
  • Create 2 more code for my MATLAB Fun Toolbox
  • Post two more code in mahtworks file exchange (MATLAB Central)
  • Finish the unfinished debt for this blog.

Well, I think that’s all the resolution for this year. I’m expecting to be busy because of my work that will start on March, so I hope I’m able to meet those resolutions. Now, if it is not to late, I would like to say Happy New Year! May this year be better than the previous one.

Regards,

0X_R

Posted in Uncategorized | Leave a comment

Bulls and Cows – A Number Guessing Game

During the first year of my undergraduate studies, I lived in a boarding house together with around 10 other students. Among of them, there was a nerd programming expert that excel at every programming language that I know at that time (At that time, I only know C++). One time, he has a programming assignment for his class and for that he made a number guessing game. At that time, the game was called (or at least that is what he names it) Dolpeng. However, after a quick google search, I just found out that the game’s real name is Bulls and Cows. The game get him an A, so, he was so proud and shared his game in the network (along with other ‘adult’ stuff that he downloaded for us). And I   accidentally ran into that game folder when I was browsing through his ‘adult’ stuff was curious, so I take a quick look at it.

The game (Bulls and Cows or Dolpeng or whatever the name is) is a number guessing game. It is played by two players only. Each player must choose their own secret number that consist of 4 non-repeating digits (for example: 1457). A number with repeating digits like 1272 cannot be used. After deciding the secret number, each player takes turn guessing the other player’s secret number. After a player (guesser) make a guess, the other player (guessee) must evaluate the guess and tell the number of bulls and cows of the guess as a hint for the guesser. Then the players switch turn until a player correctly guess the other player’s secret number.

Evaluating the guess and providing hint for the guesser is done as follows. If in the guesser’s guess, there is a digit that also exist in the guessee’s secret number and that digit is located at the same position as it is on the secret number, it is called bull. If in the guesser’s guess, there is a digit that is also exist in the guessee’s secret number but it is not  located at the same position as in the secret number, it is called cow. From the number of bulls and cows of the guess, the guesser must be able to predict the guessee’s secret number.

For example, if the guessee’s secret number is 1250 (This number, of course, must not be told to the guesser) and the guess is 4510, then the number of bulls is 1 (The bull is 0) and the numbers of cows is 2 (The cows are 1 and 5). Note that sometimes a guess may not contain any bulls or cows at all. To make it clearer, here are several list of guess and their respective numbers of bulls and cows (The secret number is still 1250).

Guess: 1250, Bulls: 4, Cows: 0 (Guesser guessed correctly).
Guess: 4310, Bulls: 1 (0), Cows: 1 (1).
Guess: 1273, Bulls: 2 (1 and 2), Cows: 0.
Guess: 5120, Bulls: 1 (0), Cows: 3 (5, 1, and 2).
Guess: 5789, Bulls: 0, Cows: 1 (5)
and so on...

Okey, that’s it about the game. Now back to the story.

At that time, the game that my friends make was designed to be able to guess our secret numbers. So, what the game does was tells me to choose a secret number (in my mind, I did not input my secret number to the game) and asks your input of the number of Bulls and Cows for the guess that it made, and after a few guess (I forgot how many), it correctly guess my secret number. At that time I was really blind to programming and was really amazed by his game. I thought that this guy is a Genius that someday in the future he will win a Nobel prize or something like that. But it turned out that I was wrong. He wasn’t that genius (because he haven’t win any Nobel up to now). It is only me that was too idiot to understand it.

Now that I’ve become smarter than I was, I finally found out how to solve the game. So, I decided to make similar game for my MATLAB Fun Toolbox. So, long story short (I notice that this is the most freuqnt pphrase that I use everytime I announce that I’ve created something new for my MATLAB Fun Toolbox), here it is, the game’s screenshot and a video capture of the game.

MATLAB-BullNCow_01

MATLAB-BullNCow_02

I provided four modes for the game. The first one is where you play solo to guess a secret number. Nothing special here other than doing Bulls and Cows evaluation for player’s guess. The second one is where COM guesses your secret number. This mode is what was shown in the two video captures above and I think that this mode is the most interesting mode, because COM fill be able to found out your guess in not less than 8 guesses. I’ve done some simulations on the ‘solving’ algorithm and the result shows that the algorithm needs 5 guesses in average to find out the secret number with the worst case scenario of 8 guesses. I will talk about the ‘solving’ algorithm in the later part of this post (I found out that hyperlinking post to itself is a little bit weird but I’m gonna do it anyway:D, just don’t click the link, it is useless:D). For now, let me finish explaining the game mode.

The third one is player versus COM. It is where both player and COM take turns guessing each other’s secret number. This mode is like combining the first and the second mode altogether in turns. The fourth one is for player versus player. Yup, player versus player. You must be thinking, was do we need this mode? You can just play it together with your friends on a piece of paper. Why all the trouble? Well, the reason is that when playing the game, players often make mistake when evaluating its opponent guess. It might be on purpose or not, but nevertheless, it is not fair to the guesser. So, as a fail safe (or a referee, whatever that is), in this fourth mode, both player’s guess and Bulls and Cows number are being checked by COM for its consistency. Don’t worry, COM can do that without you inputting your secret number to the game (and risk your opponent knowing it by peeking). Instead, the ‘solving’ algorithm (that I mentioned earlier) are applied. This way, no one can cheat!

So, that’s it about the game. Now, let’s talk about how to solve and beat the game, hence code the ‘solving’ algorithm. Well, I’ve looked up on internet and there are a lot of methods to solve the game. Some uses fancy stuff like Genetic Algorithm and other optimization method that was too high for my intelligence. So, I decided to use one simple method: the elimination method. This method is actually a semi brute-force method and is not ideal is you are looking for optimization, but, to the hell with that, this is the only method that I can understand, so I’m just gonna use it.

Elimination method is done by firstly creating a list of all possible numbers for Bulls and Cows game. This range from 1234 to 9876 and the permutation in total will have 5040 possible combinations (5040=10*9*8*7). From this list, a number are randomly chosen as the guess. The guess then will be evaluated by user/player and the number of Bulls and Cows will be given (This is the reference number of Bulls and Cows). Then, all numbers in the list are evaluated against the guess for the number of Bulls and Cows. All numbers in the list that yield different number of Bulls and Cows when it is evaluated against the guess will be removed from the list (Note that I emphasized on ‘and’ because both the number of Bull and Cow must be the same with the reference or it is eliminated). From this the list will now have fewer number and the second guess is made by choosing randomly again from this list. This continues until all the numbers in the list are eliminated except one, which is the secret number itself.

Let’s try this for example. Let’s say that your secret number is 1234. If a guess of 1357 is made, it will have number of Bulls of 1 (1) and number of Cows of 1 (3). Then, 1357 is evaluated for all 5040 numbers in the list. This will yield 5040 combination of numbers of Bulls and Cows. The number whose number of Bulls and Cows is not 1 are eliminated from the list. For example, number of 1357 from the list will yield 4 Bulls when evaluated against 1357 (the guess). This number will be eliminated from the list because it is not possible that this number is the secret number. (I hope you understand that because I don’t how how else to say it).

The cool thing about this method is that if somewhat there is a mistake from user/player when he is evaluating the guess (either accidentally or not), all numbers on the list will be eliminated, leaving nothing in the list. When this occurs, no doubt someone has made a mistake. I also read it somewhere else that you can further optimize this method by ‘smartly’ choosing guess from the list instead of doing it randomly. But it complicates tings too much and it only improve the average guesses needed to find the secret number insignificantly, so I decided not to included it and go on with random guess from the list.

Wow, that was a lot of writing for one post. I hope you can understand what I mean and wasn’t falling asleep in the middle of reading this post. As usual, the game is downloadable from my MATLAB Fun Toolbox page. Please leave any critics or comments.

Regards,

0X_R

Posted in Uncategorized | Tagged , , , , , | 1 Comment

MATLAB Tetris – The Main Algorithm

As I promised (after more than a week), here it is, the explanation for my MATLAB Tetris code.

Board Concept and Its Representation

Since Tetris will involve a board or field of blocks, how to represent those fields in the code must be determined first before writing the code. This ‘field’ array will be modified throughout the game and will be used for visualization. For simplicity, I used a standard 20×10 array for this ‘field’ array (because Tetris field is 20 blocks in height and 10 blocks in width). However, to avoid confusion when visualizing the game, I let the first row of the ‘field’ array represent the most-upper blocks on the field instead of the most-lower blocks, and so on. In this ‘field’ array, each elements will represent whether a block in the field is occupied or not and what color that occupied in. 0 means the block is not occupied, while a number of 1 to 7 respectively represent a different block color.

Aside from that, a representation of the falling Tetris object, the shape database, and the color database must also be determined. Since tetris object is always consist of four blocks (hence, the name is Tetris), I decided to use three 1×4 arrays to represent the falling object, ‘r_current’, and ‘color_current’. Each element on those arrays respectively represent each falling block position in field row and column and it color. Thus, as the database for the falling blocks’ shape, the following constant variable are declared in cells format as follows:

shapemodifier_x{1}=[3,4,1,2];
shapemodifier_y{1}=[1,1,1,1];
shapemodifier_x{2}=[2,2,3,2];
shapemodifier_y{2}=[2,3,1,1];
shapemodifier_x{3}=[2,2,3,2];
shapemodifier_y{3}=[2,3,2,1];
shapemodifier_x{4}=[2,2,3,2];
shapemodifier_y{4}=[2,3,3,1];
shapemodifier_x{5}=[3,2,2,3];
shapemodifier_y{5}=[2,2,3,1];
shapemodifier_x{6}=[2,3,3,2];
shapemodifier_y{6}=[2,2,3,1];
shapemodifier_x{7}=[2,2,3,3];
shapemodifier_y{7}=[1,2,2,1];
shapemodifier_x{8}=[2,2,2];
shapemodifier_y{8}=[2,3,1];

By using this cell formatted shape database, I can easily created random falling block shape by creating random integer as the cell index.

To represent a color, similar variable is also declared, but array format is used instead of cell format. In this variable, each row represent a color code where the columns respectively represent red, green, and blue color intensity. This variable will be used later to visualize the game.

colormodifier=[1,0,0;...
               0,1,0;...
               0,0,1;...
               1,1,0;...
               1,0,1;...
               0,1,1;...
               1,1,1];

The General Gameplay

As in the previous game, this game also uses while loop as its main loop for the gameplay. However, unlike the other game, I use two while loops (one is nested) for tetris. The main  (outer) loop is will be used to cycle the game until it ends (game over), while the nested loop is used to accomodate the falling of one Tetris object from the top to the bottom. Since usually Tetris game provide a preview of the next upcoming block, the main loop will be initialized by declaring the next falling Tetris object (its shape and color) randomly. In the main loop, the current falling object is declared from the next falling object and a new next falling object is selected again, randomly. Next, the current falling object is placed in the field and a check is done to see if the blocks has reached the top of the field, hence, game over. If it is not, then the nested (inner) loop is executed to move the falling object down while the player move it to the left or right, rotate it, or even color swap it. After the falling object reach the bottom, the nested loop will be exitted and continued with a check to see that a complete block set has been made (The definition of complete block set differs for each game mode. Check out the MATLAB Tetris preview to see and understand the three different game mode). If yes, the field must be re-modified accordingly (also differs for each game mode). The following code shows how the main (outer) loop is laid out:

%Creating first tetris block as loop initialization
switch gamemode
  case 1
    shape_next=ceil(7*rand);
    color_next=7*ones(1,4);
  case 2
    shape_next=ceil(7*rand);
    color_next=ceil(7*rand)*ones(1,4);
  case 3
    shape_next=ceil(7*rand);
    color_next=ceil(7*rand(1,4));
end
%Performing loop for the game
gamestat=true;
while gamestat
  %Setting next tetris block as current tetris
  shape_current=shape_next;
  color_current=color_next;
  %Generating the next tetris block randomly
  switch gamemode
    case 1
      shape_next=ceil(7*rand);
      color_next=7*ones(1,4);
    case 2
      shape_next=ceil(7*rand);
      color_next=ceil(7*rand)*ones(1,4);
    case 3
      shape_next=ceil(7*rand);
      color_next=ceil(7*rand(1,4));
  end
  %Creating preview for the next tetris block
  c_next=shapemodifier_x{shape_next};
  r_next=shapemodifier_y{shape_next};
  %Drawing preview
  preview=addblock2field(preview_nt,r_next,c_next,color_next);
  graphic_p=drawfield(preview,[3,4],square,squaresize);
  imshow(graphic_p,'Parent',previewaxes)
  %Placing current tetris block in the field
  c_current=shapemodifier_x{shape_current}+3;
  r_current=shapemodifier_y{shape_current};
  %Checking for game over
  if ~checkblockposition(r_current,c_current,field)
    %Stopping game
    gamestat=false;
    break
  end
  %Moving tetris block
  playstat=true;
  pausestat=false;
  while playstat
    ... #To be explained
  end
  %Checking block position and updating field
  if (gamemode==1)||(gamemode==2)
    %Updating tetris block into field permanently
    field=addblock2field(field,r_current,c_current,...
                         color_current);
  elseif gamemode==3
    %Updating tetris block into field permanently
    field=addblock2field(field,r_current,c_current,...
                         color_current);
    %Forcing hanging blocks to fall down
    field=forcefalldown(field);
  end
  %Checking field for complete block
  if (gamestat==1)||(gamestat==2)
    ... #To be explained
  elseif gamestat==3
    ... #To be explained
  end
end

As stated previously, in this code, three variables (‘r_current’, ‘c_current’, and ‘color_current’) were used to define the falling object’s condition. These variables were initialized by choosing randomly from the ‘shapemodifier_x’ and ‘shapemodifier_y’ array declared previously. Before the nested loop begin, those three variables represent the falling object’s position at the middle top of the field (that’s why ‘c_current’ is initialized by adding it by three, that is to make the falling block placed in the middle top of the field). In the nested loop (the while playstat loop), these three variables will be updated over time, as it slowly falls down and as player move/rotate it. At the end of the nested loop, these three variables will represent the falling object’s condition at the most bottom part of the field (final condition). Then those final conditions are used to update the ‘field’ array by using addblock2field function. Because of simple representation of ‘field’ array and the falling object’s variables, the addblock2field function is simple and can be written in five lines as shown below. This means that the falling blocks has been added permanently to the ‘field’ array (Later when explaining the nested while loop, you’ll understand why I say permanently). After the falling blocks are permanently added, a check was done to see if there is a complete block set.

function field=addblock2field(field,row,col,color)
  for dotID=1:numel(row)
    field(row(dotID),col(dotID))=color(dotID);
  end
end

Notice that in the main while loop above, several local function was used other than addblock2field function. forcefalldown function is used to force all hanging blocks to fall down in the third game mode (hence no hanging blocks in this game mode), while checkblockposition checks the validity of the falling object’s position (thus, preventing stacking two blocks in one position). Aside from that, a special local function, drawfield, is also used to generate an image visualization of the current ‘field’ array. These local functions will be described later.

Falling Down The Tetris Object

In the main while loop, the falling objects is placed at the top of the field, somewhat enters the nested loop, and then comes out the final position of the falling objects. What happened when the falling objects slowly falls down and being moved/rotated by player is accommodated in this nested loop. In this nested loop, for each single loop, the falling blocks position was moved downward by one block (hence, slowly falling). However, to allow player to control the falling blocks, another two while loops are executed before the falling blocks are moved downward. The first while loop is the pause loop, and as the name suggest, it is created to accommodate game pause. The second one is the control loop, where in this loop, for a set amount of time (depending on the game speed), the downward moving is delayed, thus providing player control over the falling blocks. For every action done in this control loop, a check is done to make sure that the action does not make the falling blocks go outside the field or stack over the occupied blocks. If it does not, the action is approved and the falling block’s variables (‘r_current’, ‘c_current’, and ‘color_current’) is updated. Then, the visualization was updated by redrawing the field, however, it should be noticed the ‘field’ array is not updated yet. This is done because ‘field’ array is the reference for the checkblockposition function. Thus, it will only be updated outside this nested loop, after the falling blocks reaches the bottom. A set amount of time (and a set of control chance) the control loop is exited, the falling blocks are moved downwards by one, and the nested while loop continues from the top until the falling blocks can be no longer moved downwards (hence, it has reached the bottom).

while playstat
  %Creating infinite loop to accomodate game pause
  while pausestat
    pause(0.01)
  end
  %Creating and displaying temporary field
  tempfield=addblock2field(field,r_current,c_current,...
                           color_current);
  %Drawing graphic
  graphic=drawfield(tempfield,fieldsize,square,squaresize);
  imshow(graphic,'Parent',mainaxes)
  %Providing loop to move the current tetris block
  loopID=0;
  maxloop=max(gamefps-gamespeed,1);
  while loopID<maxloop
    %Creating checkpoint for time counter
    tic
    %Calculating future position
    switch movestat
      case 'none'
        r_temp=r_current;
        c_temp=c_current;
      case 'left'
        r_temp=r_current;
        c_temp=c_current-1;
        pause(1/controlspeed)
      case 'right'
        r_temp=r_current;
        c_temp=c_current+1;
        pause(1/controlspeed)
      case 'rotatecw'
        [c_temp,r_temp]=rotate90cw(c_current,...
                                   r_current,...
                                   c_current(1),...
                                   r_current(1));
        pause(1/controlspeed)
      case 'rotateccw'
        [c_temp,r_temp]=rotate90ccw(c_current,...
                                    r_current,...
                                    c_current(1),...
                                    r_current(1));
        pause(1/controlspeed)
      case 'forwardcolorshift'
        r_temp=r_current;
        c_temp=c_current;
        col_temp=[color_current(:,end),...
                  color_current(:,1:end-1)];
        color_current=col_temp;
        pause(1/controlspeed)
      case 'backwardcolorshift'
        r_temp=r_current;
        c_temp=c_current;
        col_temp=[color_current(:,2:end),...
                  color_current(:,1)];
        color_current=col_temp;
        pause(1/controlspeed)
      end
    %Checking future position
    if checkblockposition(r_temp,c_temp,field)
      r_current=r_temp;
      c_current=c_temp;
    end
    %Updating tempfield
    tempfield=addblock2field(field,r_current,c_current,...
                                   color_current);
    %Drawing graphic
    graphic=drawfield(tempfield,fieldsize,...
                      square,squaresize);
    imshow(graphic,'Parent',mainaxes)
    %Controlling gamespeed
    pause(1/gamefps)
    %Advancing loop
    if accelstat
      break
    else
      loopID=loopID+1;
    end
  end
  %Moving the current tetris block downward
  r_current=r_current+1;
  %Stopping the current tetris block
  if ~checkblockposition(r_current,c_current,field)
    r_current=r_current-1;
    playstat=false;
  end
end

It should be noticed that in this nested loop, two variables, ‘pausestat’ and ‘movestat’, exist without being declared previously. These variables are global variables and their values are modified by the KeyPressFcn. The value of ‘pausestat’ are false initially and will become true if the player presses pause button. The similar thing goes with the ‘movestat’. Its value will change accordingly with player’s control. This is how player control the falling blocks.

The Check

After the falling blocks is placed into the field, ‘field’ array is updated permanently. A check is needed to see if a complete block set has been made. If a complete block set has been made, those block set must be eliminated and the field must be updated and modified due to those blocks elimination (for example, forcing all blocks to uniformly fall down on game mode 1). After, field modification, another check has to be made again to see if another complete block set has been made. This is what usually called chain or combo (And what makes the game interesting). However, this means that another loop is necessary.

For the first and the second game mode, the checking part are as written below. First a check was done by simple checking if there is a row in the ‘field’ array that has no zero element values. If no, the check is ended and the flow goes back to the beginning of the main loop. If yes, the blocks on those rows will be eliminated and moving the blocks on the upperside of it downward to fill the gap. Especially for game mode 2, there is a chance that unglued hanging blocks occurs after a line removal. This blocks has to fall down, as it is shown in the 2:45-2:50 of the second video of MATLAB Tetris. To accomodate this feature, forcefalldown_obj is written. After this, another loop is done to check if there is another complete block set for chain/combo, and so on.

%Preallocating variable for chain-checking
checkstat=true;
n_chain=0;
%Performing loop check
while checkstat
  %Checking for complete line
  statarray=(field~=0);
  rowID=find(sum(statarray,2)==fieldsize(2));
  %Exitting loop if no complete blockset detected
  if isempty(rowID)
    break
  else
    n_chain=n_chain+1;
  end
  %Removing completed line and moving the upperside block down
  if ~isempty(rowID)
    for lineID=1:numel(rowID)
      field(2:rowID(lineID),:)=field(1:rowID(lineID)-1,:);
      graphic=drawfield(field,fieldsize,...
                        square,squaresize);
      imshow(graphic,'Parent',mainaxes)
      pause(2/animationspeed)
    end
  end
  %Adding and updating score
  if ~isempty(rowID)
    score=score+(sum(1:numel(rowID)));
    set(scoretext,'String',score)
  end
  %Forcing unglued blocks to fall down
  if gamemode==2
    loopstat=true;
    while loopstat
      tempfield=forcefalldown_obj(field);
      if isequal(tempfield,field)
        loopstat=false;
      else
        field=tempfield;
      end
    end
  end
  %Preventing continuous acceleration
  accelstat=false;
  movestat='none';
end

For the third game mode, a block set is considered complete block set if three or more same colored blocks are put together side-by-side (not diagonally), instead of completing a row. Thus, to find these complete block set another function, findcolorset is written. After that, those complete block set are eliminated and the ‘field’ array is updated after all hanging blocks are force to fall down by forcefalldown function. After this, another loop is done to check if there is another complete block set for chain/combo, and so on.

%Preallocating variable for chain-checking
checkstat=true;
n_chain=0;
%Performing check loop
while checkstat
  %Checking color block connectivity
  [r_obj,c_obj]=findcolorset(field,csetsizereq);
  n_obj=numel(r_obj);
  r_obj=cell2mat(r_obj);
  c_obj=cell2mat(c_obj);
  %Exitting loop if no complete blockset detected
  if n_obj==0
    break
  else
    n_chain=n_chain+1;
  end
  %Removing complete blockset
  for blockID=1:numel(r_obj)
    field(r_obj(blockID),c_obj(blockID))=0;
  end
  %Drawing graphic
  graphic=drawfield(field,fieldsize,...
                    square,squaresize);
  imshow(graphic,'Parent',mainaxes)
  pause(2/animationspeed)
  %Forcing hanging blocks to fall down
  field=forcefalldown(field);
  %Drawing graphic
  graphic=drawfield(field,fieldsize,...
                    square,squaresize);
  imshow(graphic,'Parent',mainaxes)
  pause(2/animationspeed)
  %Adding and updating score
  if n_obj~=0
    score=score+(n_chain*n_obj*numel(r_obj));
    set(scoretext,'String',score)
  end
  %Preventing continuous acceleration
  accelstat=false;
  movestat='none';
end

These three functions, findcolor, forcefalldown, and forcefalldown_obj, are actually the one that enables this Tetris game to have chain/combo play or whatever it is called. However, these function are somewhat complicated (Yeah, I spend most of the time debugging these function) and related to image processing. Thus, I decide that I’m going to explain more about these functions in another separated post. I also noticed that I haven’t explained anything about the drawfield function and other ‘hidden’ function that are related to the game visualization. However, I’m also gonna cover that in another post. These post will be focusing just on the main game flow.

So, having that said, I think that this post (after a week) is finally finished. So, I’m gonna end this long post now and back to my online game:D.

To be continued….

Posted in Uncategorized | Tagged , , | Leave a comment

The Classic Tetris in MATLAB

Somewhere during the four month time of ‘blogging’ dormancy, I actually have started drafting new code, the classical Tetris, for my fun toolbox. I was thinking of Tetris because I wanted to play more with the animation. However, somewhere along the way, I forgot that I have unfinished code. Maybe because I was too busy or because I was too lazy. Fortunately, now I’m not that busy anymore and decided to finished it. At first, I wanted to make a combination game between Tetris and bejeweled and called Bejeweled Tetris. However, it turns out that I have wrong understanding of bejeweled game (Luckily, I googled it first). So, just recently, I decided to scrap the idea and continued with just the classic tetris. But, to make up for that, I also decided to make 2 alternate game modes of tetris in the code (which actually a bad idea becauase it is the alternate game modes that make the code become harder).

While a few days ago in my author note post, I posted two youtube links, please note that that  (up, no typo here, two ‘that’) was a video capture of my MATLAB Tetris before I scrapped the bejeweled idea. So, that video was wrong and please don’t watch it anymore. Here it is, the ‘right’ version of MATLAB Tetris video capture in three different game modes.

MATLAB Tetris – Game Mode 1 (Classic)

MATLAB-Tetris_01

The first mode is the classical Tetris mode, where all hanging blocks will not fall down at all. Nothing special in this code. Just the original classical Tetris game with all the plain boring white blocks:D.

MATLAB Tetris – Game Mode 2

MATLAB-Tetris_02

The second mode is what I called ColorGlued mode. In this mode, hanging blocks will fall down if they are not glued to another same-colored blocks in its neighbors (See the second video on 2:45-2:50 to see how unglued blocks fall down and fill in the gap.). So, in this mode, there is a gravity that will pull down all the blocks. However, each side-by-side same-colored blocks will fall together as one object. Because of this rule, this game mode allows combo or chain to be made (either planned or accidentally). I made this mode because I believe I’ve read somewhere about this kind of Tetris.

MATLAB Tetris – Game Mode 3

MATLAB-Tetris_03

The third mode is what I called ColorMatched mode. This mode was made because I don’t want to completely delete the code that I made for the previous ‘wrong’ version (It’s just too much work and time goes to waste). In this mode, instead of completing a line, the blocks are eliminated by putting three or more same colored box together. Here, each block acts as individual object and will always fall down to the lowest, regardless of their neighbor.

Both three modes above runs on the same code, function, and main loop. The difference between these three modes is only the function for block generation and the function for block elimination. Just like the previous game, I’m going to explain the algorithm to show you (and probably teach you how does it work). However, since the code itself is quite big and there is a lot of explanation to it, I decided I’m gonna divide the explanation into several works and write it later (because I have this new game that I have to watched:D).

So, that’s all I’m gonna write for today. The code is available for download in My MATLAB Fun Toolbox. As usual, comments and critics are welcomed. Have a nice sunday.

Regards,

0X_R

Update for this post: MATLAB Tetris – The Main algorithm

Posted in Uncategorized | Tagged , , | 2 Comments

New Life in Japan

Time passed away and it has been 4 month since my last post. Right now, I have been living in Japan for a month to make some fortune in a Japanese company, leaving behind my families and my passion for aviation (temporarily, I hope :D). While I do miss the comfort of my family, I also enjoy the sense of freedom that I get here. However, I hope that I’m still be able to live my passion for aviation here, either by messing around with X-Plane, playing around with MATLAB, or just by watching some documentary that I will soon forget what it is about :D.

For the last one month (and for the next three month), I was and will be learning japanese language as my first training in the company from 8.30AM to 5.00PM. Everyday there are  also a lot of homework to be done at the night. Luckily, I still got time to do something else other than studying japanese or doing homework. Currently, I’ve been working on creating a simple tetris game and a number guessing game, Bull and Cow, for my MATLAB Fun Toolbox and I will be posting it here in a few days. Let’s hope that I’m gonna stay active in blogging and keep on playing around with MATLAB although I got a lot of japanese stuff to learn:D.

In the  mean time, check out my youtube video for my soon-to-be-posted MATLAB Tetris and its Bejeweled mode.

Regards,

0X_R

Posted in Uncategorized | Leave a comment