Commit 3df333c1 authored by 9731301's avatar 9731301

add networkPlaying

parent b9d28866
<component name="ArtifactManager">
<artifact type="jar" name="JTankTrouble:jar">
<output-path>$PROJECT_DIR$/out/artifacts/JTankTrouble_jar</output-path>
<root id="archive" name="JTankTrouble.jar">
<element id="module-output" name="JTankTrouble" />
</root>
</artifact>
</component>
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<project version="4"> <project version="4">
<component name="ArtifactsWorkspaceSettings">
<artifacts-to-build>
<artifact name="JTankTrouble:jar" />
</artifacts-to-build>
</component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="0b3d586d-9f0f-4ca4-b09d-03a200e1e684" name="Default Changelist" comment=""> <list default="true" id="0b3d586d-9f0f-4ca4-b09d-03a200e1e684" name="Default Changelist" comment="">
<change afterPath="$PROJECT_DIR$/.idea/artifacts/JTankTrouble_jar.xml" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/Server_Client/NetWorkGame/Client1.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/UI/LogIn/NetWorkGame/NWGFrame.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/UI/LogIn/NetWorkGame/NWGLoop.java" afterDir="false" />
<change afterPath="$PROJECT_DIR$/src/UI/LogIn/NetWorkGame/NWGRendering.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/out/production/JTankTrouble/UI/GameState/BulletState$KeyHandler2.class" beforeDir="false" afterPath="$PROJECT_DIR$/out/production/JTankTrouble/UI/GameState/BulletState$KeyHandler2.class" afterDir="false" /> <change beforePath="$PROJECT_DIR$/out/production/JTankTrouble/UI/LogIn/MainPanel$1.class" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/out/production/JTankTrouble/UI/GameState/BulletState.class" beforeDir="false" afterPath="$PROJECT_DIR$/out/production/JTankTrouble/UI/GameState/BulletState.class" afterDir="false" /> <change beforePath="$PROJECT_DIR$/out/production/JTankTrouble/UI/LogIn/MainPanel$2.class" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/out/production/JTankTrouble/UI/GameState/RewardState.class" beforeDir="false" afterPath="$PROJECT_DIR$/out/production/JTankTrouble/UI/GameState/RewardState.class" afterDir="false" /> <change beforePath="$PROJECT_DIR$/out/production/JTankTrouble/UI/LogIn/MainPanel$3.class" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/out/production/JTankTrouble/UI/GameState/TankState.class" beforeDir="false" afterPath="$PROJECT_DIR$/out/production/JTankTrouble/UI/GameState/TankState.class" afterDir="false" /> <change beforePath="$PROJECT_DIR$/out/production/JTankTrouble/UI/LogIn/MainPanel.class" beforeDir="false" />
<change beforePath="$PROJECT_DIR$/out/production/JTankTrouble/UI/LogIn/Game/Rendering.class" beforeDir="false" afterPath="$PROJECT_DIR$/out/production/JTankTrouble/UI/LogIn/Game/Rendering.class" afterDir="false" /> <change beforePath="$PROJECT_DIR$/src/UI/LogIn/MainPanel.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/UI/LogIn/MainPanel.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/out/production/JTankTrouble/UI/LogIn/Setting.class" beforeDir="false" afterPath="$PROJECT_DIR$/out/production/JTankTrouble/UI/LogIn/Setting.class" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/UI/GameState/BulletState.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/UI/GameState/BulletState.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/UI/GameState/RewardState.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/UI/GameState/RewardState.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/UI/GameState/TankState.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/UI/GameState/TankState.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/UI/LogIn/Game/Rendering.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/UI/LogIn/Game/Rendering.java" afterDir="false" />
<change beforePath="$PROJECT_DIR$/src/UI/LogIn/Setting.java" beforeDir="false" afterPath="$PROJECT_DIR$/src/UI/LogIn/Setting.java" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
...@@ -56,6 +60,11 @@ ...@@ -56,6 +60,11 @@
<property name="SHARE_PROJECT_CONFIGURATION_FILES" value="true" /> <property name="SHARE_PROJECT_CONFIGURATION_FILES" value="true" />
<property name="WebServerToolWindowFactoryState" value="false" /> <property name="WebServerToolWindowFactoryState" value="false" />
<property name="aspect.path.notification.shown" value="true" /> <property name="aspect.path.notification.shown" value="true" />
<property name="last_opened_file_path" value="$PROJECT_DIR$" />
<property name="project.structure.last.edited" value="Artifacts" />
<property name="project.structure.proportion" value="0.15" />
<property name="project.structure.side.proportion" value="0.2" />
<property name="settings.editor.selected.configurable" value="preferences.lookFeel" />
</component> </component>
<component name="RecentsManager"> <component name="RecentsManager">
<key name="ExtractSuperBase.RECENT_KEYS"> <key name="ExtractSuperBase.RECENT_KEYS">
...@@ -144,7 +153,9 @@ ...@@ -144,7 +153,9 @@
<workItem from="1596467735244" duration="13219000" /> <workItem from="1596467735244" duration="13219000" />
<workItem from="1596534338281" duration="1337000" /> <workItem from="1596534338281" duration="1337000" />
<workItem from="1596541467681" duration="2210000" /> <workItem from="1596541467681" duration="2210000" />
<workItem from="1596559015419" duration="4574000" /> <workItem from="1596559015419" duration="8215000" />
<workItem from="1596589736833" duration="13294000" />
<workItem from="1596613090214" duration="8123000" />
</task> </task>
<servers /> <servers />
</component> </component>
...@@ -156,10 +167,14 @@ ...@@ -156,10 +167,14 @@
<screen x="0" y="0" width="1536" height="824" /> <screen x="0" y="0" width="1536" height="824" />
</state> </state>
<state x="517" y="216" key="#com.intellij.fileTypes.FileTypeChooser/0.0.1536.824@0.0.1536.824" timestamp="1596402386433" /> <state x="517" y="216" key="#com.intellij.fileTypes.FileTypeChooser/0.0.1536.824@0.0.1536.824" timestamp="1596402386433" />
<state x="574" y="122" key="#com.intellij.ide.util.MemberChooser" timestamp="1596561526763"> <state x="574" y="122" key="#com.intellij.ide.util.MemberChooser" timestamp="1596620195172">
<screen x="0" y="0" width="1536" height="824" />
</state>
<state x="574" y="122" key="#com.intellij.ide.util.MemberChooser/0.0.1536.824@0.0.1536.824" timestamp="1596620195172" />
<state x="499" y="197" key="#com.intellij.ide.util.TreeClassChooserDialog" timestamp="1596591250036">
<screen x="0" y="0" width="1536" height="824" /> <screen x="0" y="0" width="1536" height="824" />
</state> </state>
<state x="574" y="122" key="#com.intellij.ide.util.MemberChooser/0.0.1536.824@0.0.1536.824" timestamp="1596561526763" /> <state x="499" y="197" key="#com.intellij.ide.util.TreeClassChooserDialog/0.0.1536.824@0.0.1536.824" timestamp="1596591250036" />
<state x="566" y="298" width="403" height="237" key="#com.intellij.refactoring.move.moveClassesOrPackages.MoveClassesOrPackagesDialog.classes" timestamp="1596368712645"> <state x="566" y="298" width="403" height="237" key="#com.intellij.refactoring.move.moveClassesOrPackages.MoveClassesOrPackagesDialog.classes" timestamp="1596368712645">
<screen x="0" y="0" width="1536" height="824" /> <screen x="0" y="0" width="1536" height="824" />
</state> </state>
...@@ -172,26 +187,34 @@ ...@@ -172,26 +187,34 @@
<screen x="0" y="0" width="1536" height="824" /> <screen x="0" y="0" width="1536" height="824" />
</state> </state>
<state x="593" y="0" key="CommitChangelistDialog2/0.0.1536.824@0.0.1536.824" timestamp="1595639194593" /> <state x="593" y="0" key="CommitChangelistDialog2/0.0.1536.824@0.0.1536.824" timestamp="1595639194593" />
<state width="1493" height="125" key="GridCell.Tab.0.bottom" timestamp="1596563065245"> <state x="549" y="153" key="FileChooserDialogImpl" timestamp="1596567968810">
<screen x="0" y="0" width="1536" height="824" /> <screen x="0" y="0" width="1536" height="824" />
</state> </state>
<state width="1493" height="125" key="GridCell.Tab.0.bottom/0.0.1536.824@0.0.1536.824" timestamp="1596563065245" /> <state x="549" y="153" key="FileChooserDialogImpl/0.0.1536.824@0.0.1536.824" timestamp="1596567968810" />
<state width="1493" height="125" key="GridCell.Tab.0.center" timestamp="1596563065245"> <state width="1493" height="145" key="GridCell.Tab.0.bottom" timestamp="1596610909897">
<screen x="0" y="0" width="1536" height="824" /> <screen x="0" y="0" width="1536" height="824" />
</state> </state>
<state width="1493" height="125" key="GridCell.Tab.0.center/0.0.1536.824@0.0.1536.824" timestamp="1596563065245" /> <state width="1493" height="145" key="GridCell.Tab.0.bottom/0.0.1536.824@0.0.1536.824" timestamp="1596610909897" />
<state width="1493" height="125" key="GridCell.Tab.0.left" timestamp="1596563065245"> <state width="1493" height="145" key="GridCell.Tab.0.center" timestamp="1596610909897">
<screen x="0" y="0" width="1536" height="824" /> <screen x="0" y="0" width="1536" height="824" />
</state> </state>
<state width="1493" height="125" key="GridCell.Tab.0.left/0.0.1536.824@0.0.1536.824" timestamp="1596563065245" /> <state width="1493" height="145" key="GridCell.Tab.0.center/0.0.1536.824@0.0.1536.824" timestamp="1596610909897" />
<state width="1493" height="125" key="GridCell.Tab.0.right" timestamp="1596563065245"> <state width="1493" height="145" key="GridCell.Tab.0.left" timestamp="1596610909896">
<screen x="0" y="0" width="1536" height="824" /> <screen x="0" y="0" width="1536" height="824" />
</state> </state>
<state width="1493" height="125" key="GridCell.Tab.0.right/0.0.1536.824@0.0.1536.824" timestamp="1596563065245" /> <state width="1493" height="145" key="GridCell.Tab.0.left/0.0.1536.824@0.0.1536.824" timestamp="1596610909896" />
<state width="1493" height="145" key="GridCell.Tab.0.right" timestamp="1596610909897">
<screen x="0" y="0" width="1536" height="824" />
</state>
<state width="1493" height="145" key="GridCell.Tab.0.right/0.0.1536.824@0.0.1536.824" timestamp="1596610909897" />
<state x="589" y="114" key="RollbackChangesDialog" timestamp="1595702094731"> <state x="589" y="114" key="RollbackChangesDialog" timestamp="1595702094731">
<screen x="0" y="0" width="1536" height="824" /> <screen x="0" y="0" width="1536" height="824" />
</state> </state>
<state x="589" y="114" key="RollbackChangesDialog/0.0.1536.824@0.0.1536.824" timestamp="1595702094731" /> <state x="589" y="114" key="RollbackChangesDialog/0.0.1536.824@0.0.1536.824" timestamp="1595702094731" />
<state x="249" y="0" key="SettingsEditor" timestamp="1596591266758">
<screen x="0" y="0" width="1536" height="824" />
</state>
<state x="249" y="0" key="SettingsEditor/0.0.1536.824@0.0.1536.824" timestamp="1596591266758" />
<state x="107" y="201" key="com.intellij.ide.util.TipDialog" timestamp="1596559084807"> <state x="107" y="201" key="com.intellij.ide.util.TipDialog" timestamp="1596559084807">
<screen x="0" y="0" width="1536" height="824" /> <screen x="0" y="0" width="1536" height="824" />
</state> </state>
...@@ -208,10 +231,10 @@ ...@@ -208,10 +231,10 @@
<screen x="0" y="0" width="1536" height="824" /> <screen x="0" y="0" width="1536" height="824" />
</state> </state>
<state x="209" y="33" key="new project wizard/0.0.1536.824@0.0.1536.824" timestamp="1596559227093" /> <state x="209" y="33" key="new project wizard/0.0.1536.824@0.0.1536.824" timestamp="1596559227093" />
<state x="511" y="41" key="refactoring.ChangeSignatureDialog" timestamp="1596369964902"> <state x="511" y="41" key="refactoring.ChangeSignatureDialog" timestamp="1596620038689">
<screen x="0" y="0" width="1536" height="824" /> <screen x="0" y="0" width="1536" height="824" />
</state> </state>
<state x="511" y="41" key="refactoring.ChangeSignatureDialog/0.0.1536.824@0.0.1536.824" timestamp="1596369964902" /> <state x="511" y="41" key="refactoring.ChangeSignatureDialog/0.0.1536.824@0.0.1536.824" timestamp="1596620038689" />
<state x="426" y="187" key="run.anything.popup" timestamp="1596369494104"> <state x="426" y="187" key="run.anything.popup" timestamp="1596369494104">
<screen x="0" y="0" width="1536" height="824" /> <screen x="0" y="0" width="1536" height="824" />
</state> </state>
......
Manifest-Version: 1.0
Main-Class: UI.LogIn.Main
Manifest-Version: 1.0
Main-Class: UI.LogIn.Main
package Server_Client.NetWorkGame;
import UI.GameState.BulletState;
import UI.GameState.EnemyTank;
import UI.GameState.TankState;
import UI.GameState.WallState;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
public class Client1 {
private Socket socket = null;
private String host;
private int port;
private int enemyX;
private int enemyY;
private int enemyRotate;
private int enemyBulletX;
private int enemyBulletY;
private boolean enemyHasLaser;
private boolean enemyHasShield;
private boolean enemyHasMoreLife;
private WallState wallState;
private ArrayList<EnemyTank> enemyTanks;
private ArrayList<BulletState> eachTankBullets;
private String serverAns;
public Client1(String address , int port) {
this.host = address;
this.port = port;
}
private String tankStateToString (TankState tank) throws IOException {
String tankComponent , bulletComponent = "";
tankComponent = tank.locX +" "+ tank.locY+" " +tank.rotate +" "+tank.hasShield() +" "+tank.hasLaser() +" "+tank.isHasMoreLife();
for (BulletState bullet : tank.getBullets()){
bulletComponent +=" " + bullet.locX + " " + bullet.locY + " " ;
}
return tankComponent + bulletComponent;
}
public void run(TankState tankState) {
try{
socket = new Socket(host,port);
OutputStream out = socket.getOutputStream();
InputStream in = socket.getInputStream();
out.write("Client1".getBytes());
String text = "";
boolean running = true;
do {
//ToDo update the tank and enemy tank x , y , ...
text = tankStateToString(tankState);
running = !text.equalsIgnoreCase("over");
out.write(text.getBytes());
byte[] buffer = new byte[2048];
int read = in.read(buffer);
serverAns = new String(buffer,0,read);
System.out.println("- From Server : "+serverAns);
}while(running);
System.out.println("Client disconnected.");
socket.close();
}catch (IOException e){
System.out.println("Error : "+e.getMessage());
e.printStackTrace();
}
}
private ArrayList<EnemyTank> createEnemyTanks(String s){
ArrayList<EnemyTank> enemyTanks = new ArrayList<>();
int numOfEnemies = findNumOfEnemies(s);
for (int i = 0 ; i < numOfEnemies ; i ++){
EnemyTank enemyTank = new EnemyTank(wallState);
enemyTanks.add(enemyTank);
}
return enemyTanks;
}
//ToDo
private int findNumOfEnemies(String s){
}
private void parser(){//ToDO separate tanks and each tank bullets
}
public void updateEnemyComponents(){
for (EnemyTank enemyTank : enemyTanks){
enemyTank.locX = enemyX;
enemyTank.locY = enemyY;
enemyTank.rotate =enemyRotate;
enemyTank.setHasShield(enemyHasShield);
enemyTank.setHasLaser(enemyHasLaser);
enemyTank.setHasMoreLife(enemyHasMoreLife);
for (BulletState bullet : enemyTank.getBullets()){
bullet.locX = enemyBulletX;
bullet.locY = enemyBulletY;
}
}
}
public ArrayList<EnemyTank> getEnemyTanks() {
return enemyTanks = createEnemyTanks(serverAns);
}
public WallState getWallState() {
return wallState;
}
}
package UI.LogIn; package UI.LogIn;
import Server_Client.NetWorkGame.Client1;
import UI.LogIn.Game.GameFrame; import UI.LogIn.Game.GameFrame;
import UI.LogIn.Game.GameLoop; import UI.LogIn.Game.GameLoop;
import UI.LogIn.Game.ThreadPool; import UI.LogIn.Game.ThreadPool;
import UI.LogIn.NetWorkGame.NWGFrame;
import UI.LogIn.NetWorkGame.NWGLoop;
import javax.imageio.ImageIO; import javax.imageio.ImageIO;
import javax.swing.*; import javax.swing.*;
...@@ -11,6 +14,8 @@ import java.awt.event.MouseAdapter; ...@@ -11,6 +14,8 @@ import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent; import java.awt.event.MouseEvent;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class MainPanel extends JPanel { public class MainPanel extends JPanel {
...@@ -48,6 +53,20 @@ public class MainPanel extends JPanel { ...@@ -48,6 +53,20 @@ public class MainPanel extends JPanel {
} }
}); });
multiPlaysBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);
Client1 client1 = null;
try {
client1 = new Client1(InetAddress.getLocalHost().getHostName(),5000);
run2(client1);
} catch (UnknownHostException ex) {
ex.printStackTrace();
}
}
});
settingBtn.addMouseListener(new MouseAdapter() { settingBtn.addMouseListener(new MouseAdapter() {
@Override @Override
public void mouseClicked(MouseEvent e) { public void mouseClicked(MouseEvent e) {
...@@ -90,4 +109,24 @@ public class MainPanel extends JPanel { ...@@ -90,4 +109,24 @@ public class MainPanel extends JPanel {
} }
}); });
} }
private void run2(Client1 client1) {
// Initialize the global thread-pool
ThreadPool.init();
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
NWGFrame frame = new NWGFrame("Trouble Tank");
frame.setLocationRelativeTo(null); // put frame at center of screen
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.setVisible(true);
frame.initBufferStrategy();
// Create and execute the game-loop
NWGLoop game = new NWGLoop(frame , client1);
game.init();
ThreadPool.execute(game);
// and the game starts ...
}
});
}
} }
package UI.LogIn.NetWorkGame;
import UI.GameState.EnemyTank;
import UI.GameState.MyTank;
import UI.GameState.WallState;
import UI.LogIn.Game.Rendering;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferStrategy;
import java.io.IOException;
import java.util.ArrayList;
public class NWGFrame extends JFrame {
private long lastRender;
private BufferStrategy bufferStrategy;
private NWGRendering rendering = new NWGRendering();
public static final int GAME_HEIGHT = 720; // 720p game resolution
public static final int GAME_WIDTH = 16 * GAME_HEIGHT / 9; // wide aspect ratio
public WallState wallState = new WallState(GAME_WIDTH, GAME_HEIGHT);
public NWGFrame(String gameName) {
lastRender = -1;
setTitle(gameName);
pack();
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(GAME_WIDTH, GAME_HEIGHT);
setResizable(false);
}
/**
* This must be called once after the JFrame is shown:
* frame.setVisible(true);
* and before any rendering is started.
*/
public void initBufferStrategy() {
// Triple-buffering
createBufferStrategy(3);
bufferStrategy = getBufferStrategy();
}
/**
* Game rendering with triple-buffering using BufferStrategy.
*/
public void render(MyTank myTank, ArrayList<EnemyTank> enemyTanks , WallState wallState) {
do {
do {
Graphics2D graphics = (Graphics2D) bufferStrategy.getDrawGraphics();
try {
rendering.doRendering(graphics, myTank, enemyTanks , wallState );
} catch (IOException e) {
e.printStackTrace();
} finally {
// Dispose the graphics
graphics.dispose();
}
// Repeat the rendering if the drawing buffer contents were restored
} while (bufferStrategy.contentsRestored());
// Display the buffer
bufferStrategy.show();
// Tell the system to do the drawing NOW;
// otherwise it can take a few extra ms and will feel jerky!
Toolkit.getDefaultToolkit().sync();
// Repeat the rendering if the drawing buffer was lost
} while (bufferStrategy.contentsLost());
}
}
package UI.LogIn.NetWorkGame;
import Server_Client.NetWorkGame.Client1;
import UI.GameState.EnemyTank;
import UI.GameState.MyTank;
import UI.LogIn.Game.GameFrame;
import java.util.ArrayList;
/*** In The Name of Allah ***/
/**
* A very simple structure for the main game loop.
* THIS IS NOT PERFECT, but works for most situations.
* Note that to make this work, none of the 2 methods
* in the while loop (update() and render()) should be
* long running! Both must execute very quickly, without
* any waiting and blocking!
*
* Detailed discussion on different game loop design
* patterns is available in the following link:
* http://gameprogrammingpatterns.com/game-loop.html
*
* @author Seyede zahra seyed fatehi
*/
public class NWGLoop implements Runnable {
/**
* Frame Per Second.
* Higher is better, but any value above 24 is fine.
*/
public static final int FPS = 30;
private NWGFrame canvas;
private MyTank myTank;
private ArrayList<EnemyTank> enemyTanks;
private Client1 client1;
public NWGLoop(NWGFrame frame , Client1 client1) {
canvas = frame;
this.client1 = client1;
}
public static long startTime;
/**
* This must be called before the game loop starts.
*/
public void init() {
// Perform all initializations ...
myTank = new MyTank(canvas.wallState);
client1.run(myTank);
enemyTanks = client1.getEnemyTanks();
canvas.addKeyListener(myTank.getMyListener());
canvas.addMouseListener(myTank.getMouseListener());
canvas.addMouseMotionListener(myTank.getMouseMotionListener());
startTime = 0;
}
@Override
public void run() {
boolean gameOver = false;
while (!gameOver) {
try {
long start = System.currentTimeMillis();
myTank.update();
client1.updateEnemyComponents();
canvas.render(myTank , enemyTanks , client1.getWallState());
long delay = (1000 / FPS) - (System.currentTimeMillis() - start);
if (delay > 0)
Thread.sleep(delay);
} catch (InterruptedException ex) {
}
}
}
}
package UI.LogIn.NetWorkGame;
import Server_Client.NetWorkGame.Client1;
import UI.GameState.*;
import UI.LogIn.Game.GameLoop;
import UI.LogIn.Setting;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class NWGRendering {
private Image image1;
private Image image2;
private Image explosionImg;
public static final int GAME_HEIGHT = 720; // 720p game resolution
public static final int GAME_WIDTH = 16 * GAME_HEIGHT / 9; // wide aspect ratio
int lastRender = -1;
private ArrayList<Float> fpsHistory;
private ArrayList<RewardState> rewards = new ArrayList<>();
private Setting setting = new Setting();
public NWGRendering() {
fpsHistory = new ArrayList<>(100);
}
/**
* Rendering all game elements based on the game state.
*/
// Draw all game elements according
// to the game 'state' using 'g2d' ...
public void doRendering(Graphics2D g2d, MyTank myTank, ArrayList<EnemyTank> enemyTanks , WallState wallState) throws IOException {
// Draw background
wallState.paintComponent(g2d);
// Draw my tank;
try {
image1 = ImageIO.read(new File(setting.getTankShapePath()));
} catch (IOException e) {
System.out.println(e);
}
// Rotation information
double rotationRequired = Math.toRadians(myTank.rotate);
BufferedImage image11 = (BufferedImage) image1;
double locationX = image11.getWidth() / 2;
double locationY = image11.getHeight() / 2;
AffineTransform tx = AffineTransform.getRotateInstance(rotationRequired, locationX, locationY);
AffineTransformOp op = new AffineTransformOp(tx, AffineTransformOp.TYPE_BILINEAR);
// Drawing the rotated image at the required drawing locations
for (EnemyTank enemyTank : enemyTanks) {
int lastX1 = 0;
int lastY1 = 0;
if (!myTank.gameOver && !enemyTank.gameOver) {
g2d.drawImage(op.filter(image11, null), myTank.locX, myTank.locY, null);
lastX1 = enemyTank.locX;
lastY1 = enemyTank.locY;
} else
g2d.drawImage(op.filter(image11, null), lastX1, lastY1, null);
//Draw enemies tanks
try {
image2 = ImageIO.read(new File("C:\\Users\\Lenovo\\IdeaProjects\\JTankTrouble\\pics\\tank_dark.png"));
} catch (IOException e) {
e.printStackTrace();
}
// Rotation information
double rotationEnemy = Math.toRadians(enemyTank.rotate);
BufferedImage image22 = (BufferedImage) image2;
double locationX2 = image22.getWidth() / 2;
double locationY2 = image22.getHeight() / 2;
AffineTransform tx2 = AffineTransform.getRotateInstance(rotationEnemy, locationX2, locationY2);
AffineTransformOp op2 = new AffineTransformOp(tx2, AffineTransformOp.TYPE_BILINEAR);
// Drawing the rotated image at the required drawing locations
int lastX2 = 0;
int lastY2 = 0;
if (!myTank.gameOver && !enemyTank.gameOver) {
g2d.drawImage(op2.filter(image22, null), enemyTank.locX, enemyTank.locY, null);
lastX2 = enemyTank.locX;
lastY2 = enemyTank.locY;
} else
g2d.drawImage(op2.filter(image22, null), lastX2, lastY2, null);
}
//Draw myTank bullet
if (myTank.getBullets().size() != 0 && !myTank.gameOver) {
Iterator<BulletState> it = myTank.getBullets().iterator();
while (it.hasNext()) {
BulletState bullet = it.next();
if (System.currentTimeMillis() - bullet.getCreateTime() > 4000) {
it.remove();
continue;
}
bullet.update(myTank);
g2d.setColor(Color.GRAY);
g2d.fillOval(bullet.locX, bullet.locY, bullet.diam, bullet.diam);
}
}
//Draw enemies tanks bullet
for (EnemyTank enemyTank :enemyTanks) {
if (enemyTank.getBullets().size() != 0 && !myTank.gameOver && !enemyTank.gameOver) {
Iterator<BulletState> it = enemyTank.getBullets().iterator();
while (it.hasNext()) {
BulletState bullet = it.next();
if (System.currentTimeMillis() - bullet.getCreateTime() > 4000) {
it.remove();
continue;
}
bullet.update(enemyTank);
g2d.setColor(Color.GRAY);
g2d.fillOval(bullet.locX, bullet.locY, bullet.diam, bullet.diam);
}
}
if (System.currentTimeMillis() - RewardState.startShieldTime > 15000) {
myTank.setHasShield(false);
enemyTank.setHasShield(false);
}
}
//Draw explosion and ruin the tank
ArrayList<BulletState> allBullets = new ArrayList<>();
for (int i = myTank.getBullets().size() - 1; i >= 0; i--) {
if (System.currentTimeMillis() - myTank.getBullets().get(i).getCreateTime() > 4000) {
break;
}
allBullets.add(myTank.getBullets().get(i));
}
for (EnemyTank enemyTank : enemyTanks) {
for (int i = enemyTank.getBullets().size() - 1; i >= 0; i--) {
if (System.currentTimeMillis() - enemyTank.getBullets().get(i).getCreateTime() > 4000) {
break;
}
allBullets.add(enemyTank.getBullets().get(i));
}
}
try {
explosionImg = ImageIO.read(new File("C:\\Users\\Lenovo\\IdeaProjects\\JTankTrouble\\pics\\explosion3.png"));
} catch (IOException e) {
System.out.println(e);
}
long startExploding;
for (BulletState bullet : allBullets) {//check my tank
if ((bullet.locX > myTank.locX - 20 && bullet.locX < myTank.locX + 20 && bullet.locY > myTank.locY - 10 && bullet.locY < myTank.locY + 10) && !myTank.hasShield() && System.currentTimeMillis() - bullet.getCreateTime() > 100 && !myTank.isHasMoreLife()) {
startExploding = System.currentTimeMillis();
if (System.currentTimeMillis() - startExploding < 1000) {
g2d.drawImage(op2.filter((BufferedImage) explosionImg, null), myTank.locX, myTank.locY, null);
myTank.setTankLife(0);
myTank.gameOver = true;
}
} else if ((bullet.locX > myTank.locX - 20 && bullet.locX < myTank.locX + 20 && bullet.locY > myTank.locY - 10 && bullet.locY < myTank.locY + 10) && !myTank.hasShield() && System.currentTimeMillis() - bullet.getCreateTime() > 100 && myTank.isHasMoreLife()) {
System.out.println("has ");
myTank.setHasMoreLife(false);
if (myTank.getTankLife() > 100)
myTank.setTankLife(myTank.getTankLife() - 10);
}
}
for (EnemyTank enemyTank :enemyTanks) {
for (BulletState bullet : allBullets) {//check enemy tank
if (!enemyTank.isHasMoreLife()) {
if ((bullet.locX > enemyTank.locX - 20 && bullet.locX < enemyTank.locX + 20 && bullet.locY > enemyTank.locY - 10 && bullet.locY < enemyTank.locY + 10) && !enemyTank.hasShield() && System.currentTimeMillis() - bullet.getCreateTime() > 100) {
enemyTank.setTankLife(enemyTank.getTankLife() - 100);
if (enemyTank.getTankLife() <= 0) {
startExploding = System.currentTimeMillis();
if (System.currentTimeMillis() - startExploding < 1000) {
g2d.drawImage(op2.filter((BufferedImage) explosionImg, null), enemyTank.locX, enemyTank.locY, null);
enemyTank.setTankLife(0);
enemyTank.gameOver = true;
}
}
}
} else if ((bullet.locX > enemyTank.locX - 20 && bullet.locX < enemyTank.locX + 20 && bullet.locY > enemyTank.locY - 10 && bullet.locY < enemyTank.locY + 10) && !enemyTank.hasShield() && System.currentTimeMillis() - bullet.getCreateTime() > 100) {
myTank.setHasMoreLife(false);
if (enemyTank.getTankLife() > 100)
enemyTank.setTankLife(enemyTank.getTankLife() - 10);
}
}
}
//Draw rewards
boolean newReward = (System.currentTimeMillis() - GameLoop.startTime >= 7000);
if (newReward) {
GameLoop.startTime = System.currentTimeMillis();
RewardState reward = new RewardState(myTank.getWalls());
reward.setVisible(true);
rewards.add(reward);
}
if (rewards.size() != 0) {
Iterator<RewardState> it = rewards.iterator();
while (it.hasNext()) {
RewardState reward = it.next();
if (reward.isVisible() && reward.isRewardForTank(myTank.locX, myTank.locY)) {
reward.runReward(myTank);
reward.setVisible(false);
it.remove();
} else if (reward.isVisible() && reward.isRewardForTank(enemyTank.locX, enemyTank.locY)) {
reward.runReward(enemyTank);
reward.setVisible(false);
it.remove();
} else if (reward.isVisible()) {
g2d.drawImage(reward.getRewardImage(), reward.locX, reward.locY, null);
}
}
}
// Print FPS info
long currentRender = System.currentTimeMillis();
if (lastRender > 0) {
fpsHistory.add(1000.0f / (currentRender - lastRender));
if (fpsHistory.size() > 100) {
fpsHistory.remove(0); // remove oldest
}
float avg = 0.0f;
for (float fps : fpsHistory) {
avg += fps;
}
avg /= fpsHistory.size();
String str = String.format("Average FPS = %.1f , Last Interval = %d ms",
avg, (currentRender - lastRender));
g2d.setColor(Color.CYAN);
g2d.setFont(g2d.getFont().deriveFont(18.0f));
int strWidth = g2d.getFontMetrics().stringWidth(str);
int strHeight = g2d.getFontMetrics().getHeight();
g2d.drawString(str, (GAME_WIDTH - strWidth) / 2, strHeight + 50);
}
lastRender = (int) currentRender;
// Print user guide
String userGuide
= "Use ARROW KEYS to move the TANK. "
+ "Press ESCAPE to end the game. you=" + myTank.getTankLife() ;
g2d.setFont(g2d.getFont().deriveFont(18.0f));
g2d.drawString(userGuide, 10, GAME_HEIGHT - 10);
// Draw GAME OVER
if (myTank.gameOver) {
String str = "GAME OVER";
g2d.setColor(Color.WHITE);
g2d.setFont(g2d.getFont().deriveFont(Font.BOLD).deriveFont(64.0f));
int strWidth = g2d.getFontMetrics().stringWidth(str);
g2d.drawString(str, (GAME_WIDTH - strWidth) / 2, GAME_HEIGHT / 2);
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment