Ghost methods and meta programming can make your life much much much easier

I have been cleaning up some of my codes today at my a ruby on rails app, I had 10 similar with minor difference methods which kept me thinking why would I write 10 separate methods rather than 1 using ghost methods of ruby? But things are a little bit different when we work on rails that is basically the motivation behind this blog.

Suppose my client started to take orders from its customer to build a custom car, so imagine how many of this following methods we will need to write!!

def add_tire
    @current_build = get_current_build
    Tire = Tire.find(params[:tire_id])
    # todo do stuff
    redirect_to current_build_url
end

def add_engine
    @current_build = get_current_build
    engine = Engine.find(params[:engine_id])
    # todo add methods
    redirect_to current_build_url
end

#....more similar looking add_items methods

Probably a hundred or even the method can reach thousand. But don’t surprise, ruby has its own elegant way to handle this type of repeating. Using ruby support of ghost methods, we can solve this problem. Usually a ghost methods are being handled using method_missing, if you already are not aware of the power of method_missing, then let me tell you in short, method_missing is a method that is being called when a method is being called but it is not defined in the object. So basically when a method is being called in check within it, if not found it checks its parent if that method exists there or not, if not found then it checks its parent too, this check goes all the way to ruby object class as object is the parent of all ruby class.

Now let me show you an example:

class Test
    def say_hi(to)
        "Saying hi to "+to
    end
    def method_missing(name, *args)
        say_hi(*args)
    end
end

irb(main):022:0> Test.new.say_hi("mike")
=> "saying hi to mike"
irb(main):023:0> Test.new.say_hello("mike")
=> "saying hi to mike"

 

 

This hello, or hi method does not exist in Test class, but they are acting as if they exist, thats why they are called ghost methods.

Every ruby class has a send method, that takes method name as string argument and capable to run that method.

class Test
    def say_hi(to)
        "Saying hi to "+to
    end
    def say_bye(to)
        "Saying bye to "+to
    end
    def method_missing(method, *args)
        self.send("#{method}",*args)
    end
end

irb(main):023:0> Test.new.say_hi("mike")
=> "saying hi to mike"
irb(main):022:0> Test.new.hi("mike")
=> "saying hi to mike"
irb(main):023:0> Test.new.say_bye("mike")
=> "saying bye to mike"
irb(main):022:0> Test.new.bye("mike")
=> "saying bye to mike"

 

 

We have seen how to call a method dynamically, but we may also need to call another class name dynamically, for that Object.const_get takes string as parameter and call that class. (Object.const_get "Test").new.send("hi","mike") is the same as Test.new.hi("mike").

irb(main):023:0> (Object.const_get "Test").new.send("hi","mike")
=> "saying hi to mike"

 

In ruby meta programming there is a method called eval which exicutes a string as ruby code.

irb(main):025:0> eval("Test.new.hi('mike')")
=> "saying hi to mike"

 

Now I think we know everything to attempt to write our ghost method at controller, but writing ghost method with method_missing does not help much in rails controller because rails does not always require methods to be present in controller if corresponding template exists. So when action is missing it starts to attempt rendering templates, thats why method_missing does not invokes. But fear not, we have action_missing which is being called when ruby failed to find action. Here is an example of our car order case:

  def action_missing(m, *args, &block)
    if m.starts_with? "add_"
      k=(m.split "_", 2) [1]

      @current_build = get_current_build
      qty=params[:qty]      

      build= (Object.const_get "#{k.camelize}Build").create({(k+"_id").to_sym => params[(k+"_id").to_sym], :market_status_id => params[:market_status]})
      eval("@current_build.#{k}_builds << build")
      redirect_to current_build_url
    else
      super
    end
  end

Here we go, we have saved at least 100 lines of code, not only that, now we need to change only one line of code on change of methods, where previously, we had to change 100 lines on change.

ssl (https) from python flask

Basically here I am in this blog I am going share a code snippet, and I am going to describe what else stupid things I tried and did not work to do that. Well, don’t miss my point, when I am sharing my stupid ordeal, it does not mean, I am proving myself stupid but I am trying to save your time, I am basically telling what did not work in last couple of hour so that it could save your time.

