Hackster is hosting Hackster Holidays, Ep. 7: Livestream & Giveaway Drawing. Watch previous episodes or stream live on Friday!Stream Hackster Holidays, Ep. 7 on Friday!
pc1436
Published © GPL3+

Arduino Mkr1000 and Java Swing Shooting Game

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

BeginnerFull instructions provided1 hour2,473

Things used in this project

Story

Read more

Schematics

all 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);
}

java code(Connect to mkr1000

Java
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
		}

musicPlayer.java

Java
(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();
		} 
	}

}

NetWork.java

Java
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();
			}
		}
}

Fight.java

Java
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();
	}
}




}

Window.java

Java
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(" ");
  }

}

Reaction.java

Java
package MM
package MM;

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

Credits

pc1436
1 project • 2 followers
I am handsome man who loves arduino and so on.( Also I love you)

Comments