Juego Java programación Tutorial - Flappy pájaro Redux (5 / 12 paso)

Paso 5: Jugador y clases de obstáculo

Ya que estamos empezando con el esqueleto de las clases, ahora avanzamos a escribir las clases jugador y obstáculo. Por defecto, debemos saber que estas clases sirven un propósito básico: cargar la imagen de recursos utilizada por el objeto, la escala de la imagen a las dimensiones deseadas, haz y establece las coordenadas X e Y (la esquina superior izquierda de las imágenes; xLoc y yLoc) y, la anchura y la altura de la imagen del objeto.

Porque ya he realizado este proyecto, voy a soltar un spoiler de todos: para la detección de la colisión, explicó en un paso posterior, también necesita un método que devuelve un rectángulo que abarque el objeto, así como un método que devuelve BufferedImage el objeto. Ahora que sabes todo lo que ha requerido, le daré el código completo para las clases de pájaro, BottomPipe y TopPipe. Las tres clases son idénticamente estructuradas, difiriendo sólo en convenciones de nomenclatura.

Cuando primero se crean instancias de las clases, el ancho deseado y la altura de las imágenes pasan a la clase en el constructor, que escalará automáticamente la imagen llamando al método de la escala. Por último, se dará cuenta existen métodos getAncho y getHeight que contienen un bloque try/catch. Esto es para ayudar con la prevención de problemas de lógica en TopClass.

