Arduino Mkr1000 and Java Swing Shooting Game

Arduino Mkr1000 + Uno + Leonardo + Java = Christmas shooting game.

_7w54RImWLj

Things used in this project

Hardware components

Arduino UNO & Genuino UNO
Arduino UNO & Genuino UNO
× 1
Arduino Leonardo
Arduino Leonardo
× 1
Arduino MKR1000
Arduino MKR1000
× 1
3.7V battery
× 1
HC-06 Bluetooth Module
HC-06 Bluetooth Module
× 2
Arcade Button
× 1
joystick
× 1

Story

 

How it does work

First, I’ll talk about Computer(java)-to-board connection relationship: I wrote some Java code that can communicate with Arduino. Mkr1000 and Java are connected directly using inner IP. If we move joystick, Mkr1000 send joystick’s movement to the Java.

Uno and Leonardo are connected by Bluetooth(HC-06). If we push shooting Arcade Button. The fact that we push it is sent to Leonardo. And Leonardo receive it and press space bar using Keyboard library.

And then, Java notice that space bar was pressed and shoot! That’s All!

_MgxXDQlEC7

Photo

kakaotalk_20170116_155550132_d07tUika6C

kakaotalk_20170116_155553725_1H1FihLAU5

Schematics

Code

mkr1000 code

Arduino

#include <SPI.h>
#include <WiFi101.h>

char ssid[] = "iptime"; //  your network SSID (name)

int xpos;
int ypos;
int status = WL_IDLE_STATUS;

WiFiServer server(80);
WiFiClient client;

void setup() {
  //Initialize serial and wait for port to open:

  pinMode(A1,INPUT);
  pinMode(A2,INPUT);
  WiFi.lowPowerMode();
  // attempt to connect to Wifi network:
  while ( status != WL_CONNECTED) {
    status = WiFi.begin(ssid);

    // wait 10 seconds for connection:
    delay(10000);
  }
  
  // start the server:
  server.begin();
 
}

void loop() {
  client = server.available();
  while(client.connected()) {
      xpos = analogRead(A2);
      ypos = analogRead(A1);
      if(xpos>900)
        client.println("R");
      else  if(xpos<150)
        client.println("L");
       if(ypos<150)
        client.println("F");
       else  if(ypos>900)
        client.println("B");
  }
}

arduino uno

Arduino

#include <SoftwareSerial.h>

SoftwareSerial mySerial(10, 11); // RX, TX

void setup() {
  pinMode(7,INPUT_PULLUP);
  mySerial.begin(9600);
}

