AndroidGameOfLife: El Juego de la Vida

[xtrasgu.org]Siguiendo con las aplicaciones programadas para Android, esta vez tengo el gusto de presentar una versión simplificada de El Juego de la Vida. La simplificación viene dada por las reglas que se aplican en la frontera del tablero, que no son las correctas.

A continuación, una captura de pantalla:

AndroidGameOfLife: El Juego de la Vida

El programa lo puedes descargar en AndroidGameOfLife, y el código fuente lo tienes aquí debajo:

/*
 * AndroidGameOfLife - Game of Life for Android. 
 * 
 * Copyright (c) 2011, Pablo López Cienfuegos <xtrasgu@gmail.com>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *   
 */

package org.xtrasgu.gameoflife;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

public class AndroidGameOfLife extends Activity {
	ViewGameOfLife viewgameoflife;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Set full screen view:
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);

		// Set screen always on:
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		// Set full brightness:
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.screenBrightness = 1.0f;
		getWindow().setAttributes(lp);

		// Set portrait orientation:
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		viewgameoflife = new ViewGameOfLife(this);
		setContentView(viewgameoflife);
	}

	private class ViewGameOfLife extends View {
		int HDIM = 160;
		int VDIM = 266;
		int SUM = 0;
		int MATRIXA[][] = new int[HDIM][VDIM];
		int MATRIXB[][] = new int[HDIM][VDIM];
		Paint paint = new Paint();

		public ViewGameOfLife(Context context) {
			super(context);
			generateGameOfLifeSeed();
		}

		public void generateGameOfLifeSeed() {
			for (int i = 0; i < HDIM; i++)
				for (int j = 0; j < VDIM; j++)
					MATRIXA[i][j] = (int) (Math.floor(Math.random() * 2.0));
			invalidate();
		}

		@Override
		public boolean onTouchEvent(MotionEvent event) {
			generateGameOfLifeSeed();
			return true;
		}

		@Override
		protected void onDraw(Canvas canvas) {

			// Set background:
			paint.setColor(Color.BLACK);
			paint.setStyle(Paint.Style.FILL);
			canvas.drawPaint(paint);

			// Game of Life:
			for (int i = 1; i < HDIM - 1; i++)
				for (int j = 1; j < VDIM - 1; j++) {
					SUM = MATRIXA[i - 1][j - 1] + MATRIXA[i - 1][j]
							+ MATRIXA[i - 1][j + 1] + MATRIXA[i][j - 1]
							+ MATRIXA[i][j + 1] + MATRIXA[i + 1][j - 1]
							+ MATRIXA[i + 1][j] + MATRIXA[i + 1][j + 1];
					if (SUM == 2)
						MATRIXB[i][j] = MATRIXA[i][j];
					else if (SUM == 3)
						MATRIXB[i][j] = 1;
					else
						MATRIXB[i][j] = 0;
				}

			for (int i = 0; i < HDIM; i++)
				for (int j = 0; j < VDIM; j++)
					MATRIXA[i][j] = MATRIXB[i][j];

			paint.setColor(Color.BLUE);
			for (int i = 0; i < HDIM; i += 2) {
				canvas.drawCircle(i * 2 + 1, 1, 1, paint);
				canvas.drawCircle(i * 2 - 1, VDIM * 2 - 1, 1, paint);
			}
			for (int j = 0; j < VDIM; j += 2) {
				canvas.drawCircle(1, j * 2 + 1, 1, paint);
				canvas.drawCircle(HDIM * 2 - 1, j * 2 + 3, 1, paint);
			}

			paint.setColor(Color.YELLOW);
			for (int i = 1; i < HDIM; i += 2) {
				canvas.drawCircle(i * 2 + 1, 1, 1, paint);
				canvas.drawCircle(i * 2 - 1, VDIM * 2 - 1, 1, paint);
			}
			for (int j = 1; j < VDIM; j += 2) {
				canvas.drawCircle(1, j * 2 + 1, 1, paint);
				canvas.drawCircle(HDIM * 2 - 1, j * 2 - 1, 1, paint);
			}

			paint.setColor(Color.GREEN);
			for (int i = 0; i < HDIM; i++)
				for (int j = 0; j < VDIM; j++)
					if (MATRIXA[i][j] == 1)
						canvas.drawCircle(i * 2 + 1, j * 2 + 1, 1, paint);
			invalidate();
		}
	}
}