Usted puede notar cuando se crea el buffer de objetos, se crea utilizando el tipo ARGB. Esto se basa en el deseo de un canal alfa que se incluirán. Usted verá por qué en el paso de detección de colisión.

 import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Image; import java.awt.image.BufferedImage; public class Bird { //global variables private Image flappyBird; private int xLoc = 0, yLoc = 0; /** * Default constructor */ public Bird(int initialWidth, int initialHeight) { flappyBird = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/blue_bird.png")); scaleBird(initialWidth, initialHeight); } /** * Method to scale the bird sprite into the desired dimensions * width The desired width of the flappy bird * height The desired height of the flappy bird */ public void scaleBird(int width, int height) { flappyBird = flappyBird.getScaledInstance(width, height, Image.SCALE_SMOOTH); } /** * Getter method for the flappyBird object. * Image */ public Image getBird() { return flappyBird; } /** * Method to obtain the width of the Bird object * int */ public int getWidth() { try { return flappyBird.getWidth(null); } catch(Exception e) { return -1; } } /** * Method to obtain the height of the Bird object * int */ public int getHeight() { try { return flappyBird.getHeight(null); } catch(Exception e) { return -1; } } /** * Method to set the x location of the Bird object * x */ public void setX(int x) { xLoc = x; } /** * Method to get the x location of the Bird object * int */ public int getX() { return xLoc; } /** * Method to set the y location of the Bird object * y */ public void setY(int y) { yLoc = y; } /** * Method to get the y location of the Bird object * int */ public int getY() { return yLoc; } /** * Method used to acquire a Rectangle that outlines the Bird's image * Rectangle outlining the bird's position on screen */ public Rectangle getRectangle() { return (new Rectangle(xLoc, yLoc, flappyBird.getWidth(null), flappyBird.getHeight(null))); } /** * Method to acquire a BufferedImage that represents the Bird's image object * Bird's BufferedImage object */ public BufferedImage getBI() { BufferedImage bi = new BufferedImage(flappyBird.getWidth(null), flappyBird.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics g = bi.getGraphics(); g.drawImage(flappyBird, 0, 0, null); g.dispose(); return bi; } } 
 import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Image; import java.awt.image.BufferedImage; public class BottomPipe { //global variables private Image bottomPipe; private int xLoc = 0, yLoc = 0; /** * Default constructor */ public BottomPipe(int initialWidth, int initialHeight) { bottomPipe = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/tube_bottom.png")); scaleBottomPipe(initialWidth, initialHeight); } /** * Method to scale the BottomPipe sprite into the desired dimensions * width The desired width of the BottomPipe * height The desired height of the BottomPipe */ public void scaleBottomPipe(int width, int height) { bottomPipe = bottomPipe.getScaledInstance(width, height, Image.SCALE_SMOOTH); } /** * Getter method for the BottomPipe object. * Image */ public Image getPipe() { return bottomPipe; } /** * Method to obtain the width of the BottomPipe object * int */ public int getWidth() { return bottomPipe.getWidth(null); } /** * Method to obtain the height of the BottomPipe object * int */ public int getHeight() { return bottomPipe.getHeight(null); } /** * Method to set the x location of the BottomPipe object * x */ public void setX(int x) { xLoc = x; } /** * Method to get the x location of the BottomPipe object * int */ public int getX() { return xLoc; } /** * Method to set the y location of the BottomPipe object * y */ public void setY(int y) { yLoc = y; } /** * Method to get the y location of the BottomPipe object * int */ public int getY() { return yLoc; } /** * Method used to acquire a Rectangle that outlines the BottomPipe's image * Rectangle outlining the BottomPipe's position on screen */ public Rectangle getRectangle() { return (new Rectangle(xLoc, yLoc, bottomPipe.getWidth(null), bottomPipe.getHeight(null))); } /** * Method to acquire a BufferedImage that represents the TopPipe's image object * TopPipe's BufferedImage object */ public BufferedImage getBI() { BufferedImage bi = new BufferedImage(bottomPipe.getWidth(null), bottomPipe.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics g = bi.getGraphics(); g.drawImage(bottomPipe, 0, 0, null); g.dispose(); return bi; } } 
 import java.awt.Graphics; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.Image; import java.awt.image.BufferedImage; public class TopPipe { //global variables private Image topPipe; private int xLoc = 0, yLoc = 0; /** * Default constructor */ public TopPipe(int initialWidth, int initialHeight) { topPipe = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource("resources/tube_top.png")); scaleTopPipe(initialWidth, initialHeight); } /** * Method to scale the topPipe sprite into the desired dimensions * width The desired width of the topPipe * height The desired height of the topPipe */ public void scaleTopPipe(int width, int height) { topPipe = topPipe.getScaledInstance(width, height, Image.SCALE_SMOOTH); } /** * Getter method for the TopPipe object. * Image */ public Image getPipe() { return topPipe; } /** * Method to obtain the width of the TopPipe object * int */ public int getWidth() { return topPipe.getWidth(null); } /** * Method to obtain the height of the TopPipe object * int */ public int getHeight() { return topPipe.getHeight(null); } /** * Method to set the x location of the TopPipe object * x */ public void setX(int x) { xLoc = x; } /** * Method to get the x location of the TopPipe object * int */ public int getX() { return xLoc; } /** * Method to set the y location of the TopPipe object * y */ public void setY(int y) { yLoc = y; } /** * Method to get the y location of the TopPipe object * int */ public int getY() { return yLoc; } /** * Method used to acquire a Rectangle that outlines the TopPipe's image * Rectangle outlining the TopPipe's position on screen */ public Rectangle getRectangle() { return (new Rectangle(xLoc, yLoc, topPipe.getWidth(null), topPipe.getHeight(null))); } /** * Method to acquire a BufferedImage that represents the TopPipe's image object * TopPipe's BufferedImage object */ public BufferedImage getBI() { BufferedImage bi = new BufferedImage(topPipe.getWidth(null), topPipe.getHeight(null), BufferedImage.TYPE_INT_ARGB); Graphics g = bi.getGraphics(); g.drawImage(topPipe, 0, 0, null); g.dispose(); return bi; } } 

Artículos Relacionados

Flappy pájaro Valentín Pop-Up tarjeta cómo 3D de Kirigami (Flappy de San Valentín).

Flappy pájaro Valentín Pop-Up tarjeta cómo 3D de Kirigami (Flappy de San Valentín).

Una rápida tarjeta de San Valentín hice basado en el popular juego de pájaros Flappy.Compartir en FACEBOOK: http://on.fb.me/15TrVYfTWEET: http://bit.ly/15Ts5P6MENÉAME: http://bit.ly/16qHt5LTUMBLR: http://bit.ly/10K8fhzDescargar el patrón gratis aquí:
Java programación Part2(Text and running)

Java programación Part2(Text and running)

En su java.java tendrás el código-la clase java {}público principal vacío estático (String args[]) {}}}Así que si vamos a hacer programas en java tenemos texto y el código para una simple línea de texto es-System.out.println ("programación en Java Ho
Java programación 2 | Cómo trabajar con Eclipse (Java)

Java programación 2 | Cómo trabajar con Eclipse (Java)

Hoy vamos a aprender cómo hacer un proyecto en Eclipse y cómo usar Java! Usted necesita descargar Eclipse (https://eclipse.org/downloads/) y Java (https://www.java.com/download/).Paso 1: Hacer una carpeta!El primer paso es hacer una carpeta. Puede co
Utilice el Bloc de notas y comandos para Java programación

Utilice el Bloc de notas y comandos para Java programación

Hola, en este instructable, les mostraré cómo crear y ejecutar un programa creado en java utilizando el Bloc de notas. Se necesita abrir algunas cosas:-Bloc de notas-El símbolo del sistemaPaso 1: Crear el programa de Para este paso, utilice el Bloc d
Java programación - interés compuesto

Java programación - interés compuesto

Hola en este Instructable mostrará usted cómo crear un programa en Java que calcula el interés aplicado al capital depositado a largo del tiempo.  Antes de empezar este Instructable necesita cosas:1. un ordenador de sobremesa o portátiles2. un compil
Programación Tutorial [Scratch] - Cookie Clicker -

Programación Tutorial [Scratch] - Cookie Clicker -

¡ Hola chicos!Hoy te enseñaré cómo programar a tu clicker propia galleta, desde cero, usando el lenguaje de programación llamado scratch!Suscríbete al canal de YouTube para más tutoriales!-----CreateTech-----
Java programación Parte1 (configurar Eclipse)

Java programación Parte1 (configurar Eclipse)

Antes de empezar a programar java tenemos que configurar un ide de java. Se llama eclipse se puede descargar aquí.Paso 1: Crear un proyecto deAhora que ya tienes descargado eclipse tenemos que crear un proyecto java. El nombre java. Ahora, haga clic
Juego de tronos Dragon - Tutorial de maquillaje SFX

Juego de tronos Dragon - Tutorial de maquillaje SFX

Emparejar con alguien va como Daenerys Targaryen y ser un dragón épico en la fiesta de halloween este año!Colorida y detallada y lo mejor de todo - puede comer y beber sin problemas.Preparaciones de tiempo alrededor de 1, 5hTiempo de aplicación aprox
Volver a entrar pájaros Flappy

Volver a entrar pájaros Flappy

Paso 1: Ir a la App Store Go to the app store. A continuación, haga clic en compra. A continuación encuentra flappy pájaro en compras. Finalmente golpéelo suavemente y deje que se cargue.Paso 2: Juego de pájaros Flappy Enjoy
Cómo hacer backup progreso pájaro Flappy y transferirlo a otro iPhone

Cómo hacer backup progreso pájaro Flappy y transferirlo a otro iPhone

Flappy pájaro ha convertido rápidamente en uno de los juegos más populares para el iPhone.Su creador lo quitaron de la App Store, sin embargo ha puesto prometido regreso del juego este que viene agosto.Si todavía tienes la versión antigua del juego g
Cómo jugar Java [ME] Juegos en una PSP!

Cómo jugar Java [ME] Juegos en una PSP!

Esto es relativamente fácil pero tu PSP tiene custom firmware. Son el tipo de juegos java, todo bien pero algunos funcionan bien y otras no. Personas hacen esto una de las razones principales es que puede ejecutar mini opera en tu PSP utilizando esto
Cómo descargar pájaros Flappy

Cómo descargar pájaros Flappy

Gracias por conocer esta revisión Flappy Bird descargar¿Quieres descargar pájaros Flappy gratis? ¿Descarga directa, no hay encuestas?Asegúrese de echar un vistazo a la revisión del video sobre para la historia completa sobre descargar Flappy pájaro l
Divertido juego con arduino y procesamiento

Divertido juego con arduino y procesamiento

Este tutorial le mostrará cómo hacer una primera persona FPS-shooter en el proceso con la ayuda de un arduino. Este proyecto nos fue entregado como un examen final en un curso de especialización técnica, (Bachillerato).Video del proyecto! :) (Difícil
Cómo escribir un programa de Tic-Tac-Toe en Java

Cómo escribir un programa de Tic-Tac-Toe en Java

Introducción:Tres en raya es un juego muy común que es bastante fácil de jugar. Las reglas del juego son simples y bien conocidos. Debido a estas cosas, Tic-Tac-Toe es bastante fácil de código de arriba. En este tutorial, buscará cómo codificar un tr