Friday, February 12, 2016

PDFPrinter Class!

PDFPrinter is a class created to provide an easy way to generate simple PDF documents in Qt Creator (C++). The PDFPrinter is an open source project that can be found at Github.


The PDFPrinter class was created using some native classes from Qt, for example: QPrinter and QPainter.
The main objective of PDFPrinter is to make life easier for software developers who want to generate simple PDF documents. You don't need to bother in align the text on the page size, align or resize the images, or break a page, the PDFPrinter class does all of it for you.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 // Now you can create an object of the PDFPrinter class:  
 PDFPrinter pdfPrinter;  

 // Call the 'start' function and pass the file path where do you want to save the PDF  
 pdfPrinter.start("C:\\Desktop\\test.pdf");  

 // You can set the margins of the page in percentage (e.g. 10%)  
 pdfPrinter.setHorizontalMargin(10);  
 pdfPrinter.setVerticalMargin(10);  

 // You can set a font size  
 pdfPrinter.setFontSize(24);  

 // You can set the font as bold  
 pdfPrinter.setTextBold(true);  

 // You can print a title in the center of the page (horizontal center)  
 pdfPrinter.printText("My Report", QtPrinter::Center);  

 // You can print a line  
 pdfPrinter.printLine();  

 // You can print your text  
 pdfPrinter.printText("This is my first report created with the PDFPrinter class!", QtPrinter::Left);  

 // And finally you need to call the end function  
 pdfPrinter.end(); 
To know more about the PDFPrinter class please visit: https://github.com/kelvins/PDFPrinter

Thursday, June 18, 2015

Stack Implementation in C

Today i gonna show you a simple example of stack implementation in C. The stack is a very common data structure used in programs.

"In computer science, a stack or LIFO (last in, first out) is an abstract data type that serves as a collection of elements, with two principal operations: push, which adds an element to the collection, and pop, which removes the last element that was added."

Ok, but talk is cheap. Show me the code.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <stdio.h>
#include <malloc.h>

#define MAX 50 // Maximum size of array

int index = 0; // Index of values

// Stack data structure
typedef struct{
    int value;
}Structure, *Pointer;

// Initializes the stack
void initialize(Pointer stack[]){
    for (int i = 0; i < MAX; ++i){
        stack[i] = NULL;
    }
}

// Push a value on the stack
void push(Pointer stack[], int value){
    Pointer temp = (Pointer) malloc( sizeof(Structure) ); // Allocates memory
    temp->value = value; // Puts the value on the structure
    stack[index] = temp; // Puts the new structure on the stack
    index++;
}

// Delete a value from the stack
void pop(Pointer stack[]){
    stack[index] = NULL;
    index--;
}

// Shows the stack
void show(Pointer stack[]){
    printf("STACK : ");
    for (int i = 0; i < index; ++i){
        printf("[%d]-", stack[i]->value);
    }
    printf("\n");
}

int main(){
    Pointer STACK[MAX];
 
    initialize(STACK);
 
    push(STACK, 15);
    push(STACK, 55);
    push(STACK, 80);
    push(STACK, 99);
    push(STACK, 43);

    show(STACK);
    pop(STACK);
    show(STACK);
    pop(STACK);
    show(STACK);
    pop(STACK);
    show(STACK);

    return 0;
}

If you have any questions or suggestions, please leave your comment.

Sunday, June 14, 2015

Sequential Search with Sentinel

Sentinel value is a way to improve the speed of sequential search. In traditional sequential search we need to test if the value is the key we are searching, however, in the sequential search with sentinel we put the value in the array end, therefore, the value is always found.

At the end we just need to test if the value of the 'index' variable is the last position of the array, if is that true, then, the value was not found, and the method returns -1.

Take a look at the example below.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def SequentialSearch(value, array):
    for x in xrange(0, len(array)):
        if array[x] == value:
            return x
    return -1

def SentinelSearch(value, array):
    array.append(value) # Puts the value at the end of the array
    index = 0
    while array[index] != value: # While the value is different
        index += 1
    array.pop() # Removes the value at the end of the array
    if index == len(array)-1: # If the 'index' variable is the last position of the array, returns -1
        return -1
    return index # Else, returns the position of the value on the array

array = [1, 4, 5, 2, 42, 34, 54, 98, 89, 78, 67]
print SequentialSearch(54, array)
print SentinelSearch(98, array)

I hope you enjoyed it.
Any questions just comment.

Friday, May 29, 2015

Python Lists

Today I will show you some very interesting methods that can be used in Python lists, which can often save your time.

Most methods can be found in the following link: https://docs.python.org/2/tutorial/datastructures.html

Create a characters list:

lista = ['1', '4', '3', '2', '5', '7', '6', '8', '9']

Convert all characters of the list to int:

lista = map(int, lista)

Show the greatest value from the list:

print max(lista)

