Hello!
I am a beginner java programmer and a couple of days ago i started programming again(i had kinda like a break for a while). So yesterday when i got bored i just started making a random game. It is supposed to be a square that moves to random locations but i *ed up somewhere. The square wont move and im not sure if it is because the updating of the screen if weird or just my other code. Im really new to making games and i have just started learning so the code will be bad. If there is any like really weird code in there it might be because i changed and tried alot of things when trying to fix it. So have i just made a small mistake or is it a big failure that i should delete and work on when i get better? This is just a thing i started making when i was bored so I dont really care about it and its mostly a test. Here is the code:
First class:
And second class:import javax.swing.*; import java.awt.*; public class Main extends JFrame{ Image dbImage; Graphics dbg; AI bot; public Main(){ bot = new AI(); setVisible(true); setSize(500,500); setResizable(false); setDefaultCloseOperation(3); setLocation(500,250); } public void draw(Graphics g){ g.setColor(Color.GRAY); g.fillRect(0,0,500,500); bot.draw(g); } public void paint(Graphics g){ dbImage = createImage(getWidth(),getHeight()); dbg = dbImage.getGraphics(); draw(dbg); g.drawImage(dbImage,0,0,this); } public static void main(String[] args) { new Main(); } }
Also tell me if i should do something wrong!(Remember im really new to making games)import java.awt.*; import java.util.Random; public class AI implements Runnable{ Rectangle enemy; int x,y; int randXDir; int randYDir; Random r; Thread t1; public AI(){ r = new Random(); Thread t1 = new Thread(); enemy = new Rectangle(250,250,15,15); x = enemy.x; y = enemy.y; setRandomXDir(); setRandomYDir(); t1.start(); } public void setRandomXDir(){ randXDir = r.nextInt(490); } public void setRandomYDir(){ randYDir = r.nextInt(485); } public void draw(Graphics g){ g.setColor(Color.GREEN); g.fillRect(x, y, enemy.width, enemy.height); } public void setDirection(){ if(x > randXDir){ x -= 1; if(x == randXDir){ setRandomXDir(); setDirection(); } } if(x < randXDir){ x += 1; if(x == randXDir){ setRandomXDir(); setDirection(); } } if(y > randYDir){ y = y - 1; if(y == randYDir){ setRandomXDir(); setDirection(); } } if(y < randYDir){ y = y + 1; if(y == randYDir){ setRandomXDir(); setDirection(); } } } public void move(){ setDirection(); } public void run(){ try{ move(); Thread.sleep(5); }catch(Exception e){System.out.println("error");} } }