So using flask when I shared a static file migrated directly from django, while working with django we have figured out that we actually don’t need powerful tool like django, instead we can use something very lightweight like flask and it is much easier to switch from django to flask as for both of them default front end templating is jinja. Now after this shift, I had to face a little bit trouble with https, because when I tried https, it is completely blank, I lost my mind, what the hell is going on here? Then I realized for flask probably I need to define my ssl. They got this nice documentation at their website (http://flask.pocoo.org/snippets/111/), I follwed them, and it did not work! Why it won’t work? Alright after couple of trial and google search I realized this is an old school way of doing this, fine, I need to go to new school, obviously! I got myself a new dress and now context looks more pretty {“cert.crt”,”key.key”}. I am impressed but what the hell? it did not work as well, why it won’t work? I lost my mind! hours of fighting, and I got this error:

Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 810, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 763, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 602, in inner
    passthrough_errors, ssl_context).serve_forever()
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 506, in make_server
    passthrough_errors, ssl_context)
  File "/usr/local/lib/python2.7/dist-packages/werkzeug/serving.py", line 450, in __init__
    self.socket = ssl_context.wrap_socket(self.socket,
AttributeError: 'OpenSSL.SSL.Context' object has no attribute 'wrap_socket'

It is because I am using a python 2.7 version below 2.7.9.

What else did I try? You won’t want to know, I tried to install pyopenssl on heroku using pip, but looks like it is a ported version and failed to compile on heroku. Now I will write about what I had to do to make it work.

I have to make my cirtificate and keys:

$ openssl genrsa -des3 -passout pass:x -out server.pass.key 2048
 openssl rsa -passin pass:x -in server.pass.key -out server.key
 rm server.pass.key
 openssl req -new -key server.key -out server.csr
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt

So now we have server.key and server.csr two files in our directory

Now python script:

from flask import Flask, request, send_from_directory
from flask import render_template

#from OpenSSL import SSL
#context = SSL.Context(SSL.SSLv23_METHOD)
#context.use_privatekey_file('server.key')
#context.use_certificate_file('server.crt')

import os

ASSETS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '/static')
app = Flask(__name__, static_url_path='/static')

@app.route('/js/')
def send_js(path):
    return send_from_directory('js', path)

@app.route('/signup')
def signup():
    return render_template('signup.html')

if __name__ == '__main__':
    context = ('server.crt', 'server.key')
    app.run(ssl_context=context, threaded=True, debug=True)

Done! Up and running if you got a version >=2.7.9.!

RESTful API design best practices

For this new project I am currently involved in, I need to design and criticize some APIs. So I thought maybe digging up a little bit about RESTful API might be helpful for me.

When we are talking about API, we know that we are talking about Abstract Programming Interfaces, indeed but what makes a API good and bad? People having this religious debates about SOAP and REST, but U want to know, what should we keep in mind when we are designing a RESTful API.

First of we need to be clear about our goals why and what for we are creating this APIs. We create APIs for another developer so that they can offer good stuff to their customers. But the goal of api is to scale, so that our product can reach more people.
Why do we need to go for REST? Well, Rest is not a standard but a way of doing something that makes life easier. It has this following features:

i) Scalability: It has theability to make it grow faster. Say we want to add a new feature in our api, we can add it without much effort.
ii) Generality: It has to use a general protocol, like http, or https.
iii) Independence: Another good thing about REST is that, different part of apis can be independent in this architecture.
iv) Latency: caching is another big feature.
v) Security: as REST use http type protocols, it also has some good feature of security, we can use http headers for security purpose.
vi) Encapsulation: Rest architecture only shows thing that could possibly be necessary to other.

Why json?
Ubiquity: well, 50-70% of the market uses JSON.
Simplicity: It has a simpler grammar than any other competitors.
Readability: We don’t need any other prior knowledge to read jsons.
Scalability: Jsons are easy to add to.
Flexibility: It is flexible, everything can fit in json.
HATEOAS: it does not contain content type or anything, it only contains things that is necessary.

REST is easy for user but it can be hard for those who makes it. But one thing we need to keep it in mind, it is not a standard like w3 but it is a style, it is an architecture. This is easy to maintain if we keep few things in mind.

Suppose we have this application that creates user, gets user derails, change user details and so on. So one noob approach would be:

/createUser
/getUserDetail
/changePassword
…and so on.

Is it good? it is not. Not only it is bad, it also confuses the user of our API. We should put only nouns in our API request url not behaviors like doThis. We can do that with less urls to request. In fact we can do that with one using http methods, GET, PUT, POST, DElete, head, (PATCH). CRUD is not necessarily a one to one correspondent of GET, PUT, POST, DELETE. In fact PUT and POST can be used to get, create and update. Before discussing about POST or PUT, I think we can go for something simple, like getting information. I think there can be 2 types of resources need to be care about, we can get whole bunch of users, or a single instance of users.
i) collection
/users <- it is a plural
ii)instance
/users/1231 <-nested

Now lets talk about PUT. PUT has this little complicacy that, PUT is idempotent, it sends all the same state remains same does not matter if we get a 101 or what as a result. So need to take care sometime. We need to present all the field present when we do PUT. With PUT can’t support partial update. As PUT returns some data in the end a blank PUT can be used similarly as GET if implemented like that.

POST always done on parent (eg: /users) for POST 200 response is not good enough to return, as when the request is successful it also returns 200, it can be 201. but for update 200 is ok. POST is the only method not idempotent. We can make it idempotent. Some rest api has data limit, we can reduce it using partial updates. Also has impact on performence.

Now it is always a good idea to deal with Accept header of a request and send priority list which it can accept. When we send a request, it is also important to have a content-type.  We can do it easily if we use it as an extention.

applications/aln2c3.json.

BASE URLs does not mean a lot in rest api. https://api.foo.com is better looking than http://www.foo.com/dev/service/api/rest .Version should be in url, https://api.foo.com/v1, or as media type application/json;application&v=1, for those who changes api very frequently media type is better option. But it requires more work to make it done. not ideal and it is not completely fall under rest api system. About versioning, 1.2.3.4 should not be at api version of data exchange.

It is always better to use Camel cases not underscore when it comes to json. Date should be at iso 8601 and it should be UTC rather than anything else, it saves a lot of work.

There should always have ids but does the user need to know about this ids? Nope, we can use HREF in json media, instead. Hypermedia is paramount, does not have xlink like xml.

Now we talked about the fundamentals, but at the same time giving too much information on each api calls are a bad idea because it costs you money. So what can you do? You can ask user to request, what do you want? and upon his request you can extend your api response.

?expand=resource1, resource2

 

It is being considered as different resource so it will be stored in different cache. Offset and limits can also be done the same way.

?offset=5-&limit=25

It is always our dream that there won’t be any errors anywhere, but practically it never happens, but error can be tackled. So it is always better to keep user updated about the errors. Rather than just let them check the headers for error messages we should tell them in json response status about it. we should describe that error to him, give them a link to get notified about the error updates. Thats how we can help them.

About security, I would say sessions does not do much good other than over heads, sessions can be copied and you won’t see it coming, not only that session requires extra clustering at your server, it also better not to have them when you need better performance. Url changes all the time, so it is better not to hash urls, rather than urls rather use it on content.

There are also some people that believe oAuth2 better than oAuth1a, but honestly speaking oauth is not more secure than 2, oAuth2 wanted to make life easier though some people really doubt about its success. The use bearer token can be questioned.

It is always better to use api keys, rather than user passwords.
ENtropy: long in length, you can’t guess like a password.
password reset: does not affect on password change.
independence: not broken on password change or anything.
speed: If we use bcript  it may take 0.1 or 0.5 s, user may never notice, but some hacker will notice that it will take time.
limited exposure: only who downloaded it, he knows
traceablity: we can trace why it did not work.

Now for login there is this common misconception on when to use 401 and 402.

401 unauthorized means unauthenticated, maybe password was unchecked.
402 forbidden, credentials taken but found out he is not allowed

