June 09, 2013

Playing Tetris in engineer style

Introduction

Month ago my girlfriend showed me a 9gag post and asked, if I could build something like that. So I ordered 2 led matrices and buttons from ebay, and built it, so here it is:
Sorry for the quality, I recorded it with my cellphone yesterday evening, but I hope you see the point of it.
It was a complicated project, so writing a step-by-step tutorial would take too many time, so I just summarize the main steps of the project and some advises.

First step: wiring of the led-matrix and functional for driving it

I checked the ebay site where I ordered the matrices and found this:
It's very similar in the inner working as the 7 segment display, see below. I wrote a custom functional for driving it, see at the code.

Second step: connect the buttons

I used very simple buttons from dx:
If you press it, it connects the 2 wire. It was the first time I've ever used a button with arduino, so I was a little bit confused about it, but Google helped me out again.

Third step: writing the tetris program

As I said in the title, and as you can see in the video, this version is only beta. There are bugs in the code, sometimes it makes weird things, and I can't figure out why. I'm going to fix it sometimes, but until then, here is the code:
(if link's broken, here: http://codepad.org/gY3fLXXx)
But during the programming I've learned something useful. There is a a 2D int array, called fix[16][8], which store the fix dots, the fix pixels. It has a 5 in every pixel, where led lights and a 0 where led's dark. So I wanted to check if there is a full line, so I wrote this code:
//full line
for(int i=0; i<16; i++){
  int ch=1;
  for(int j=0; j<8; j++) ch=ch*fix[i][j];
  if(ch>0){
    for(int k=i; k<15; k++)
      {for(int l=0; l<8; l++)
        fix[k][l]=fix[k+1][l];
      }
     for(int k=0; k<8; k++) fix[15][k]=0;
    }
     
}
It multiply every number in a line and if it's bigger than 0 at the end, ie there was no 0 in the line, so it's a full line, the program deletes it. And it didn't work. Why? After a long time I figured it out: 5^8=390625. And it's too big for an int, so it overflows and gives back a negative number! So finally I changed ch to long int and so it works now. I could change if(ch>0) to if(ch!=0)or ch=ch*fix[i][j]; to ch=ch*fix[i][j]/5; but long int was my first tough and it works so I leave it so.

Summary

It was, and it's still a big project, I hope, someday I'll finish it. Maybe I will add a demultiplexer to use less output of the arduino, and use better buttons, maybe even a use a keypad. But first I have to make the program better.

Best regards, hope you enjoy:

Mark

No comments:

Post a Comment