AndroidGenerateSID: Generador Aleatorio de Nombres de Sistema SAP

[xtrasgu.org]Teniendo en cuenta el gran éxito de GenerateSID: Generador Aleatorio de Nombres de Sistema SAP, y el de su secuela GenerateSID: Generador Aleatorio de Nombres de Sistema SAP (v2.0), era evidente que la saga no podía terminar ahí.

Aprovechando el entorno de desarrollo que estuve configurando en Installing the Android SDK under Debian GNU/LiNUX 5.0 Lenny, he modificado el Generador Aleatorio de Nombres de Sistema SAP para que ahora funcione en Android.

El aspecto de la aplicación, como suele ser habitual, impecable:

AndroidGenerateSID: Generador Aleatorio de Nombres de Sistema SAP

Si te apetece probarlo, lo puedes descargar en AndroidGenerateSID.

Ya por último, y como de costumbre, el código fuente del programa:

/*
 * AndroidGenerateSID - Let Android choose an SAP SID for you. 
 * 
 * Copyright (c) 2010, Pablo López Cienfuegos 
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see .
 *   
 */

package org.xtrasgu.generatesid;

import java.util.Arrays;
import android.app.Activity;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;

public class AndroidGenerateSID extends Activity {
	ViewGenerateSID viewgeneratesid;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Set full screen view:
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Set full brightness:
		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.screenBrightness = 1.0f;
		getWindow().setAttributes(lp);

		viewgeneratesid = new ViewGenerateSID(this);
		setContentView(viewgeneratesid);
	}

	private class ViewGenerateSID extends View {

		public ViewGenerateSID(Context context) {
			super(context);
		}

		@Override
		public boolean onTouchEvent(MotionEvent event){
			invalidate();
			return true;
		}
		
		@Override
		protected void onDraw(Canvas canvas) {
			Paint paint = new Paint();
			
			// Set background:
			paint.setColor(Color.BLACK);
			paint.setStyle(Paint.Style.FILL);
			canvas.drawPaint(paint);
			
			// Set foreground: 
			paint.setColor(Color.WHITE);
			paint.setStyle(Paint.Style.FILL_AND_STROKE);
			paint.setAntiAlias(true);
			paint.setTextSize(120);
			paint.setTextAlign(Paint.Align.CENTER);
			canvas.drawText(generateSID(), canvas.getWidth()/2, canvas.getHeight()/2, paint);
		}
		
		public String generateSID() {
			int rnd;
			String sid;
			String alfa="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			String alfanum=alfa+"0123456789";
			String[] existingSIDs={};	//Add your existing system landscape SIDs
			String[] exceptionSIDs={"ADD", "ALL", "AND", "ANY", "ASC", "AUX", "COM", "CON", "DBA",
					"END", "EPS", "FOR", "GID", "IBM", "INT", "KEY", "LOG", "LPT",
					"MON", "NIX", "NOT", "NUL", "OFF", "OMS", "PRN", "RAW", "ROW",
					"SAP", "SET", "SGA", "SHG", "SID", "SQL", "SYS", "TMP", "UID",
					"USR", "VAR"}; 
			
			sid="ADD";
			while(Arrays.binarySearch(existingSIDs, sid)>-1 || Arrays.binarySearch(exceptionSIDs, sid)>-1){
				rnd=(int)Math.floor(Math.random()*alfa.length());
				sid=""+alfa.substring(rnd, rnd+1);
				for(int i=0;i<2;i++){
					rnd=(int)Math.floor(Math.random()*alfanum.length());
					sid+=alfanum.substring(rnd, rnd+1);
				}
			}
			return sid;
		}
	}
}