Show the lowest value from the list:

print min(lista)

Sum all values from the list

print sum(lista)

Search and returns the index of the value passed by parameter:

lista.index(7)

Sort the list in ascending order:

lista.sort()

Reverse the list

lista.reverse()

Insert all elements of a list at the end of another list:

lista.extend(lista2)

Remove the value passed as parameter (the first found in the list):

lista.remove(14)

Remove the last value from the list:

lista.pop()

Remove the first value from the list:

lista.pop(0)

Count how many times the parameter appear in the list:

lista.count(3)

Convert a string into a list:

lista = []
string = '1 2 3 4 5 6 7 8'
lista = string.split()

Transform a list into a string (separate by comma):

lista = ['1', '4', '3', '2', '5', '7', '6', '8', '9']
string = ', '.join(lista)
print string

Generate a random value from the list:

import random
random.choice(lista)


These are some methods you can use in your algorithm when you are working with lists in Python. 
I hope you enjoyed the tips.

Tuesday, May 5, 2015

Tower of Hanoi - Python

Today i will show a little example in Python of the famous problem Tower of Hanoi.

"The Tower of Hanoi is a mathematical game or puzzle. It consists of three rods, and a number of disks of different sizes which can slide onto any rod. The puzzle starts with the disks in a neat stack in ascending order of size on one rod, the smallest at the top, thus making a conical shape.
The objective of the puzzle is to move the entire stack to another rod, obeying the following simple rules:
  1. Only one disk can be moved at a time.
  2. Each move consists of taking the upper disk from one of the stacks and placing it on top of another stack i.e. a disk can only be moved if it is the uppermost disk on a stack.
  3. No disk may be placed on top of a smaller disk.
With three disks, the puzzle can be solved in seven moves. The minimum number of moves required to solve a Tower of Hanoi puzzle is 2n - 1, where n is the number of disks." 

See the example below:


If you want to know more about Tower of Hanoi click here

Ok, ok, but where's the code?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
def Hanoi(pin0, pin2, pin1, num):
  if num == 1:
    print 'Move from ' + str(pin0) + ' to ' + str(pin2)
  else:
    Hanoi(pin0, pin1, pin2, num-1)
    Hanoi(pin0, pin2, pin1, 1)
    Hanoi(pin1, pin2, pin0, num-1)

# Parameters: (from)Pin0, (to)Pin2, (helper)Pin1, Number of Disks
Hanoi(0, 2, 1, 3)

The code shows each necessary move to pass all the disks from the first rod to the last rod.

If you liked please share. If you have any questions just ask.

Thursday, March 19, 2015

Fibonacci Sequence in Python

Hello, today i'll gonna show you a little example of Fibonacci sequence in python, using recursivity.
In math, Fibonacci sequence is the numbers in the following sequence:
0,\;1,\;1,\;2,\;3,\;5,\;8,\;13,\;21,\;34,\;55,\;89,\;144,\; \ldots\;
By definition, the first two numbers in the Fibonacci sequence are either 0 and 1, and each subsequent number is the sum of the previous two.
Below is the code (only 7 lines), using recursion to find the number in the Fibonacci sequence, according to the index past by parameter. Ex.: Fibonacci(11) = 89.
def Fibonacci(n):
    if n <= 1:
        return n
    else:
        return Fibonacci(n-1) + Fibonacci(n-2)
print('Fibonacci = ' + str(Fibonacci(10)) )

If you want to know more about the Fibonacci sequence, visit this link.

Any questions just comment

Tuesday, February 17, 2015

First HTML5 Game

The HTML5 came with many new possibilities, support new tags, like canvas, video, audio, which enable and facilitate the development of games, but all the logic of the game is developed in Javascript.

Below i will show you a little tutorial about developing a simple game in HTML5, for this, it is advisable that you already have a basic knowledge of HTML and Javascript.

The objective of the game is to collect with a basket, all fruits that are falling, and take care not to catch the bomb because if that happens you lose the game.

You can download the source files on:







First we need to create a folder for the project, then download and save the below images inside this folder.



Well, done this we will create the index.html file which contains, among others, the canvas tag. We assign a name id "stage" for the canvas and the width and height 800×600. Note that we also use a style to the canvas, setting borders and background color. And here we will call the method "initialize()" at the "onLoad" of the body tag.

<!DOCTYPE html>
<html>
  <head>
    <title>First HTML5 Game</title>
 
    <style type="text/css">
      canvas{
        border: 1px solid #000;
        background-color: #eee;
      }
    </style>
    <script src="game.js"></script>
  </head>
  <body onLoad="initialize()">
    <canvas id="stage" width="800" height="600">
      Your browser do not support HTML5
    </canvas>
  </body>
</html>

Now, the main part, the game.js file, which contains all the logic of the game.

1º We need to create the variables to be used in the game.

