English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Ejemplo de juego de goma de ajedrez simple implementado en Android

Este artículo muestra un ejemplo de un juego simple de GoBang implementado en Android. Lo comparto con todos para que lo refieran, como se detalla a continuación:

Acabo de escribir un pequeño programa de GoBang en Android y aquí lo comparto con todos.

Después de escribir, siento que el SDK de Android, aunque también utiliza Java, es muy diferente de Java ME.

Primero, el SDK de Android no implementa todos los estándares de Java ME, y las aplicaciones que se ejecutaban en KJava no se pueden ejecutar directamente en Android.

Además, el SDK de Android tiene una gran cantidad de API propias, que los desarrolladores deben conocer.

El framework de desarrollo de Android es diferente de otros, y es necesario aprender.

Este juego de GoBang es una referencia al Demo de Snake de Android y otros ejemplos, más con mis propias necesidades.

Entre las funciones implementadas se incluyen el tablero, hacer movimientos, determinar el ganador, y reiniciar el juego. Actualmente, no se ha implementado la función de inteligencia artificial para hacer movimientos.

La función táctil de Android es bastante útil, hace poco vi una demostración de G1La pantalla táctil es muy útil, y el "Window" de Android, "Shade" y la táctil juntos se ven muy impresionantes.

Uhm, este GoBang también se realiza con la pantalla táctil para hacer movimientos. Haz clic en una posición del tablero para caer una pieza en el tablero.

Primero, coloquemos una imagen para ver el efecto.

Bueno, aquí va el código directamente:

/*
 * Five In a Row. (GoBang)
 * Este es un programa simple de GoBang, que es un ejercicio propio, y lo publico aquí para compartir con todos.
 * Espero poder comunicarme más con todos ustedes. Mi GoogleTalk: lixinso <at> gmail.com
 *
 *
 */
//----------------------
//TBD: IA, reversión de jugadas
//---------------------
package lixinsong.game.gobang;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
//Este es el programa principal, heredado de Activity, que implementa el método onCreate.:
public class gobang extends Activity {
 GobangView gbv;
 /** Llamado cuando la actividad se crea por primera vez. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  gbv = (GobangView)this.findViewById(R.id.gobangview);
  gbv.setTextView((TextView)this.findViewById(R.id.text));
}

La vista R.id.gobangview está definida en res.

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent">
 <lixinsong.game.gobang.GobangView android:id="@"+id/gobangview"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:text="aaaaa" tileSize="24" />
 <RelativeLayout
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:layout_centerInParent="true" >
  <TextView
   android:id="@"+id/text"
   android:text="hahahhaha"
   android:visibility="visible"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:gravity="center_horizontal"
   android:textColor="#ffff0000"
   android:textStyle="bold"
   android:textSize="24sp" />
  </RelativeLayout>
</FrameLayout>

View de GoBang

package lixinsong.game.gobang;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
/*la rejilla en total10×10casilla
 * centrado de la rejilla
 *
 *
 *
 */
//public class GobangView extends View implements Runnable {
public class GobangView extends View{
 protected static int GRID_SIZE = 10;
 protected static int GRID_WIDTH = 30; // ancho de las casillas de la rejilla
 protected static int CHESS_DIAMETER = 26; // diámetro de las piezas
 protected static int mStartX;// ubicación superior izquierda de la rejilla en X
 protected static int mStartY;// ubicación superior izquierda de la rejilla
 private Bitmap[] mChessBW; // piezas negras y blancas
 private static int[][] mGridArray; // la rejilla
 boolean key = false;
 wbflag = 1; //ahora es el turno del ajedrez blanco=2ahora es el turno del ajedrez negro=1. Aquí primero pongo el ajedrez negro (el ajedrez negro se configurará para que sea el tablero del ordenador más tarde)
 int mLevel = 1; //Dificultad del juego
 int mWinFlag = 0;
 private final int BLACK=1;
 private final int WHITE=2;
 int mGameState = GAMESTATE_RUN; //Fase del juego: 0=Juego no iniciado,1=Juego en curso,2=Final del juego
 static final int GAMESTATE_PRE = 0;
 static final int GAMESTATE_RUN = 1;
 static final int GAMESTATE_PAUSE = 2;
 static final int GAMESTATE_END = 3;
 //private TextView mStatusTextView; // Establecer el texto de visualización según el estado del juego
 public TextView mStatusTextView; // Establecer el texto de visualización según el estado del juego
 private Bitmap btm1;
 private final Paint mPaint = new Paint();
 CharSequence mText;
 CharSequence STRING_WIN = "¡Gana el blanco!" /n Presione la tecla de Fuego para comenzar un nuevo juego.";
 CharSequence STRING_LOSE = "¡Gana el negro!" /n Presione la tecla de Fuego para comenzar un nuevo juego.";
 CharSequence STRING_EQUAL = "¡Genial! Estás igual!" /n Presione la tecla de Fuego para comenzar un nuevo juego.";
 public GobangView(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
  }
 public GobangView(Context context, AttributeSet attrs) { //Parece que se está llamando a este constructor, ¿por qué no el anterior?
  super(context, attrs);
  this.setFocusable(true); //20090530
  this.setFocusableInTouchMode(true);
  init();}}
 }
 //Aquí se dibujan las piezas de ajedrez, más tarde no se utilizaron imágenes, sino que se dibujaron directamente círculos. Porque las imágenes que hice no se ven bien.
 // Inicializar el Bitmap de las piezas negras y blancas
 public void init() {
  mGameState = 1; //Configurar el estado del juego como iniciado
  wbflag = BLACK; //El primer jugador es el negro.
  mWinFlag = 0; //Limpiar las marcas de victoria y derrota.
  mGridArray = new int[GRID_SIZE-1][GRID_SIZE-1];
  mChessBW = new Bitmap[2];
  Bitmap bitmap = Bitmap.createBitmap(CHESS_DIAMETER, CHESS_DIAMETER, Bitmap.Config.ARGB_8888);
  Canvas canvas = new Canvas(bitmap);
  Resources r = this.getContext().getResources();
  Drawable tile = r.getDrawable(R.drawable.chess1);
  tile.setBounds(0, 0, CHESS_DIAMETER, CHESS_DIAMETER);
  tile.draw(canvas);
  mChessBW[0] = bitmap;
  tile = r.getDrawable(R.drawable.chess2);
  tile.setBounds(0, 0, CHESS_DIAMETER, CHESS_DIAMETER);
  tile.draw(canvas);
  mChessBW[1] = bitmap;
 }
 public void setTextView(TextView tv){
  mStatusTextView =tv;
  mStatusTextView.setVisibility(View.INVISIBLE);
 }
 @Override
 protected void onSizeChanged(int w, int h, int oldw, int oldh) {
  mStartX = w / 2 - GRID_SIZE * CHESS_DIAMETER / 2;
  mStartY = h / 2 - GRID_SIZE * CHESS_DIAMETER / 2;
 }
  @Override
 public boolean onTouchEvent(MotionEvent event){
  switch (mGameState) {
  case GAMESTATE_PRE:
   break;
  case GAMESTATE_RUN: {
    int x;
    int y;
    float x0 = GRID_WIDTH - (event.getX() - mStartX) % GRID_WIDTH;
    float y0 = GRID_WIDTH) - (event.getY() - mStartY) % GRID_WIDTH;
    if (x0 < GRID_WIDTH / 2) {
     x = (int) ((event.getX() - mStartX) / GRID_WIDTH);
    } else {
     x = (int) ((event.getX() - mStartX) / GRID_WIDTH) - 1;
    }
    if (y0 < GRID_WIDTH / 2) {
     y = (int) ((event.getY() - mStartY) / GRID_WIDTH);
    } else {
     y = (int) ((event.getY() - mStartY) / GRID_WIDTH) - 1;
    }
    if ((x >= 0 && x < GRID_SIZE - 1)
      && (y >= 0 && y < GRID_SIZE - 1)) {
     if (mGridArray[x][y] == 0) {
      if (wbflag == BLACK) {
       putChess(x, y, BLACK);
       //this.mGridArray[x][y] = 1;
       if(checkWin(BLACK)){ //Si el rey negro ha ganado
        mText = STRING_LOSE;
        mGameState = GAMESTATE_END;
        showTextView(mText);
       } else if(checkFull()){//Si el tablero está lleno
        mText = STRING_EQUAL;
        mGameState = GAMESTATE_END;
        showTextView(mText);
       }
       wbflag = WHITE;
      } else if (wbflag == WHITE) {
       putChess(x, y, WHITE);
       //this.mGridArray[x][y] = 2;
       if(checkWin(WHITE)){
        mText = STRING_WIN;
        mGameState = GAMESTATE_END;
        showTextView(mText);
       } else if(checkFull()){//Si el tablero está lleno
        mText = STRING_EQUAL;
        mGameState = GAMESTATE_END;
        showTextView(mText);
       }
       wbflag = BLACK;
      }
     }
    }
   }
   break;
  case GAMESTATE_PAUSE:
   break;
  case GAMESTATE_END:
   break;
  }
  this.invalidate();
  else
 }
 @Override
 public boolean onKeyDown(int keyCode, KeyEvent msg) {
  Log.e("KeyEvent.KEYCODE_DPAD_CENTER", " "); + keyCode);
  if(keyCode == KeyEvent.KEYCODE_DPAD_CENTER){
   switch(mGameState){
   case GAMESTATE_PRE:
    break;
   case GAMESTATE_RUN:
    break;
   case GAMESTATE_PAUSE:
    break;
   case GAMESTATE_END:
   Paint paintCircle = new Paint();//El juego termina, presione el botón CENTER para continuar
    Log.e("Fire Key Pressed:::", "FIRE");
    mGameState = GAMESTATE_RUN;
    this.setVisibility(View.VISIBLE);
    this.mStatusTextView.setVisibility(View.INVISIBLE);
    this.init();
    this.invalidate();
   }
    break;
   }
  }
  return super.onKeyDown(keyCode, msg);
 }
 @Override
 public void onDraw(Canvas canvas) {
  canvas.drawColor(Color.YELLOW);
  // 画棋盘
  Paint paintCircle = new Paint();
   Paint paintRect = new Paint();
   paintRect.setColor(Color.GRAY);
   paintRect.setStrokeWidth(2);
   paintRect.setStyle(Style.STROKE);
   for (int i = 0; i < GRID_SIZE; i++) {
    for (int j = 0; j < GRID_SIZE; j++) {
     int mLeft = i * CHESS_DIAMETER + mStartX;
     int mTop = j * CHESS_DIAMETER + mStartY;
     int mRright = mLeft + GRID_WIDTH;
     int mBottom = mTop + GRID_WIDTH;
     canvas.drawRect(mLeft, mTop, mRright, mBottom, paintRect);
    }
   }
   //画棋盘的外边框
   paintRect.setStrokeWidth(4);
   canvas.drawRect(mStartX, mStartY, mStartX + CHESS_DIAMETER*GRID_SIZE, mStartY + CHESS_DIAMETER*GRID_SIZE, paintRect);
  }
  //画棋子
  for (int i = 0; i < GRID_SIZE-1; i++) {
   for (int j = 0; j < GRID_SIZE-1; j++) {
    if(mGridArray[i][j] == BLACK){
     //通过图片来画
     //canvas.drawBitmap(mChessBW[0], mStartX + GRID_WIDTH, mStartY+1) * CHESS_DIAMETER - , mPaint);/2 GRID_WIDTH + GRID_WIDTH, CHESS_DIAMETER+1)* CHESS_DIAMETER - , mPaint);/2 通过圆形来画
     //{
      Paint paintCircle = new Paint();
      paintCircle.setColor(Color.WHITE);
      paintCircle.setColor(Color.BLACK);
      (i + GRID_WIDTH, mStartY+1) * (j + GRID_WIDTH, CHESS_DIAMETER+1)* , paintCircle);/2public void putChess(int x, int y, int blackwhite){
     }
    }else if(mGridArray[i][j] == WHITE){
     //通过图片来画
     //canvas.drawBitmap(mChessBW[1, mStartY + GRID_WIDTH, mStartY+1) * CHESS_DIAMETER - , mPaint);/2 GRID_WIDTH + GRID_WIDTH, CHESS_DIAMETER+1)* CHESS_DIAMETER - , mPaint);/2 通过圆形来画
     //{
     Paint paintCircle = new Paint();
      paintCircle.setColor(Color.WHITE);
      canvas.drawCircle(mStartX
      (i + GRID_WIDTH, mStartY+1) * (j + GRID_WIDTH, CHESS_DIAMETER+1)* , paintCircle);/2public void putChess(int x, int y, int blackwhite){
     }
    }
   }
  }
 }
 mGridArray[x][y] = blackwhite;
  public boolean checkWin(int wbflag){
 }
 i表示列(根据宽度算出来的)
  for(int i = 0; i < GRID_SIZE - 1 ; i++ ) //i表示行(根据高度算出来的)
   for(int j = 0; j < GRID_SIZE - 1; j++{//检测横轴五个相连
    //] == wbflag)&& (mGridArray[i
    ) >= 0)&& ((j+4)) && - 1(mGridArray[i][j] == wbflag) && (mGridArray[i][j
     ] == wbflag)&& (mGridArray[i+1][j] == wbflag) && (mGridArray[i + 2][j] == wbflag)){ + 3][j] == wbflag)){ + 4纵轴
     "win"); + mWinFlag = wbflag;
     if( mWinFlag == wbflag){
    }
    //))&&5if(((i
    ))&& ((i+4)) && - 1(mGridArray[i][j] == wbflag) && (mGridArray[i][j
       ] == wbflag)&& (mGridArray[i ][j+1] == wbflag) && (mGridArray[i ][j+ 2左上到右下+ 3左上到右下+ 4Log.e("check win or loss:", wbflag
       "win"); + mWinFlag = wbflag;
       if( mWinFlag == wbflag){
      }
    //if(((j5if(((i
    ))&& ((i+4)) && - 1右上到左下+4)) && - 1(mGridArray[i][j] == wbflag) && (mGridArray[i
       ] == wbflag)&& (mGridArray[i+1] == wbflag)){+1] == wbflag) && (mGridArray[i + 2 ] == wbflag)){+ 2][j + 3] == wbflag)){+ 3][j + 4 ] == wbflag)){+ 4Log.e("check win or loss:", wbflag
       "win"); + mWinFlag = wbflag;
       if( mWinFlag == wbflag){
      }
    //个相连5if(((i
    ) >= 0)&& ((j-4) < (GRID_SIZE+4)) && - 1(mGridArray[i][j] == wbflag) && (mGridArray[i
       ] == wbflag)&& (mGridArray[i-1] == wbflag)){+1] == wbflag) && (mGridArray[i - 2 ] == wbflag)){+ 2][j - 3] == wbflag)){+ 3][j - 4 ] == wbflag)){+ 4Log.e("check win or loss:", wbflag
       "win"); + mWinFlag = wbflag;
       if( mWinFlag == wbflag){
      }
  }
  return true;
   else
  }
   return false;
 }
 public boolean checkFull() {
  int mNotEmpty = 0;
  for(int i = 0; i < GRID_SIZE -1; i ++)
   for(int j = 0; j < GRID_SIZE - 1; j ++{
    if(mGridArray[i][j] != 0) mNotEmpty +=1;
   }
  if(mNotEmpty == (GRID_SIZE-1)*(GRID_SIZE-1)) return true;
  else return false;
 }
 public void showTextView(CharSequence mT){
  this.mStatusTextView.setText(mT);
  mStatusTextView.setVisibility(View.VISIBLE);
 }
}