It is always good idea to add this POST method, because some user may never heard of DELETE kind of methods. And why post? Because POST is  the only method that is not idempoten.

?_method=DELETE

How to fix theano numpy wrong number of dimensions!

Recently I had to work with Theano, numpy, scipy libraries in python. had to pass hour with this this piece of error which says TypeError: (‘Bad input argument to theano function at index 1(0-based)’, ‘Wrong number of dimensions: expected 2, got 1 with shape (2,).’) So here it goes, how I fixed it.

For the sake helping other fellow programmers, I am posting the whole error log, which will help them via google:

/usr/lib/python2.7/dist-packages/scipy/lib/_util.py:35: DeprecationWarning: Module scipy.linalg.blas.fblas is deprecated, use scipy.linalg.blas instead
DeprecationWarning)
/usr/lib/python2.7/dist-packages/scipy/lib/_util.py:35: DeprecationWarning: Module scipy.linalg.blas.fblas is deprecated, use scipy.linalg.blas instead
DeprecationWarning)
/usr/lib/python2.7/dist-packages/scipy/lib/_util.py:35: DeprecationWarning: Module scipy.linalg.blas.fblas is deprecated, use scipy.linalg.blas instead
DeprecationWarning)
/usr/lib/python2.7/dist-packages/scipy/lib/_util.py:35: DeprecationWarning: Module scipy.linalg.blas.fblas is deprecated, use scipy.linalg.blas instead
DeprecationWarning)
/usr/lib/python2.7/dist-packages/scipy/lib/_util.py:35: DeprecationWarning: Module scipy.linalg.blas.fblas is deprecated, use scipy.linalg.blas instead
DeprecationWarning)
/usr/lib/python2.7/dist-packages/scipy/lib/_util.py:35: DeprecationWarning: Module scipy.linalg.blas.fblas is deprecated, use scipy.linalg.blas instead
DeprecationWarning)
/usr/lib/python2.7/dist-packages/scipy/lib/_util.py:35: DeprecationWarning: Module scipy.linalg.blas.fblas is deprecated, use scipy.linalg.blas instead
DeprecationWarning)
/usr/lib/python2.7/dist-packages/scipy/lib/_util.py:35: DeprecationWarning: Module scipy.linalg.blas.fblas is deprecated, use scipy.linalg.blas instead
DeprecationWarning)
False
Traceback (most recent call last):
File "bgd.py", line 44, in 
theta = gradient_descent_2(alpha, x, y, 2000)
File "bgd.py", line 24, in gradient_descent_2
hypothesis =find_hypothesis(x, theta).T
File "/usr/local/lib/python2.7/dist-packages/Theano-0.6.0-py2.7.egg/theano/compile/function_module.py", line 497, in __call__
allow_downcast=s.allow_downcast)
File "/usr/local/lib/python2.7/dist-packages/Theano-0.6.0-py2.7.egg/theano/tensor/type.py", line 157, in filter
data.shape))
TypeError: ('Bad input argument to theano function at index 1(0-based)', 'Wrong number of dimensions: expected 2, got 1 with shape (2,).')

So basically it is saying that in my code there is a shape mismatch, apparently there should not be any mismatch, because I coded everything, I KNOW what I did! But apparently there is something in numpy that makes a matrix without height, which means with blank height. So it has a shape of (2, ).

Example could be:

import numpy as np
theta = np.array([1,1])
print theta.shape       #(2,)

It works pretty fine when you are working with nupy alone, but it causes tremendous problems when you are using other library like THENO.

Now let me share another snippet, from where I got this error:

from theano import tensor as T, function

T_x,T_y, T_z, T_theta, T_loss = T.dmatrices('x','y','z','theta','loss')
find_hypothesis=function([T_x,T_theta],T.dot(T_x,T_theta))

hypothesis =find_hypothesis(x, theta).T

From code like this you will get the error I previously mentioned.

Now lets talk about how did I fix it, actually it was simple, I passed hours without any reason. You can solve it just by reshapiing your numpy like this:

theta=theta.reshape(theta.shape[0],1)        #had tough time without this,