2º The initialize method is responsible for loading all the images, assign values to variables and set a time for the gameloop, which will be called every 30 milliseconds.

3º The keyDown method is responsible for testing the keys pressed on the keyboard and move the player (fruit basket) on the X axis.

4. The gameloop method is responsible for clean up and draw on the screen, collision tests, move the fruit, among other things necessary to test every "round" of play.

Below the game.js file.

// Create the variables
var playerHeight, playerWidth, playerPosX, playerSpeed, playerPoints, playerImg;
var orangeImg, appleImg, pearImg, fruitPosX, fruitPosY, fruitSpeed, bombImg;
var collisionFlag, gameOver;

// Function that starts the game, it loads all the resources and sets the initial value of the variables
function initialize(){
  // Sets the canvas variable for the HTML Canvas
  canvas = document.getElementById("stage");
  context = canvas.getContext("2d");

  // Create and load all the pictures of the game
  orangeImg = new Image();
  orangeImg.src = 'orange.png';
  appleImg = new Image();
  appleImg.src = 'apple.png';
  pearImg = new Image();
  pearImg.src = 'pear.png';
  bombImg = new Image();
  bombImg.src = 'bomb.png';
  playerImg = new Image();
  playerImg.src = 'basket.png';
 
  // Set initial values for the variables Player
  playerHeight = 125;
  playerWidth  = 150;
  playerSpeed  = 20;
  playerPoints = 00;
  playerPosX   = (canvas.width/2)-(playerWidth/2);
 
  // Start the values for the flags of the game
  collisionFlag = false;
  gameOver = false;
 
  // Start the necessary variables of fruits
  fruitPosY = -50;
  fruitSpeed = 15;
  fruitPosX = canvas.width/2;
  fruitImg = orangeImg;

  // Draw the basket of fruit on screen in X and Y position
  context.drawImage(playerImg, playerPosX, canvas.height-120);
 
  // Add keyboard events
  document.addEventListener("keydown", keyDown);
 
  // Call the gameLoop method every 30 milliseconds
  loop = setInterval(gameLoop, 30);
}

// Function to control key Down
function keyDown(key){
  if(key.keyCode == 37)
    if( playerPosX > 0 )
      playerPosX -= playerSpeed;
 
  if(key.keyCode == 39)
    if( playerPosX < (canvas.width - playerWidth) )
      playerPosX += playerSpeed;

  // If the game is not over yet draws the basket of fruit on screen
  if( gameOver == false )
    context.drawImage(playerImg, playerPosX, canvas.height-120);
}

function gameLoop(){

  // Clean the canvas
  context.clearRect(0, 0, canvas.width, canvas.height);
 
  // Draw the fruit and the fruit basket
  context.drawImage(fruitImg, fruitPosX, fruitPosY);
  context.drawImage(playerImg, playerPosX, canvas.height-120);

  // If the fruit has not reached the bottom of the screen, she keeps 'falling'
  if( fruitPosY <= canvas.height ){
    fruitPosY += fruitSpeed;
  // Otherwise it resets the position and generates a fruit or random pump
  }else{
    fruitPosY = -50;
    fruitPosX = Math.random() * (canvas.width-50);
    collisionFlag = false;

    if( Math.floor((Math.random() * 4)) == 0 )
      fruitImg = bombImg;
    else if( Math.floor((Math.random() * 4)) == 1 )
      fruitImg = appleImg;
    else if( Math.floor((Math.random() * 4)) == 2 )
      fruitImg = pearImg;
    else if( Math.floor((Math.random() * 4)) == 3 )
      fruitImg = orangeImg;

  }
 
  // Test whether the fruit 'fell' into the basket, if so, increments a point and sets the flag to true collision
  if( ( fruitPosX > playerPosX && fruitPosX < (playerPosX+playerWidth) ) && 
      ( fruitPosY >= canvas.height-100) &&
      collisionFlag == false &&
      fruitImg != bombImg){
 
    playerPoints++;
    collisionFlag = true;

  }else if( ( fruitPosX > playerPosX && fruitPosX < (playerPosX+playerWidth) ) && 
    ( fruitPosY >= canvas.height-playerHeight) &&
    collisionFlag == false &&
    fruitImg == bombImg){

    context.clearRect(0, 0, canvas.width, canvas.height);
    context.font = "80pt Arial";
    context.fillText("Game Over", (canvas.width/2)-250, 300, 500);
    gameOver = true;
    clearInterval(loop);

  }

  // Show player points on the screen
  context.font = "32pt Arial";
  context.fillText(playerPoints+" fruits", canvas.width-140, 50, 100);
}
And the result of the game should look like the screen below.

I hope you enjoyed and learned a little about how to develop games in HTML5.

In this tutorial i haven't used any framework, but there are already several great frameworks for the development of HTML5 games, like Phaser or MelonJS.