PS: Aquí también recomiendo otro juego de goma de cinco en línea en versión js de este sitio para que todos lo consideren (su IA es relativamente simple).

Juego de goma de cinco en línea en línea:
http://tools.jb51.net/juegos/wuziqi

Los lectores interesados en más contenido relacionado con Android pueden ver la sección especial de este sitio: 'Tutorial de inicio y avanzado de desarrollo de Android', 'Técnicas de depuración y métodos de solución de problemas comunes de Android', 'Resumen de uso de componentes básicos de Android', 'Resumen de técnicas de View de Android', 'Resumen de técnicas de layout de Android' y 'Resumen de uso de controles de Android'.

Espero que lo descrito en este artículo pueda ayudar a todos en el diseño de programas Android.

Declaración: Este artículo se ha obtenido de la red, pertenece al propietario original, el contenido ha sido contribuido y subido por los usuarios de Internet, este sitio web no posee los derechos de propiedad, no ha sido editado por humanos y no asume la responsabilidad de las responsabilidades legales relacionadas. Si encuentra contenido sospechoso de infracción de derechos de autor, por favor envíe un correo electrónico a: notice#w3Declaración: El contenido de este artículo se ha obtenido de la red, pertenece al propietario original, el contenido ha sido contribuido y subido por los usuarios de Internet, este sitio web no posee los derechos de propiedad, no ha sido editado por humanos y no asume la responsabilidad de las responsabilidades legales relacionadas. Si encuentra contenido sospechoso de infracción de derechos de autor, por favor envíe un correo electrónico a: notice#w

Te gustará