How to automate numpy installation in your project using setuptool?

Recently for an opensurce project, I had to work using numpy. Numpy makes life a lot easier, without any doubt, but when it comes to setup.py of setuptool. It does not work just by adding <code>’install_requires:[“numpy”]’ </code> mainly because unlike any other python packages numpy is written in C/C++, mainly because of the optimization, interpreted language like python are not fast enough for mathematical computations. They ported their code in python. So before using them we need to compile them.

To do that we need to use custom commands, for custom commands in setuptool, we need to add “cmdclass” as a key in the dictionary. “build_ext” is a cython command which helps to compile files of numpy. But before compiling is done we should not call anything else, so we need to customize some existing class. So we overwrite build_ext class with an extension of it.

So the code should look like this:

 

from setuptools import setup
from setuptools.command.build_ext import build_ext as _build_ext

class build_ext(_build_ext):
    'to install numpy'
    def finalize_options(self):
        _build_ext.finalize_options(self)
        # Prevent numpy from thinking it is still in its setup process:
        __builtins__.__NUMPY_SETUP__ = False
        import numpy
        self.include_dirs.append(numpy.get_include())

config = {
 'cmdclass':{'build_ext':build_ext}, #numpy hack
 'setup_requires':['numpy'],         #numpy hack
 #...
 'install_requires': ["numpy" ]
}

 

Now why do we write __NUMPY_SETUP__=false? I have found an interesting answer @ StackOverFlow by coldfix.

In the source code of numpy we have got this:

 

if __NUMPY_SETUP__:
    import sys as _sys
    _sys.stderr.write('Running from numpy source directory.\n')
    del _sys
else:
    # import submodules etc. (main branch)

So when NUMPY_SETUP is true it does not import submodules so we need to make it sure that it does not get called first time. Then we include it in our library path.

 

 

Adding animation on character movement using Libgdx

reviously, we have talked about making a character. But our character was lifeless. It was like moving image left or right. Now it is time to add animation to our character bob so that it look more like a character who has life. Most importantly this time I am writing my own code. This time I am not explaining other’s code in my own word like my previous 2 libgdx blog.

First thing we got to do is, we have to make a sprite-sheet.

We have to store it in the asset directory of android.

Now to contemplate where actually we were rendering our character bob? We have done it in WorldRenderer.java. It has a render() method which is responsible for decoration of the environment.

public void render() {
spriteBatch.begin();
drawBlocks();
drawBob();
spriteBatch.end();

if (debug)
drawDebug();
}

we are more interested about the character animation today so we will be rewriting our drawBob() method today. But before that we must load our textures first in loadTextures() method which is being called in the constructor of this class. What actually we need to load here? We need to load our sprite image. Then we need to divide and split it into frames into a 1D array and then we have to make Animation object using this Array and we also need to define the time each frame will consume. Thats it.

	private static final int        FRAME_COLS = 6;      
    private static final int        FRAME_ROWS = 5;        
    Animation                       walkAnimation;          
    Texture                         walkSheet;              
    TextureRegion[]                 walkFrames;             
    TextureRegion                   currentFrame;           

    float stateTime;                                        

	private void loadTextures() {
		walkSheet = new  Texture(Gdx.files.internal("animation_sheet.png"));
		TextureRegion[][] tmp = TextureRegion.split(walkSheet, walkSheet.getWidth() / 
				FRAME_COLS, walkSheet.getHeight() / FRAME_ROWS);
		walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
        int index = 0;
        for (int i = 0; i < FRAME_ROWS; i++) {
                for (int j = 0; j < FRAME_COLS; j++) {
                        walkFrames[index++] = tmp[i][j];
                }
        }
        walkAnimation = new Animation(0.025f, walkFrames);

        stateTime = 0f;

        bobTexture = new  Texture(Gdx.files.internal("images/bob.png"));
        blockTexture = new Texture(Gdx.files.internal("images/block.png"));
	}

As I was saying, we need to move to our main focused function drawBob(). To access the sprite frames we need to access to the frames via time elapsed. So we need to keep updating stateTimewith a delta otherwise the same frame will keep appearing. Gdx.graphics.getDeltaTime() returns the time passed since the last call to render() in seconds. So basically I was explaining this code.