void loop() { // run over and over
  if(digitalRead(7)==0)
    mySerial.print("a");
    delay(300);
}
public class NetWork {
		private Socket socket;
		InputStream in;
		public NetWork(){
			try {
				socket = new Socket("mkr1000's inner Ip",mkr1000's inner port);
				in = socket.getInputStream();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		private char getText(){
			try {
				if(in.available()>0)
					return (char) in.read();//read direction
			} catch (IOException e) {
				//ignore
			}
			return 'N';//no move
		}
(package name: sounds)
import java.io.File;


import javax.sound.sampled.AudioSystem;

import javax.sound.sampled.Clip;


public class MusicPlayer implements Runnable{

	public Clip clip;
	private	File file;
	
	public MusicPlayer(String musicFileName){
		file=new File(musicFileName);
		
	}
	public MusicPlayer(File musicFile){
		file=musicFile;
	}
	@Override
	@Deprecated
	public void run() {
		try{

			clip = AudioSystem.getClip();

			clip.open(AudioSystem.getAudioInputStream(file));
			clip.loop(Clip.LOOP_CONTINUOUSLY);
			clip.start();
			
			
			Thread.sleep(clip.getMicrosecondLength()/1000);

		}

		catch(Exception e){
			e.printStackTrace();
		}

		
	}
	public void Pause(){
		clip.stop();
	}
	public void Stop(){
		clip.stop();
		clip.close();
	}
	public void ReStart(){
		clip.start();
	}
	public void Start(){
		new Thread(this).start();
	}
	public void StartAtFirst(){
		try {
			clip.close();
			clip=AudioSystem.getClip();
			clip.open(AudioSystem.getAudioInputStream(file));
			Start();
		} catch (Exception e) {
			// TODO 자동 생성된 catch 블록
			e.printStackTrace();
		} 
	}

}
if you want to use my code, change ip
package : MM
package MM;


import java.io.IOException;
import java.io.InputStream;

import java.net.Socket;

import java.net.UnknownHostException;

public class NetWork {
		private Socket socket;
		InputStream in;
		public NetWork(){
			try {
				socket = new Socket("192.168.0.2",80);
				in = socket.getInputStream();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
		}
		private char getText(){
			try {
				if(in.available()>0)
					return (char) in.read();
			} catch (IOException e) {
				//ignore
			}
			return 'N';
		}
		public Reaction getReaction() {
			char result = getText();
			switch(result){
			case 'R': return Reaction.Right;
			case 'B': return Reaction.Behind;
			case 'F': return Reaction.Front;
			case 'L': return Reaction.Left;
			}
			return Reaction.NM;
		}
		public void dispose(){
			try {
				socket.close();
				in.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
}
it is main start code.
package shoot
package shoot;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Collections;
import java.util.Iterator;
import java.util.Random;
import sounds.MusicPlayer;
import javax.swing.*;

import MM.NetWork;
public class Fight extends JPanel implements KeyListener , ActionListener,Runnable{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1313313143231311254L;
	public static boolean isChange = false;
	public static int Level=1;
	public static MusicPlayer music = new MusicPlayer("JingleBell.wav");
	static int jumsu;
	public static JFrame frame=new JFrame("MyGame");
	public static int mocsom=5;
	public static final int WEIGHT = (int) Toolkit.getDefaultToolkit().getScreenSize().getWidth();
	public static final int HEIGHT=(int) Toolkit.getDefaultToolkit().getScreenSize().getHeight();
	private static java.util.List<Point> bulletsPos = new java.util.ArrayList<>();
	private Image playerImage = Toolkit.getDefaultToolkit().createImage("Christmas.gif");
	private static Image enemyImage = Toolkit.getDefaultToolkit().createImage("happyXmas.jpg");
	private Point playerCurPos =new Point(WEIGHT/2-playerImage.getWidth(this)/2,HEIGHT/2-playerImage.getHeight(this)/2);
	private static java.util.List<Point> enemyPos = new java.util.ArrayList<>();
	public static JLabel poinLabel=new JLabel();
	public static Image backGround = Toolkit.getDefaultToolkit().createImage("background.jpg");
	public static int enemyh=-1;
	public static int enemyw=-1;
	static NetWork net;
	long current;
	int ewh;
	Image robot = Toolkit.getDefaultToolkit().createImage("robot.png");
	public Fight(){
		current = System.currentTimeMillis();

		setPreferredSize(new Dimension(WEIGHT,HEIGHT));
		setFocusable(true);
		addKeyListener(this);
		new Timer(300,this).start();
		poinLabel.setText("Point :"+jumsu+",  SkillLevel : "+Level);
		poinLabel.setPreferredSize(new Dimension(1000,100));
		poinLabel.setFont(new Font("궁서",Font.ITALIC, 30));
		add(poinLabel);
		bulletsPos=Collections.synchronizedList(bulletsPos);
		enemyPos=Collections.synchronizedList(enemyPos); 
		net = new NetWork();
		while(enemyh==-1)
			enemyh = enemyImage.getHeight(this);
		while(enemyw==-1)
			enemyw = enemyImage.getWidth(this);
		ewh = enemyw/2;
	}
	public void  paintComponent(Graphics g){
		Graphics2D g2d=(Graphics2D)g;
		g2d.drawImage(backGround, 0, 0, getWidth(), getHeight(), this);
		g2d.drawImage(playerImage, playerCurPos.x, playerCurPos.y, this);
		g2d.setColor(Color.green);
		
		
		synchronized (bulletsPos) {
			
		
		for(Point p :bulletsPos){
			synchronized (p) {
				
			
			g2d.setColor(Window.getRandomColor());	
			g2d.fillOval(p.x+ewh,p.y-15,10,30);
			}
		}
		
			
		
		}
			
		
		synchronized (enemyPos) {
			
		
		try{
		for(Point p:enemyPos){
			
			synchronized (p) {
				
			
			g2d.drawImage(enemyImage,p.x,p.y, this);
			}
		}
		}catch(Exception e){
			
		}
		
		}
		
		g2d.setColor(Color.orange);
		for(int i = 1;i<=mocsom;i++){
			g2d.fillOval(10+i*50, 10, 50, 50);
		}
		g2d.setColor(Color.pink);
		
		poinLabel.setText("Point :"+jumsu+",  SkillLevel : "
				+ ""+Level);
		
		
	}
	public static void main(String[]args) throws Exception{ 
		
		int i = 700;
		Fight f=new Fight();
		new Thread(f).start();
		Thread.sleep(10000);
		frame.setContentPane(f);
		frame.pack();
		frame.addWindowListener(new Window(net));
		frame.setVisible(true);
		f.new brak().start();

		music.Start();
		Random rand = new Random();
		
		while(true){
			try{breaked();}catch(Exception e){}         
			Thread.sleep(i);
				
			synchronized (enemyPos) {
				
			
				enemyPos.add(new Point(rand.nextInt(WEIGHT),rand.nextInt(50)));
			
				Iterator<Point> it = enemyPos.iterator();
				while(it.hasNext()){
					
					Point p=it.next();
					synchronized (p) {
						
					
						p.x+=rand.nextInt(60)-30;
						p.y+=rand.nextInt(60)-10;
						if(p.x<0&&p.y<0||p.y>HEIGHT)
							it.remove();
					}
			}
			
			}
			if(jumsu>=150&&!isChange){
				i=100;
				isChange=true;
			}
			if(isChange){
				Level=3;
			}
		
		}
	}

	@Override
	public void keyTyped(KeyEvent e) {
		// TODO 자동 생성된 메소드 스텁
		
	}
	@Override
	public void keyPressed(KeyEvent e) {
	
		
			if(e.getKeyCode()==KeyEvent.VK_SPACE){
				if(current+300<System.currentTimeMillis()){
				switch(Level){
				default :
				case 3: bulletsPos.add(new Point(playerCurPos.x-ewh+playerImage.getWidth(this),playerCurPos.y));//오른쪽
				case 2: bulletsPos.add(new Point(playerCurPos.x-ewh,playerCurPos.y));//왼쪽
				case 1: bulletsPos.add(new Point(playerCurPos.x-ewh+playerImage.getWidth(this)/2,playerCurPos.y));//가운데
				current = System.currentTimeMillis();
				}
				}
			}	                     
		
		
		repaint();
	}
	@Override
	public void keyReleased(KeyEvent e) {
		// TODO 자동 생성된 메소드 스텁
		
	}
	@Override
	public void actionPerformed(ActionEvent e) {
		
		Iterator<Point> it=bulletsPos.iterator();
		while(it.hasNext()){
			Point p = it.next();
				
				p.y-=40;
			
			if(p.y<0)
				it.remove();
			
		}
		repaint();
			
	}
public static void breaked(){ 

	synchronized (bulletsPos) {
		synchronized (enemyPos) {
			
		
	
			for(Point ep:enemyPos){
				synchronized (ep) {
					
				
			
				for(Point pb:bulletsPos){
					synchronized (pb) {
						
					
					if(Math.abs(pb.x - ep.x) <enemyw && Math.abs(pb.y - ep.y) < enemyh)
					{
							
							
						
								pb.y = -10;
							
							
								
							
								ep.y=HEIGHT;
							
							jumsu++;
							break;
					}
					}
				}//end for pb
				}
			}//end for ep
		}
	}
}
	
	public boolean playerbreaked(){
		breaked();
			
		
			
		synchronized (enemyPos) {
			
		
			for(Point ep:enemyPos){
				synchronized (ep) {
					
				
				if(
						playerCurPos.x-ep.x<enemyw
						&&
						playerCurPos.y-ep.y<enemyh
						&&
						ep.x-playerCurPos.x<playerImage.getWidth(this)
						&&
						ep.y-playerCurPos.y<playerImage.getHeight(this)
				)
				{
						ep.y = HEIGHT;
					
					return true;
				}
				}
			
			}
		}
			
			return false;
		
	}
	
	class brak extends Thread{
		Image tmp;
		public void run(){
			while(true){
				repaint();
				try{
				breaked();
				if(playerbreaked()){
					mocsom--;
					if(mocsom<=0)
					{
						frame.setVisible(false);
						frame.dispose();
						JFrame jf=new JFrame();
						jf.setLayout(new FlowLayout());
						jf.setTitle("GameOver");
						jf.setBounds(WEIGHT/2-150,HEIGHT/2-150    , 100, 100);
						jf.setPreferredSize(new Dimension(300,300));
						jf.pack();
						jf.add(new JLabel("Happy Christmas!"));
						JLabel jl = new JLabel(new ImageIcon("Christmas.gif"));
						jf.add(jl);
						jf.setVisible(true);
						jf.addWindowListener(new Window(net));
						music.Pause();
						break;
					}
					Thread.yield();
					tmp = playerImage;
					playerImage = robot;
					Thread.sleep(3000); 
					playerImage=tmp;                   

				}
				}
				catch(Exception e){}
			}
		}
	}


@Override
public void run() {
	while(true){
		
		switch(net.getReaction()){
		case Behind:
			playerCurPos.y+=3;
			break;
		case Front:
			playerCurPos.y-=3;
			break;
		case Left:
			playerCurPos.x-=3;
			break;
		case NM:
			break;
		case Right:
			playerCurPos.x+=3;
			break;
		}
		repaint();
	}
}




}
package shoot

it choose bullets color and define windowClosing

package shoot;

import java.awt.Color;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

import MM.NetWork;
import java.util.*;
public class Window extends WindowAdapter{
	private static int g = 0;
	private static int b = 50;
	NetWork net;
	public Window(NetWork net){
		this.net = net;
	}
	@Override
	public void windowClosing(WindowEvent e){
		e.getWindow().dispose();
		net.dispose();
		System.exit(0);
	}
	public static Color getRandomColor(){
		if(!Fight.isChange)
			return new Color(255,++g%256,b);
		else
			return new Color(255,++g%256,++b%120);
	}
	
}

leonardo

Arduino

#include<Keyboard.h>
void setup() {

  Serial1.begin(9600);
  Keyboard.begin();
}

void loop() { // run over and over
  if (Serial1.available()) {
    if(Serial1.read()=='a')
      Keyboard.print(" ");
  }

}
package MM
package MM;

public enum Reaction {
	Right,Left,Front,Behind,NM
	
}

About The Author

Ibrar Ayyub

I am an experienced technical writer holding a Master's degree in computer science from BZU Multan, Pakistan University. With a background spanning various industries, particularly in home automation and engineering, I have honed my skills in crafting clear and concise content. Proficient in leveraging infographics and diagrams, I strive to simplify complex concepts for readers. My strength lies in thorough research and presenting information in a structured and logical format.

Follow Us:
LinkedinTwitter

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top