AndroidLight: Usando la Pantalla como Linterna

[xtrasgu.org]¿Para qué vale Instalar el SDK de Android en Debian GNU/LiNUX 5.0 Lenny? Pues vale para programar aplicaciones para Android, siempre y cuando sepas algo de Java.

El primer Android que tuve fue un HTC Magic que venía sin ningún tipo de led que permitiese usar el móvil como si fuese una linterna, por lo que buscando en el Android Market, encontré una aplicación que ponía la pantalla del móvil en blanco y subía el brillo lo suficiente como para poder entrar en una habitación a oscuras sin dejarte un dedo del pie en el intento.

Esta aplicación parecía una buena candidata para empezar, ya que la usaba de vez en cuando, no podía ser muy complicada de programar, y la que había encontrado en el Android Market me pedía demasiados permisos para ser una aplicación que sólo ponía el fondo de la pantalla en blanco…

Programar para Android es bastante sencillo, ya que una vez que consigues el esqueleto de la aplicación, añadirle funcionalidades es tan fácil como buscar en Google algún foro en el que expliquen cómo pasar el móvil a pantalla completa, o cómo usar el sensor de movimiento, o lo que necesites.

Sin más, el código de AndroidLight:

/*
 * AndroidLight - Use a white screen in your Android as a torch. 
 * 
 * Copyright (c) 2010, Pablo López Cienfuegos 
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see .
 *   
 */

package org.xtrasgu.light;

import android.app.Activity;
import android.view.Window;
import android.view.WindowManager;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;

public class AndroidLight extends Activity {
    ViewLight viewlight;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set full screen view:
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // Set full brightness:
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.screenBrightness = 1.0f;
        getWindow().setAttributes(lp);

        viewlight = new ViewLight(this);
        setContentView(viewlight);
    }

    private class ViewLight extends View {
        public ViewLight(Context context) {
            super(context);
        }

        @Override
        protected void onDraw(Canvas canvas) {
            Paint paint = new Paint();
            paint.setStyle(Paint.Style.FILL);
            paint.setColor(Color.WHITE);
            canvas.drawPaint(paint);
        }
    }
}

Pondría una captura de pantalla, pero no me pareció que hiciese falta poner una pantalla completamente en blanco… 🙂

Installing the Android SDK under Debian GNU/LiNUX 5.0 Lenny

Eclipse AndroidEsta entrada está escrita en bárbaro ya que fue creada originalmente para C3, el portal corporativo de CSC abierto a la participación de los empleados. Tranquilos todos que no me estoy volviendo loco, sencillamente es una cuestión de patrones y marineros…

In this blog entry, I’ll try to provide some tips to get an Android development environment running under Debian GNU/LiNUX 5.0 Lenny. First of all, let’s see what documentation we have:

As a general advise for this documentation, if they state that you can install Eclipse 3.3 or Eclipse 3.4, it means that you must choose between those two options; using the latest Eclipse version, is not a good idea… you are warned!

In my case, I downloaded the Eclipse IDE for Java Developers from the Eclipse Ganymede Sr2 Packages page, as JDK I’m using the sun-java6 package provided by Debian, and I got the android-sdk-linux_x86-1.5 from Download Android 1.5 SDK, Release 3.

I only had a couple of problems with the installation, both of them already mentioned in the documentation:

  1. You must use the JDK provided by Sun, not the gcj version usually shiped with Debian; you can use update-alternatives –config java to configure what JDK version you are using.
  2. If you cannot configure the Eclipse’s remote installation URL using https://dl-ssl.google.com/android/eclipse/, you must try using http://dl-ssl.google.com/android/eclipse/ instead (no SSL version).

And that’s all! Now you can start developing Android applications from Debian GNU/LINUX…