private void drawBob() {
	Bob bob = world.getBob();
        Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        stateTime += Gdx.graphics.getDeltaTime();
        currentFrame = walkAnimation.getKeyFrame(stateTime, true);
        spriteBatch.draw(currentFrame, bob.position.x * ppuX, bob.position.y * ppuY, facex*Bob.SIZE * ppuX, Bob.SIZE * ppuY);
}

Bingo! Sprite works. BUT! This is odd because bob is animating its run state all the time even when he is not running, it need to be fixed, right? Actually we have been preparing for this moment from the first day. Remember we are keeping an enum to keep the current state of bob and using controller we are updating bob’s state. So here it will only need a if else condition to check what is the current state of bob. Is he running? Or another word, is user pressing arrow keys? If yes then show this animation:

if (bob.state==bob.state.WALKING){
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        stateTime += Gdx.graphics.getDeltaTime();
        currentFrame = walkAnimation.getKeyFrame(stateTime, true);
        spriteBatch.draw(currentFrame, bob.position.x * ppuX, bob.position.y * ppuY, Bob.SIZE * ppuX, Bob.SIZE * ppuY);

}

and if he is idle show that old static image.

else if(bob.state==bob.state.IDLE){
			spriteBatch.draw(bobTexture, bob.position.x * ppuX, bob.position.y * ppuY,Bob.SIZE * ppuX, Bob.SIZE * ppuY);
		}

We are good now, aren’t we? Yes we have improved a lot. But still when we move left the bob face in one direction thats what we want so no complain but when we move right bob keep his face to that old direction again! Thats stupid, is not it? So we need to flip the direction of our sprite and image. It is not hard at all. It requires trick. if add negative to the size of the image it will flip the image in X axis. So lets put this function together:

private void drawBob() {
		Bob bob = world.getBob();

		int facex=1;
		if(bob.facingLeft){
			facex=-1;
		}

		if (bob.state==bob.state.WALKING){
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        stateTime += Gdx.graphics.getDeltaTime();
        currentFrame = walkAnimation.getKeyFrame(stateTime, true);
        spriteBatch.draw(currentFrame, bob.position.x * ppuX, bob.position.y * ppuY, facex*Bob.SIZE * ppuX, Bob.SIZE * ppuY);

		}
		else if(bob.state==bob.state.IDLE){
			spriteBatch.draw(bobTexture, bob.position.x * ppuX, bob.position.y * ppuY, facex* Bob.SIZE * ppuX, Bob.SIZE * ppuY);
		}

			//spriteBatch.draw(bobTexture, bob.position.x * ppuX, bob.position.y * ppuY, Bob.SIZE * ppuX, Bob.SIZE * ppuY);

	}

We are basically done!

Now put the hole class together:

package com.me.mygdxgame;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.math.Rectangle;

public class WorldRenderer {

 private World world;
 private OrthographicCamera cam;

 /** for debug rendering **/
 ShapeRenderer debugRenderer = new ShapeRenderer();

 public WorldRenderer(World world) {
  this.world = world;
  this.cam = new OrthographicCamera(10, 7);
  this.cam.position.set(5, 3.5f, 0);
  this.cam.update();

  spriteBatch = new SpriteBatch();
  loadTextures();
 }

	private static final float CAMERA_WIDTH = 10f;
	private static final float CAMERA_HEIGHT = 7f;
	private SpriteBatch spriteBatch;
	private boolean debug = false;
	private int width;
	private int height;
	private float ppuX;	// pixels per unit on the X axis
	private float ppuY;	// pixels per unit on the Y axis
	public void setSize (int w, int h) {
		this.width = w;
		this.height = h;
		ppuX = (float)width / CAMERA_WIDTH;
		ppuY = (float)height / CAMERA_HEIGHT;
	}
   private void drawBlocks() {

	          for (Block block : world.getBlocks()) {
	              spriteBatch.draw(blockTexture, block.position.x * ppuX, block.position.y * ppuY, Block.SIZE * ppuX, Block.SIZE * ppuY);
	          }

	      }

/** Textures **/
	private Texture bobTexture;
	private Texture blockTexture;

	private static final int        FRAME_COLS = 6;      
    private static final int        FRAME_ROWS = 5;        
    Animation                       walkAnimation;          
    Texture                         walkSheet;              
    TextureRegion[]                 walkFrames;             
    TextureRegion                   currentFrame;           

    float stateTime;                                        

	private void loadTextures() {
		walkSheet = new  Texture(Gdx.files.internal("animation_sheet.png"));
		TextureRegion[][] tmp = TextureRegion.split(walkSheet, walkSheet.getWidth() / 
				FRAME_COLS, walkSheet.getHeight() / FRAME_ROWS);
		walkFrames = new TextureRegion[FRAME_COLS * FRAME_ROWS];
        int index = 0;
        for (int i = 0; i < FRAME_ROWS; i++) {
                for (int j = 0; j < FRAME_COLS; j++) {
                        walkFrames[index++] = tmp[i][j];
                }
        }
        walkAnimation = new Animation(0.025f, walkFrames);

        stateTime = 0f;

        bobTexture = new  Texture(Gdx.files.internal("images/bob.png"));
        blockTexture = new Texture(Gdx.files.internal("images/block.png"));
	}
	public void render() {
		 spriteBatch.begin();
				drawBlocks();
				drawBob();
		 spriteBatch.end();

			if (debug)
				drawDebug();
		  }
	private void drawBob() {
		Bob bob = world.getBob();

		int facex=1;
		if(bob.facingLeft){
			facex=-1;
		}

		if (bob.state==bob.state.WALKING){
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
        stateTime += Gdx.graphics.getDeltaTime();
        currentFrame = walkAnimation.getKeyFrame(stateTime, true);
        spriteBatch.draw(currentFrame, bob.position.x * ppuX, bob.position.y * ppuY, facex*Bob.SIZE * ppuX, Bob.SIZE * ppuY);

		}
		else if(bob.state==bob.state.IDLE){
			spriteBatch.draw(bobTexture, bob.position.x * ppuX, bob.position.y * ppuY, facex* Bob.SIZE * ppuX, Bob.SIZE * ppuY);
		}

			//spriteBatch.draw(bobTexture, bob.position.x * ppuX, bob.position.y * ppuY, Bob.SIZE * ppuX, Bob.SIZE * ppuY);

	}
	private void drawDebug() {
		// render blocks
		debugRenderer.setProjectionMatrix(cam.combined);
		debugRenderer.begin(ShapeType.Line);
		for (Block block : world.getBlocks()) {
			Rectangle rect = block.bounds;
			float x1 = block.position.x + rect.x;
			float y1 = block.position.y + rect.y;
			debugRenderer.setColor(new Color(1, 0, 0, 1));
			debugRenderer.rect(x1, y1, rect.width, rect.height);
		}
		// render Bob
		Bob bob = world.getBob();
		Rectangle rect = bob.bounds;
		float x1 = bob.position.x + rect.x;
		float y1 = bob.position.y + rect.y;
		debugRenderer.setColor(new Color(0, 1, 0, 1));
		debugRenderer.rect(x1, y1, rect.width, rect.height);
		debugRenderer.end();
	}
 }

How to create simple menu in libgdx

Actually making menu using libgdx is pretty easy, but most probably because of the lack of tutorial or (proper SEO) initially it took me a little more time then usual to make it done, It has become easier for me when I have a look at their test cases provided. Let me share a simplified code with you guys. Here in this tutorial we will write code for a button that starts the game.

In our main method we have to run a new instance of LwjglApplication class which requires an ApplicationListener to launch. So we need to implement ApplicationListener for sure. As the Game class provides few extra benefit like setting which screen to show up and things. So in this blog I will be extending Game class. Game class has a setScreen method just changing it decides which method will be shown in the screen. We want to take advantage of it in future when the button will get pressed so I am sending a self instance of this class.

//MainMenuGame.java

package com.sadafnoor.MainMenu;
 
import com.badlogic.gdx.Game;
 
public class MainMenuGame extends Game {
@Override
public void create() {
setScreen(new MenuScreen(this));
}
}

Now we will be writing the code we are interested about. We will extend the screen class as it is required for setScreen(). We need to create a Stage to add our button which handles the viewing region and at the same time takes care of the input actions so we need to send it to input process as well.

stage = new Stage();
Gdx.input.setInputProcessor(stage);

We need to define the skin of our button which is basically the background color, fonts and so on.

BitmapFont bfont=new BitmapFont();
bfont.scale(1);
skin.add("default",bfont);

Now we need to define the style of our button, which is TextButtonStyle. Here will get a lot of options to deal with. we can define what colors will it take when the mouse is over it, when the button is pressed and so on. and then finally we can create our TextButtion. Then we can set the position of it and add it to the stage.

import com.badlogic.gdx.Game;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;

public class MenuScreen implements Screen {
	Skin skin;
	Stage stage;
	SpriteBatch batch;

	Game g;
	public MenuScreen(Game g){
		create();
		this.g=g;
	}

	public MenuScreen(){
		create();
	}
	public void create(){
		batch = new SpriteBatch();
		stage = new Stage();
		Gdx.input.setInputProcessor(stage);

		// A skin can be loaded via JSON or defined programmatically, either is fine. Using a skin is optional but strongly
		// recommended solely for the convenience of getting a texture, region, etc as a drawable, tinted drawable, etc.
		skin = new Skin();
		// Generate a 1x1 white texture and store it in the skin named "white".
		Pixmap pixmap = new Pixmap(100, 100, Format.RGBA8888);
		pixmap.setColor(Color.GREEN);
		pixmap.fill();

		skin.add("white", new Texture(pixmap));

		// Store the default libgdx font under the name "default".
		BitmapFont bfont=new BitmapFont();
		bfont.scale(1);
		skin.add("default",bfont);

		// Configure a TextButtonStyle and name it "default". Skin resources are stored by type, so this doesn't overwrite the font.
		TextButtonStyle textButtonStyle = new TextButtonStyle();
		textButtonStyle.up = skin.newDrawable("white", Color.DARK_GRAY);
		textButtonStyle.down = skin.newDrawable("white", Color.DARK_GRAY);
		textButtonStyle.checked = skin.newDrawable("white", Color.BLUE);
		textButtonStyle.over = skin.newDrawable("white", Color.LIGHT_GRAY);

		textButtonStyle.font = skin.getFont("default");

		skin.add("default", textButtonStyle);

		// Create a button with the "default" TextButtonStyle. A 3rd parameter can be used to specify a name other than "default".
		final TextButton textButton=new TextButton("PLAY",textButtonStyle);
		textButton.setPosition(200, 200);
		stage.addActor(textButton);
		stage.addActor(textButton);
		stage.addActor(textButton);

	}

	public void render (float delta) {
		Gdx.gl.glClearColor(0.2f, 0.2f, 0.2f, 1);
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		stage.act(Math.min(Gdx.graphics.getDeltaTime(), 1 / 30f));
		stage.draw();
		Table.drawDebug(stage);
	}

	@Override
	public void resize (int width, int height) {
		stage.setViewport(width, height, false);
	}

	@Override
	public void dispose () {
		stage.dispose();
		skin.dispose();
	}

	@Override
	public void show() {
		// TODO Auto-generated method stub

	}

	@Override
	public void hide() {
		// TODO Auto-generated method stub

	}

	@Override
	public void pause() {
		// TODO Auto-generated method stub

	}

	@Override
	public void resume() {
		// TODO Auto-generated method stub

	}
}

Now we will add callback function. When the key is pressed a callback function of addaction will get triggered and via our previously passed game we will change setScreen.

textButton.addListener(new ChangeListener() {
			public void changed (ChangeEvent event, Actor actor) {
				//System.out.println("Clicked! Is checked: " + button.isChecked());
				textButton.setText("Starting new game");
				g.setScreen( new GameScreen());

			}
		});

Altogether: