From 63ec1c8f026c08d0781f37f085f84342dcc6f4cd Mon Sep 17 00:00:00 2001 From: cokacider Date: Wed, 2 May 2018 11:43:35 +0900 Subject: [PATCH 01/47] updateCameraForRoamingMovements Method Refactoring Refactoring Operation - Introduce Explaining Variable - Extract Method Refactoring target - updateCameraForRoamingMovements(TimeStep timeStep) For readability To remove duplicated codes --- .../client/inputs/CameraController.java | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/src/seventh/client/inputs/CameraController.java b/src/seventh/client/inputs/CameraController.java index 773e0b5..b6f43d7 100644 --- a/src/seventh/client/inputs/CameraController.java +++ b/src/seventh/client/inputs/CameraController.java @@ -301,24 +301,18 @@ private void updateCameraForRoamingMovements(TimeStep timeStep) { double dt = timeStep.asFraction(); int newX = (int)Math.round(pos.x + playerVelocity.x * movementSpeed * dt); - int newY = (int)Math.round(pos.y + playerVelocity.y * movementSpeed * dt); - + int newY = (int)Math.round(pos.y + playerVelocity.y * movementSpeed * dt); bounds.x = newX; - if( map.checkBounds(bounds.x, bounds.y) || - ((bounds.x < bounds.width/2) || (bounds.y < bounds.height/2)) || - map.checkBounds(bounds.x + bounds.width/2, bounds.y + bounds.height/2) ) { + if( cameraForRoamingMovementsIsOutOfMap() ) { bounds.x = (int)pos.x; - } - + } bounds.y = newY; - if( map.checkBounds(bounds.x, bounds.y) || - ((bounds.x < bounds.width/2) || (bounds.y < bounds.height/2)) || - map.checkBounds(bounds.x + bounds.width/2, bounds.y + bounds.height/2) ) { + if( cameraForRoamingMovementsIsOutOfMap() ) { bounds.y = (int)pos.y; } - + pos.x = bounds.x; pos.y = bounds.y; @@ -329,6 +323,21 @@ private void updateCameraForRoamingMovements(TimeStep timeStep) { Sounds.setPosition(cameraCenterAround); } } + + /** + * To remove duplicated code and for readability in updateCameraForRoamingMovements(TimeStep timeStep) function + * + */ + private boolean cameraForRoamingMovementsIsOutOfMap() { + final boolean boundsXYIsOutOfMap = map.checkBounds(bounds.x, bounds.y); + final boolean boundsXIsLowerThanViewPortCenterX = bounds.x < bounds.width / 2; + final boolean boundsYIsLowerThanViewPortCenterY = bounds.y < bounds.height / 2; + final boolean boundsCenterIsOutOfMap = map.checkBounds(bounds.x + bounds.width/2, bounds.y + bounds.height/2); + + return boundsXYIsOutOfMap || + (boundsXIsLowerThanViewPortCenterX || boundsYIsLowerThanViewPortCenterY) || + boundsCenterIsOutOfMap; + } /** From fb98c87d1ed4b45b6c215e5eabbe2471987f5429 Mon Sep 17 00:00:00 2001 From: cokacider Date: Wed, 2 May 2018 11:48:25 +0900 Subject: [PATCH 02/47] convert taps to 4 spaces --- src/seventh/client/inputs/CameraController.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/seventh/client/inputs/CameraController.java b/src/seventh/client/inputs/CameraController.java index b6f43d7..451f906 100644 --- a/src/seventh/client/inputs/CameraController.java +++ b/src/seventh/client/inputs/CameraController.java @@ -328,16 +328,16 @@ private void updateCameraForRoamingMovements(TimeStep timeStep) { * To remove duplicated code and for readability in updateCameraForRoamingMovements(TimeStep timeStep) function * */ - private boolean cameraForRoamingMovementsIsOutOfMap() { - final boolean boundsXYIsOutOfMap = map.checkBounds(bounds.x, bounds.y); + private boolean cameraForRoamingMovementsIsOutOfMap() { + final boolean boundsXYIsOutOfMap = map.checkBounds(bounds.x, bounds.y); final boolean boundsXIsLowerThanViewPortCenterX = bounds.x < bounds.width / 2; final boolean boundsYIsLowerThanViewPortCenterY = bounds.y < bounds.height / 2; final boolean boundsCenterIsOutOfMap = map.checkBounds(bounds.x + bounds.width/2, bounds.y + bounds.height/2); - + return boundsXYIsOutOfMap || - (boundsXIsLowerThanViewPortCenterX || boundsYIsLowerThanViewPortCenterY) || - boundsCenterIsOutOfMap; - } + (boundsXIsLowerThanViewPortCenterX || boundsYIsLowerThanViewPortCenterY) || + boundsCenterIsOutOfMap; + } /** From f04dd53e8bc290e3cb9d759bfa127046acde565c Mon Sep 17 00:00:00 2001 From: aikaran Date: Wed, 2 May 2018 17:11:09 +0900 Subject: [PATCH 03/47] Refactoring IS-A Relationship Target : Tri class in seventh.math package Reason : An inheritance should from an IS-A relationship, but tri(if i guessed correctly, the meaning of this is triple) is not a pair. --- src/seventh/math/Tri.java | 52 ++++++++++++++++++++++++++++++++++----- 1 file changed, 46 insertions(+), 6 deletions(-) diff --git a/src/seventh/math/Tri.java b/src/seventh/math/Tri.java index 7d21819..6858c24 100644 --- a/src/seventh/math/Tri.java +++ b/src/seventh/math/Tri.java @@ -6,24 +6,64 @@ /** * @author Tony - * + * */ -public class Tri extends Pair { +public class Tri { /** - * Thrid Var + * Get the first item */ - private Z third; + private X first; + /** + * Get the second item + */ + private Y second; + + /** + * Get the third item + */ + private Z third; + /** * @param first * @param second + * @param third */ public Tri(X first, Y second, Z third) { - super(first, second); - this.third = third; + this.first = first; + this.second = second; + this.third = third; + } + + /** + * @param first the first to set + */ + public void setFirst(X first) { + this.first = first; + } + + /** + * @return the first + */ + public X getFirst() { + return first; + } + + /** + * @param second the second to set + */ + public void setSecond(Y second) { + this.second = second; } + /** + * @return the second + */ + public Y getSecond() { + return second; + } + /** * @param third the third to set */ From 3f6ccf8327d397ce006a61c380b65cc9386d28c7 Mon Sep 17 00:00:00 2001 From: cokacider Date: Thu, 3 May 2018 23:31:51 +0900 Subject: [PATCH 04/47] Replace the number of weapon classes with a constant Refactoring Operation: - Replace Magic Number with Symbolic Constant Refactoring Target: - the number of array of Button and Label because the numeric value(7) had no obvious meaning, I replace the value with constant --- src/seventh/client/gfx/WeaponClassDialog.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/seventh/client/gfx/WeaponClassDialog.java b/src/seventh/client/gfx/WeaponClassDialog.java index 5f8c8ce..07caf21 100644 --- a/src/seventh/client/gfx/WeaponClassDialog.java +++ b/src/seventh/client/gfx/WeaponClassDialog.java @@ -30,6 +30,8 @@ public class WeaponClassDialog extends Widget { private Label title; private Theme theme; + private static final int NUMBER_OF_WEAPON_CLASSES = 7; + private Button[] weaponClasses; private Label[] weaponClassDescriptions; private Button cancel; @@ -47,8 +49,8 @@ public WeaponClassDialog(InGameOptionsDialog owner, ClientConnection network, Th this.team = ClientTeam.ALLIES; this.theme = theme; - this.weaponClasses = new Button[7]; - this.weaponClassDescriptions = new Label[7]; + this.weaponClasses = new Button[NUMBER_OF_WEAPON_CLASSES]; + this.weaponClassDescriptions = new Label[NUMBER_OF_WEAPON_CLASSES]; createUI(); } From 49273eb4f6d83df91718578bdbc7cb277274aeb9 Mon Sep 17 00:00:00 2001 From: cokacider Date: Fri, 4 May 2018 00:00:13 +0900 Subject: [PATCH 05/47] Extract methods createTitleLabel, createCancelButton Refactoring Operation: - Extract Method Refactoring Target: - createUI method I think it needs to isolate independent parts of code. --- src/seventh/client/gfx/WeaponClassDialog.java | 32 +++++++++++++------ 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/src/seventh/client/gfx/WeaponClassDialog.java b/src/seventh/client/gfx/WeaponClassDialog.java index 07caf21..aca0f62 100644 --- a/src/seventh/client/gfx/WeaponClassDialog.java +++ b/src/seventh/client/gfx/WeaponClassDialog.java @@ -91,7 +91,21 @@ private void createUI() { Rectangle bounds = getBounds(); - this.title = new Label("Select a Weapon"); + createTitleLabel(bounds); + + refreshButtons(); + + createCancelButton(bounds); + + addWidget(cancel); + addWidget(title); + } + + /** + * @param bounds + */ + private void createTitleLabel(final Rectangle bounds) { + this.title = new Label("Select a Weapon"); this.title.setTheme(theme); //this.title.setForegroundColor(0xffffffff); this.title.setBounds(new Rectangle(bounds)); @@ -100,10 +114,13 @@ private void createUI() { this.title.setFont(theme.getSecondaryFontName()); this.title.setHorizontalTextAlignment(TextAlignment.CENTER); this.title.setTextSize(22); - - refreshButtons(); - - this.cancel = new Button(); + } + + /** + * @param bounds + */ + private void createCancelButton(final Rectangle bounds) { + this.cancel = new Button(); this.cancel.setText("Cancel"); this.cancel.setBounds(new Rectangle(0,0,100,40)); this.cancel.getBounds().centerAround(bounds.x + 205, bounds.y + bounds.height - 10); @@ -120,10 +137,7 @@ public void onButtonClicked(ButtonEvent event) { owner.close(); } }); - - addWidget(cancel); - addWidget(title); - } + } private Vector2f refreshButtons() { Rectangle bounds = getBounds(); From b46130acb7a3164bc6a54a2f600f9077cbc81be4 Mon Sep 17 00:00:00 2001 From: cokacider Date: Fri, 4 May 2018 00:02:39 +0900 Subject: [PATCH 06/47] convert tabs to 4 spaces --- src/seventh/client/gfx/WeaponClassDialog.java | 22 +++++++++---------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/src/seventh/client/gfx/WeaponClassDialog.java b/src/seventh/client/gfx/WeaponClassDialog.java index aca0f62..06bfc32 100644 --- a/src/seventh/client/gfx/WeaponClassDialog.java +++ b/src/seventh/client/gfx/WeaponClassDialog.java @@ -102,10 +102,10 @@ private void createUI() { } /** - * @param bounds - */ - private void createTitleLabel(final Rectangle bounds) { - this.title = new Label("Select a Weapon"); + * @param bounds + */ + private void createTitleLabel(final Rectangle bounds) { + this.title = new Label("Select a Weapon"); this.title.setTheme(theme); //this.title.setForegroundColor(0xffffffff); this.title.setBounds(new Rectangle(bounds)); @@ -114,13 +114,13 @@ private void createTitleLabel(final Rectangle bounds) { this.title.setFont(theme.getSecondaryFontName()); this.title.setHorizontalTextAlignment(TextAlignment.CENTER); this.title.setTextSize(22); - } + } - /** - * @param bounds - */ - private void createCancelButton(final Rectangle bounds) { - this.cancel = new Button(); + /** + * @param bounds + */ + private void createCancelButton(final Rectangle bounds) { + this.cancel = new Button(); this.cancel.setText("Cancel"); this.cancel.setBounds(new Rectangle(0,0,100,40)); this.cancel.getBounds().centerAround(bounds.x + 205, bounds.y + bounds.height - 10); @@ -137,7 +137,7 @@ public void onButtonClicked(ButtonEvent event) { owner.close(); } }); - } + } private Vector2f refreshButtons() { Rectangle bounds = getBounds(); From b86c24883c96f17837af8f2f0bdd6c76c0d18d10 Mon Sep 17 00:00:00 2001 From: cokacider Date: Fri, 4 May 2018 00:16:31 +0900 Subject: [PATCH 07/47] Rename method createTitleLabel -> setupTitleLabel createCancelButton -> setupCancelButton --- src/seventh/client/gfx/WeaponClassDialog.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/seventh/client/gfx/WeaponClassDialog.java b/src/seventh/client/gfx/WeaponClassDialog.java index 06bfc32..fbe7d11 100644 --- a/src/seventh/client/gfx/WeaponClassDialog.java +++ b/src/seventh/client/gfx/WeaponClassDialog.java @@ -91,11 +91,11 @@ private void createUI() { Rectangle bounds = getBounds(); - createTitleLabel(bounds); + setupTitleLabel(bounds); refreshButtons(); - createCancelButton(bounds); + setupCancelButton(bounds); addWidget(cancel); addWidget(title); @@ -104,7 +104,7 @@ private void createUI() { /** * @param bounds */ - private void createTitleLabel(final Rectangle bounds) { + private void setupTitleLabel(final Rectangle bounds) { this.title = new Label("Select a Weapon"); this.title.setTheme(theme); //this.title.setForegroundColor(0xffffffff); @@ -119,7 +119,7 @@ private void createTitleLabel(final Rectangle bounds) { /** * @param bounds */ - private void createCancelButton(final Rectangle bounds) { + private void setupCancelButton(final Rectangle bounds) { this.cancel = new Button(); this.cancel.setText("Cancel"); this.cancel.setBounds(new Rectangle(0,0,100,40)); From f70a11b15ce7e477dd60f549b0c71b2a180d5f75 Mon Sep 17 00:00:00 2001 From: terry2511 Date: Fri, 4 May 2018 17:12:08 +0900 Subject: [PATCH 08/47] Refactoring game/entities and map --- src/seventh/game/entities/Door.java | 58 +++++++++++---------- src/seventh/game/entities/Entity.java | 7 ++- src/seventh/game/entities/PlayerEntity.java | 10 ++-- src/seventh/map/OrthoMap.java | 55 +++++++++---------- 4 files changed, 67 insertions(+), 63 deletions(-) diff --git a/src/seventh/game/entities/Door.java b/src/seventh/game/entities/Door.java index a8ecfce..25fd1a0 100644 --- a/src/seventh/game/entities/Door.java +++ b/src/seventh/game/entities/Door.java @@ -389,10 +389,10 @@ else if(this.isBlocked) { } public void open(Entity ent) { - if(this.doorState != DoorState.OPENED || - this.doorState != DoorState.OPENING || - this.doorState != DoorState.CLOSING) { - + boolean isNotOpened = this.doorState != DoorState.OPENED; + boolean isNotOpening = this.doorState != DoorState.OPENING; + boolean isNotClosing = this.doorState != DoorState.CLOSING; + if(isNotOpened || isNotOpening || isNotClosing) { if(!canBeHandledBy(ent)) { return; } @@ -407,31 +407,35 @@ public void open(Entity ent) { // figure out what side the entity is // of the door hinge, depending on their // side, we set the destinationOrientation - switch(this.hinge) { - - case NORTH_END: - case SOUTH_END: - if(entPos.x < hingePos.x) { - this.targetOrientation = (float)Math.toRadians(0); - } - else if(entPos.x > hingePos.x) { - this.targetOrientation = (float)Math.toRadians(180); - } - break; - case EAST_END: - case WEST_END: - if(entPos.y < hingePos.y) { - this.targetOrientation = (float)Math.toRadians(90); - } - else if(entPos.y > hingePos.y) { - this.targetOrientation = (float)Math.toRadians(270); - } - break; - default: - break; - } + setDestinationOrientation(entPos, hingePos); } } + + private void setDestinationOrientation(Vector2f entPos, Vector2f hingePos) { + switch(this.hinge) { + + case NORTH_END: + case SOUTH_END: + if(entPos.x < hingePos.x) { + this.targetOrientation = (float)Math.toRadians(0); + } + else if(entPos.x > hingePos.x) { + this.targetOrientation = (float)Math.toRadians(180); + } + break; + case EAST_END: + case WEST_END: + if(entPos.y < hingePos.y) { + this.targetOrientation = (float)Math.toRadians(90); + } + else if(entPos.y > hingePos.y) { + this.targetOrientation = (float)Math.toRadians(270); + } + break; + default: + break; + } + } public void close(Entity ent) { if(this.doorState != DoorState.CLOSED || diff --git a/src/seventh/game/entities/Entity.java b/src/seventh/game/entities/Entity.java index 9ba3a8a..9939749 100644 --- a/src/seventh/game/entities/Entity.java +++ b/src/seventh/game/entities/Entity.java @@ -661,10 +661,13 @@ private int adjustX(Vector2f collisionTilePos, float deltaY, int currentX, int c */ public boolean update(TimeStep timeStep) { boolean isBlocked = false; + boolean isWalking = currentState == State.WALKING; + boolean isSprinting = currentState == State.SPRINTING; + boolean isCrouching = currentState==State.CROUCHING; this.movementDir.zeroOut(); if(this.isAlive && !this.vel.isZero()) { - if(currentState != State.WALKING && currentState != State.SPRINTING) { + if(!isWalking && !isSprinting) { currentState = State.RUNNING; } @@ -754,7 +757,7 @@ else if(deltaX==0 && deltaY!=0) { this.walkingTime = WALK_TIME; } else { - if(this.walkingTime<=0 && currentState!=State.CROUCHING) { + if(this.walkingTime<=0 && !isCrouching) { currentState = State.IDLE; } diff --git a/src/seventh/game/entities/PlayerEntity.java b/src/seventh/game/entities/PlayerEntity.java index d5d9dad..47ef60a 100644 --- a/src/seventh/game/entities/PlayerEntity.java +++ b/src/seventh/game/entities/PlayerEntity.java @@ -1012,11 +1012,15 @@ public void sprint() { * 6) you are not reloading */ - if(currentState!=State.DEAD && - stamina > 0 && + final boolean isAlive = currentState!=State.DEAD; + final boolean hasStamina = stamina > 0; + final boolean noRecoveryTime = recoveryTime <= 0; + + if(isAlive && + hasStamina && !firing && !wasSprinting && - recoveryTime <= 0) { + noRecoveryTime) { Weapon weapon = this.inventory.currentItem(); boolean isReady = weapon != null ? weapon.isReady() : true; diff --git a/src/seventh/map/OrthoMap.java b/src/seventh/map/OrthoMap.java index 7364838..617c95e 100644 --- a/src/seventh/map/OrthoMap.java +++ b/src/seventh/map/OrthoMap.java @@ -487,6 +487,9 @@ public void setMask(List tiles, int mask) { } } + + + /* * (non-Javadoc) * @@ -494,38 +497,10 @@ public void setMask(List tiles, int mask) { */ public void destroy() { - if ( this.backgroundLayers != null ) { - for (int i = 0; i < this.backgroundLayers.length; i++) { - Layer layer = this.backgroundLayers[i]; - if ( layer == null ) { - continue; - } - - - for( int j = 0; j < this.backgroundLayers[i].numberOfRows(); j++ ) { - this.backgroundLayers[i].destroy(); - } - this.backgroundLayers[i] = null; - } - - } + + destoryRowLayerisNotNULL(this.backgroundLayers); this.backgroundLayers = null; - - - if ( this.foregroundLayers != null ) { - for (int i = 0; i < this.foregroundLayers.length; i++) { - Layer layer = this.foregroundLayers[i]; - if ( layer == null ) { - continue; - } - - for( int j = 0; j < this.foregroundLayers[i].numberOfRows(); j++ ) { - this.foregroundLayers[i].destroy(); - } - - this.foregroundLayers[i] = null; - } - } + destoryRowLayerisNotNULL(this.foregroundLayers); this.foregroundLayers = null; this.collidableLayers=null; @@ -563,6 +538,24 @@ public void destroy() { this.mapObjects.clear(); } } + + public void destoryRowLayerisNotNULL(Layer[] layers) { + // TODO Auto-generated method stub + if ( layers != null ) { + for (int i = 0; i < layers.length; i++) { + Layer layer = layers[i]; + if ( layer == null ) { + continue; + } + + for( int j = 0; j < layers[i].numberOfRows(); j++ ) { + layers[i].destroy(); + } + layers[i] = null; + } + } + } + /* (non-Javadoc) * @see seventh.map.Map#getTileWorldHeight() From 599191518f46716c3e0096cab888257894d37499 Mon Sep 17 00:00:00 2001 From: terry2511 Date: Fri, 4 May 2018 17:31:48 +0900 Subject: [PATCH 09/47] Door Update --- src/seventh/game/entities/Door.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/seventh/game/entities/Door.java b/src/seventh/game/entities/Door.java index 25fd1a0..0a10faa 100644 --- a/src/seventh/game/entities/Door.java +++ b/src/seventh/game/entities/Door.java @@ -392,6 +392,7 @@ public void open(Entity ent) { boolean isNotOpened = this.doorState != DoorState.OPENED; boolean isNotOpening = this.doorState != DoorState.OPENING; boolean isNotClosing = this.doorState != DoorState.CLOSING; + if(isNotOpened || isNotOpening || isNotClosing) { if(!canBeHandledBy(ent)) { return; From 39e527a373abee0cfce56edac87484e148af0020 Mon Sep 17 00:00:00 2001 From: aikaran Date: Sat, 5 May 2018 22:48:27 +0900 Subject: [PATCH 10/47] Extract Method ProgressBarView I extracted the source code that needs explanation. --- src/seventh/ui/view/ProgressBarView.java | 40 +++++++++++++----------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/src/seventh/ui/view/ProgressBarView.java b/src/seventh/ui/view/ProgressBarView.java index ba0bca5..56c567a 100644 --- a/src/seventh/ui/view/ProgressBarView.java +++ b/src/seventh/ui/view/ProgressBarView.java @@ -47,25 +47,27 @@ public void render(Canvas canvas, Camera camera, float alpha) { canvas.fillRect(bounds.x, bounds.y, percentOfWidth, bounds.height, progressBar.getForegroundColor()); canvas.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 0xff000000); - int x = bounds.x; - int y = bounds.y; - - // add a shadow effect - canvas.drawLine( x, y+1, x+bounds.width, y+1, 0x8f000000 ); - canvas.drawLine( x, y+2, x+bounds.width, y+2, 0x5f000000 ); - canvas.drawLine( x, y+3, x+bounds.width, y+3, 0x2f000000 ); - canvas.drawLine( x, y+4, x+bounds.width, y+4, 0x0f000000 ); - canvas.drawLine( x, y+5, x+bounds.width, y+5, 0x0b000000 ); - canvas.drawLine( x, y+6, x+bounds.width, y+6, 0x0a000000 ); - - y = y+15; - canvas.drawLine( x, y-6, x+bounds.width, y-6, 0x0a000000 ); - canvas.drawLine( x, y-5, x+bounds.width, y-5, 0x0b000000 ); - canvas.drawLine( x, y-4, x+bounds.width, y-4, 0x0f000000 ); - canvas.drawLine( x, y-3, x+bounds.width, y-3, 0x2f000000 ); - canvas.drawLine( x, y-2, x+bounds.width, y-2, 0x5f000000 ); - canvas.drawLine( x, y-1, x+bounds.width, y-1, 0x8f000000 ); + addAShadowEffect(canvas, bounds); } } - + + private void addAShadowEffect(Canvas canvas, Rectangle bounds) { + int x = bounds.x; + int y = bounds.y; + + canvas.drawLine( x, y+1, x+bounds.width, y+1, 0x8f000000 ); + canvas.drawLine( x, y+2, x+bounds.width, y+2, 0x5f000000 ); + canvas.drawLine( x, y+3, x+bounds.width, y+3, 0x2f000000 ); + canvas.drawLine( x, y+4, x+bounds.width, y+4, 0x0f000000 ); + canvas.drawLine( x, y+5, x+bounds.width, y+5, 0x0b000000 ); + canvas.drawLine( x, y+6, x+bounds.width, y+6, 0x0a000000 ); + + y = y+15; + canvas.drawLine( x, y-6, x+bounds.width, y-6, 0x0a000000 ); + canvas.drawLine( x, y-5, x+bounds.width, y-5, 0x0b000000 ); + canvas.drawLine( x, y-4, x+bounds.width, y-4, 0x0f000000 ); + canvas.drawLine( x, y-3, x+bounds.width, y-3, 0x2f000000 ); + canvas.drawLine( x, y-2, x+bounds.width, y-2, 0x5f000000 ); + canvas.drawLine( x, y-1, x+bounds.width, y-1, 0x8f000000 ); + } } From 39bdfdd0aa3e624246a5c8583049794878805874 Mon Sep 17 00:00:00 2001 From: cokacider Date: Sun, 6 May 2018 14:29:37 +0900 Subject: [PATCH 11/47] Extract methods from refreshButtons method Refactoring Operation: - Extract Method Refactoring Target: - refreshButtons method 'refresh' contains 'initializing' and 'setup'. it is needed to separate these two different functions. --- src/seventh/client/gfx/WeaponClassDialog.java | 21 ++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/src/seventh/client/gfx/WeaponClassDialog.java b/src/seventh/client/gfx/WeaponClassDialog.java index fbe7d11..038808d 100644 --- a/src/seventh/client/gfx/WeaponClassDialog.java +++ b/src/seventh/client/gfx/WeaponClassDialog.java @@ -140,15 +140,13 @@ public void onButtonClicked(ButtonEvent event) { } private Vector2f refreshButtons() { - Rectangle bounds = getBounds(); - - Vector2f pos = new Vector2f(); - pos.x = bounds.x + 120; - pos.y = bounds.y + 50; - - int yInc = 50; + initWeaponClasses(); + return setupWeaponClasses(); + } + + private void initWeaponClasses() { for(int i = 0; i < weaponClasses.length; i++) { if( this.weaponClasses[i] != null ) { removeWidget(weaponClasses[i]); @@ -160,7 +158,16 @@ private Vector2f refreshButtons() { this.weaponClassDescriptions[i] = null; } } + } + + private Vector2f setupWeaponClasses() { + Rectangle bounds = getBounds(); + + Vector2f pos = new Vector2f(); + pos.x = bounds.x + 120; + pos.y = bounds.y + 50; + int yInc = 50; switch(team) { case AXIS: From 0aeb486939306c692390b35037e208e3a5761828 Mon Sep 17 00:00:00 2001 From: cokacider Date: Sun, 6 May 2018 15:47:11 +0900 Subject: [PATCH 12/47] Refactoring refreshButtons method Refactoring Operation: - Extract Method Refactoring Target: - refreshButtons method - setupWeaponClasses method to remove duplicated codes ease to change the weapon types --- src/seventh/client/gfx/WeaponClassDialog.java | 80 ++++++++++++------- 1 file changed, 50 insertions(+), 30 deletions(-) diff --git a/src/seventh/client/gfx/WeaponClassDialog.java b/src/seventh/client/gfx/WeaponClassDialog.java index 038808d..9f21e85 100644 --- a/src/seventh/client/gfx/WeaponClassDialog.java +++ b/src/seventh/client/gfx/WeaponClassDialog.java @@ -171,43 +171,63 @@ private Vector2f setupWeaponClasses() { switch(team) { case AXIS: - this.weaponClasses[0] =setupButton(pos, Type.MP40); - this.weaponClassDescriptions[0] = setupLabel(pos, Type.MP40); pos.y += yInc; - - this.weaponClasses[1] =setupButton(pos, Type.MP44); - this.weaponClassDescriptions[1] = setupLabel(pos, Type.MP44); pos.y += yInc; - - this.weaponClasses[2] =setupButton(pos, Type.KAR98); - this.weaponClassDescriptions[2] = setupLabel(pos, Type.KAR98); pos.y += yInc; + for (int weaponClassIndex = 0; weaponClassIndex < NUMBER_OF_WEAPON_CLASSES; weaponClassIndex++) { + setupAXISWeaponClass(weaponClassIndex, pos); + if (weaponClassIndex < NUMBER_OF_WEAPON_CLASSES - 1) { + pos.y += yInc; + } + } break; case ALLIES: default: - this.weaponClasses[0] =setupButton(pos, Type.THOMPSON); - this.weaponClassDescriptions[0] = setupLabel(pos, Type.THOMPSON); pos.y += yInc; - - this.weaponClasses[1] =setupButton(pos, Type.M1_GARAND); - this.weaponClassDescriptions[1] = setupLabel(pos, Type.M1_GARAND); pos.y += yInc; - - this.weaponClasses[2] =setupButton(pos, Type.SPRINGFIELD); - this.weaponClassDescriptions[2] = setupLabel(pos, Type.SPRINGFIELD); pos.y += yInc; - break; - - } - this.weaponClasses[3] =setupButton(pos, Type.RISKER); - this.weaponClassDescriptions[3] = setupLabel(pos, Type.RISKER); pos.y += yInc; - - this.weaponClasses[4] =setupButton(pos, Type.SHOTGUN); - this.weaponClassDescriptions[4] = setupLabel(pos, Type.SHOTGUN); pos.y += yInc; - - this.weaponClasses[5] =setupButton(pos, Type.ROCKET_LAUNCHER); - this.weaponClassDescriptions[5] = setupLabel(pos, Type.ROCKET_LAUNCHER); pos.y += yInc; - - this.weaponClasses[6] =setupButton(pos, Type.FLAME_THROWER); - this.weaponClassDescriptions[6] = setupLabel(pos, Type.FLAME_THROWER); + for (int weaponClassIndex = 0; weaponClassIndex < NUMBER_OF_WEAPON_CLASSES; weaponClassIndex++) { + setupALLIESWeaponClass(weaponClassIndex, pos); + if (weaponClassIndex < NUMBER_OF_WEAPON_CLASSES - 1) { + pos.y += yInc; + } + } + break; + } return pos; } + private static final Type[] AXIS_WEAPON_TYPES = { + // AXIS only + Type.MP40, + Type.MP44, + Type.KAR98, + + // AXIS, ALLIES share + Type.RISKER, + Type.SHOTGUN, + Type.ROCKET_LAUNCHER, + Type.FLAME_THROWER + }; + + private static final Type[] ALLIES_WEAPON_TYPES = { + // ALLIES only + Type.THOMPSON, + Type.M1_GARAND, + Type.SPRINGFIELD, + + // AXIS, ALLIES share + Type.RISKER, + Type.SHOTGUN, + Type.ROCKET_LAUNCHER, + Type.FLAME_THROWER + }; + + private void setupAXISWeaponClass(int weaponClassIndex, Vector2f pos) { + this.weaponClasses[weaponClassIndex] = setupButton(pos, AXIS_WEAPON_TYPES[weaponClassIndex]); + this.weaponClassDescriptions[weaponClassIndex] = setupLabel(pos, AXIS_WEAPON_TYPES[weaponClassIndex]); + } + + private void setupALLIESWeaponClass(int weaponClassIndex, Vector2f pos) { + this.weaponClasses[weaponClassIndex] = setupButton(pos, ALLIES_WEAPON_TYPES[weaponClassIndex]); + this.weaponClassDescriptions[weaponClassIndex] = setupLabel(pos, ALLIES_WEAPON_TYPES[weaponClassIndex]); + } + private String getClassDescription(Type type) { String message = ""; switch(type) { From 82e78a5c78050b8137a6b8b353a4344e0195925e Mon Sep 17 00:00:00 2001 From: GardenHee Date: Sun, 6 May 2018 18:55:34 +0900 Subject: [PATCH 13/47] Refactoring Seventh.game.type.obj.ObjectiveScript.java --- .../type/obj/NonDefenderTypeException.java | 7 + .../type/obj/NonLeoNativeTypeException.java | 10 + .../game/type/obj/NonObjectTypeException.java | 10 + .../type/obj/NotExistScriptFileException.java | 9 + .../game/type/obj/ObjectiveScript.java | 186 +++++++++++------- 5 files changed, 146 insertions(+), 76 deletions(-) create mode 100644 src/seventh/game/type/obj/NonDefenderTypeException.java create mode 100644 src/seventh/game/type/obj/NonLeoNativeTypeException.java create mode 100644 src/seventh/game/type/obj/NonObjectTypeException.java create mode 100644 src/seventh/game/type/obj/NotExistScriptFileException.java diff --git a/src/seventh/game/type/obj/NonDefenderTypeException.java b/src/seventh/game/type/obj/NonDefenderTypeException.java new file mode 100644 index 0000000..31aa88d --- /dev/null +++ b/src/seventh/game/type/obj/NonDefenderTypeException.java @@ -0,0 +1,7 @@ +package seventh.game.type.obj; + +public class NonDefenderTypeException extends Exception { + public String toString(){ + return "*** ERROR -> defenders must either be a 2(for allies) or 4(for axis) or 'allies' or 'axis' values"; + } +} diff --git a/src/seventh/game/type/obj/NonLeoNativeTypeException.java b/src/seventh/game/type/obj/NonLeoNativeTypeException.java new file mode 100644 index 0000000..1a9b8d9 --- /dev/null +++ b/src/seventh/game/type/obj/NonLeoNativeTypeException.java @@ -0,0 +1,10 @@ +package seventh.game.type.obj; + +import seventh.shared.Cons; + +public class NonLeoNativeTypeException extends Exception { + public String toString(){ + return "*** ERROR -> objectives must either be an Array of objectives or a Java class or custom Leola class"; + } + +} diff --git a/src/seventh/game/type/obj/NonObjectTypeException.java b/src/seventh/game/type/obj/NonObjectTypeException.java new file mode 100644 index 0000000..1b8c699 --- /dev/null +++ b/src/seventh/game/type/obj/NonObjectTypeException.java @@ -0,0 +1,10 @@ +package seventh.game.type.obj; + +import seventh.shared.Cons; + +public class NonObjectTypeException extends Exception { + public String toString(){ + return "*** ERROR -> objectives must either be an Array of objectives or a Java class or custom Leola class"; + } + +} diff --git a/src/seventh/game/type/obj/NotExistScriptFileException.java b/src/seventh/game/type/obj/NotExistScriptFileException.java new file mode 100644 index 0000000..75527bf --- /dev/null +++ b/src/seventh/game/type/obj/NotExistScriptFileException.java @@ -0,0 +1,9 @@ +package seventh.game.type.obj; + +public class NotExistScriptFileException extends Exception{ + + public String toString() { + return "*** ERROR -> No associated script file for objective game type"; + + } +} diff --git a/src/seventh/game/type/obj/ObjectiveScript.java b/src/seventh/game/type/obj/ObjectiveScript.java index 3b2ad54..31791f6 100644 --- a/src/seventh/game/type/obj/ObjectiveScript.java +++ b/src/seventh/game/type/obj/ObjectiveScript.java @@ -45,85 +45,119 @@ public GameType loadGameType(String mapFile, int maxScore, long matchTime) throw List axisSpawnPoints = new ArrayList(); byte defenders = Team.AXIS_TEAM_ID; int minimumObjectivesToComplete = 1; - + final long timeBetweenRounds = 10_000L; + File scriptFile = new File(mapFile + ".obj.leola"); - if(!scriptFile.exists()) { - Cons.println("*** ERROR -> No associated script file for objective game type. Looking for: " + scriptFile.getName()); + if (!scriptFile.exists()) { + throw new NotExistScriptFileException(); + }; + + LeoObject config = getRuntime().eval(scriptFile); + if (LeoObject.isTrue(config)) { + + addscriptedObjectives(objectives, config); + defenders = addScriptedDenfenders(defenders, config); + alliedSpawnPoints = loadSpawnPoint(config, "alliedSpawnPoints"); + axisSpawnPoints = loadSpawnPoint(config, "axisSpawnPoints"); + minimumObjectivesToComplete = checkMinumumObjectCompleteSize(objectives, config); + } - else { - LeoObject config = getRuntime().eval(scriptFile); - if(LeoObject.isTrue(config)) { - LeoObject scriptedObjectives = config.getObject("objectives"); - if(LeoObject.isTrue(scriptedObjectives)) { - switch(scriptedObjectives.getType()) { - case ARRAY: { - LeoArray array = scriptedObjectives.as(); - for(int i = 0; i < array.size(); i++) { - LeoObject o = array.get(i); - if (o instanceof LeoNativeClass) { - if(o.getValue() instanceof Objective) { - Objective objective = (Objective)o.getValue(); - objectives.add(objective); - } - else { - Cons.println(((LeoNativeClass) o).getNativeClass() + " is not of type: " + Objective.class.getName()); - } - - } - } - break; - } - case NATIVE_CLASS: { - LeoObject o = scriptedObjectives; - if(o.getValue() instanceof Objective) { - Objective objective = (Objective)o.getValue(); - objectives.add(objective); - } - else { - Cons.println(((LeoNativeClass) o).getNativeClass() + " is not of type: " + Objective.class.getName()); - } - break; - } - default: { - Cons.println("*** ERROR -> objectives must either be an Array of objectives or a Java class or custom Leola class"); - } - } - } - - LeoObject scriptedDefenders = config.getObject("defenders"); - if(LeoObject.isTrue(scriptedDefenders)) { - switch(scriptedDefenders.getType()) { - case INTEGER: - case LONG: - case REAL: - defenders = (byte)scriptedDefenders.asInt(); - break; - case STRING: - if(Team.ALLIED_TEAM_NAME.equalsIgnoreCase(scriptedDefenders.toString())) { - defenders = Team.ALLIED_TEAM_ID; - } - break; - default:{ - Cons.println("*** ERROR -> defenders must either be a 2(for allies) or 4(for axis) or 'allies' or 'axis' values"); - } - } - } - - alliedSpawnPoints = loadSpawnPoint(config, "alliedSpawnPoints"); - axisSpawnPoints = loadSpawnPoint(config, "axisSpawnPoints"); - if(config.hasObject("minimumObjectivesToComplete")) { - minimumObjectivesToComplete = config.getObject("minimumObjectivesToComplete").asInt(); - } - else { - minimumObjectivesToComplete = objectives.size(); - } + + return new ObjectiveGameType(getRuntime(), objectives, alliedSpawnPoints, axisSpawnPoints, + minimumObjectivesToComplete, maxScore, matchTime, timeBetweenRounds, defenders); + + } + + private int checkMinumumObjectCompleteSize(List objectives, LeoObject config) { + int minimumObjectivesToComplete; + if (config.hasObject("minimumObjectivesToComplete")) { + minimumObjectivesToComplete = config.getObject("minimumObjectivesToComplete").asInt(); + } else { + minimumObjectivesToComplete = objectives.size(); + } + return minimumObjectivesToComplete; + } + + private void addscriptedObjectives(List objectives, LeoObject config) throws Exception { + LeoObject scriptedObjectives = config.getObject("objectives"); + if (LeoObject.isTrue(scriptedObjectives)) { + loadscriptObjectCase(objectives, scriptedObjectives); + } + } + private void loadscriptObjectCase(List objectives, LeoObject scriptedObjectives) throws Exception{ + switch (scriptedObjectives.getType()) { + case ARRAY: { + addAllLeoObjectValues(objectives, scriptedObjectives); + break; + } + case NATIVE_CLASS: { + addNativeClassObjectValues(objectives, scriptedObjectives); + break; + } + default: { + throw new NonObjectTypeException(); + } + } + } + + private byte addScriptedDenfenders(byte defenders, LeoObject config) throws Exception { + LeoObject scriptedDefenders = config.getObject("defenders"); + if (LeoObject.isTrue(scriptedDefenders)) { + defenders = loadscriptedDefenderCase(defenders, scriptedDefenders); + } + return defenders; + } + + private byte loadscriptedDefenderCase(byte defenders, LeoObject scriptedDefenders)throws Exception { + switch (scriptedDefenders.getType()) { + case INTEGER: + case LONG: + case REAL: + defenders = (byte) scriptedDefenders.asInt(); + break; + case STRING: + if (Team.ALLIED_TEAM_NAME.equalsIgnoreCase(scriptedDefenders.toString())) { + defenders = Team.ALLIED_TEAM_ID; } + break; + default: { + throw new NonDefenderTypeException(); } - - final long timeBetweenRounds = 10_000L; - - GameType gameType = new ObjectiveGameType(getRuntime(), objectives, alliedSpawnPoints, axisSpawnPoints, - minimumObjectivesToComplete, maxScore, matchTime, timeBetweenRounds, defenders); - return gameType; + } + return defenders; + } + + + private void addAllLeoObjectValues(List objectives, LeoObject scriptedObjectives) throws Exception { + LeoArray array = scriptedObjectives.as(); + for (int i = 0; i < array.size(); i++) { + addLeoObjectValues(objectives, array, i); + } + } + + private void addNativeClassObjectValues(List objectives, LeoObject scriptedObjectives)throws Exception { + LeoObject o = scriptedObjectives; + addObjectValue(objectives, o); + } + + + private void addLeoObjectValues(List objectives, LeoArray array, int i) throws Exception { + LeoObject o = array.get(i); + if (o instanceof LeoNativeClass) { + addObjectValue(objectives, o); + } + } + private void addObjectValue(List objectives, LeoObject o) throws NonLeoNativeTypeException { + if (o.getValue() instanceof Objective) { + objectives.add((Objective)o.getValue()); + } else { + printNonNativeClassTypeToConsole(o); + throw new NonLeoNativeTypeException(); + } + } + + + private void printNonNativeClassTypeToConsole(LeoObject o) { + Cons.println(((LeoNativeClass) o).getNativeClass() + " is not of type: "+ Objective.class.getName()); } } From 113af0be606e5f01ac8084e4aed012dbfe8a9503 Mon Sep 17 00:00:00 2001 From: cokacider Date: Sun, 6 May 2018 18:32:23 +0900 Subject: [PATCH 14/47] Refactoring getClassDescription method Refactoring operation: -Replace Data Value with Object -Form Template Method Refactoring target: -getClassDescription method to reduce duplicated codes if new descriptions of weapons are added, you can simply add a new subclass without touching the existing code --- .../client/gfx/WeaponClassDescription.java | 241 ++++++++++++++++++ src/seventh/client/gfx/WeaponClassDialog.java | 38 +-- 2 files changed, 251 insertions(+), 28 deletions(-) create mode 100644 src/seventh/client/gfx/WeaponClassDescription.java diff --git a/src/seventh/client/gfx/WeaponClassDescription.java b/src/seventh/client/gfx/WeaponClassDescription.java new file mode 100644 index 0000000..568bff4 --- /dev/null +++ b/src/seventh/client/gfx/WeaponClassDescription.java @@ -0,0 +1,241 @@ +package seventh.client.gfx; + +public abstract class WeaponClassDescription { + + protected static final String THOMPSON = "Thompson | 30/180 rnds"; + protected static final String M1_GARAND = "M1 Garand | 8/40 rnds"; + protected static final String SPRINGFIELD = "Springfield | 5/35 rnds"; + protected static final String MP40 = "MP40 | 32/160 rnds"; + protected static final String MP44 = "MP44 | 30/120 rnds"; + protected static final String KAR98 = "KAR-98 | 5/25 rnds"; + protected static final String RISKER = "MG-z | 21/42 rnds"; + protected static final String SHOTGUN = "Shotgun | 5/35 rnds"; + protected static final String ROCKET_LAUNCHER = "M1 | 5 rnds"; + protected static final String FLAME_THROWER = "Flame Thrower"; + + protected static final String PISTOL = "Pistol | 9/27 rnds"; + + public String getDescription() { + String description = ""; + boolean nothingInMessage = true; + + String mainWeaponMessage = getMainWeaponMessage(); + String subWeaponMessage = getSubWeaponMessage(); + String grenadeMassege = getGrenadeMessage(); + + if (mainWeaponMessage != null) { + description += mainWeaponMessage; + nothingInMessage = false; + } + + if (subWeaponMessage != null) { + if (!nothingInMessage) + description += "\n"; + description += subWeaponMessage; + nothingInMessage = false; + } + + if (grenadeMassege != null) { + if (!nothingInMessage) + description += "\n"; + description += grenadeMassege; + nothingInMessage = false; + } + + return description; + } + + protected abstract String getMainWeaponMessage(); + protected abstract String getSubWeaponMessage(); + protected abstract String getGrenadeMessage(); +} + +class ThompsonDescription extends WeaponClassDescription { + + @Override + protected String getMainWeaponMessage() { + return THOMPSON; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "2 Frag Grenades"; + } + +} + +class M1GarandDescription extends WeaponClassDescription { + + @Override + protected String getMainWeaponMessage() { + return M1_GARAND; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "2 Smoke Grenades"; + } + +} + +class SpringfieldDescription extends WeaponClassDescription { + + @Override + protected String getMainWeaponMessage() { + return SPRINGFIELD; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "1 Frag Grenades"; + } + +} + +class Mp40Description extends WeaponClassDescription { + + @Override + protected String getMainWeaponMessage() { + return MP40; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "2 Frag Grenades"; + } + +} + +class Mp44Description extends WeaponClassDescription { + + @Override + protected String getMainWeaponMessage() { + return MP44; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "2 Smoke Grenades"; + } + +} + +class Kar98Description extends WeaponClassDescription { + + @Override + protected String getMainWeaponMessage() { + return KAR98; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "1 Frag Grenade"; + } + +} + +class RiskerDescription extends WeaponClassDescription { + + @Override + protected String getMainWeaponMessage() { + return RISKER; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return null; + } + +} + +class ShotgunDescription extends WeaponClassDescription { + + @Override + protected String getMainWeaponMessage() { + return SHOTGUN; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return null; + } + +} + +class RocketLauncherDescription extends WeaponClassDescription { + + @Override + protected String getMainWeaponMessage() { + return ROCKET_LAUNCHER; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "5 Frag Grenades"; + } + +} + +class FlameThrowerDescription extends WeaponClassDescription { + + @Override + protected String getMainWeaponMessage() { + return FLAME_THROWER; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "2 Frag Grenades"; + } + +} \ No newline at end of file diff --git a/src/seventh/client/gfx/WeaponClassDialog.java b/src/seventh/client/gfx/WeaponClassDialog.java index 9f21e85..6295eb0 100644 --- a/src/seventh/client/gfx/WeaponClassDialog.java +++ b/src/seventh/client/gfx/WeaponClassDialog.java @@ -232,52 +232,34 @@ private String getClassDescription(Type type) { String message = ""; switch(type) { case THOMPSON: - message = "Thompson | 30/180 rnds\n" + - "Pistol | 9/27 rnds \n" + - "2 Frag Grenades"; + message = new ThompsonDescription().getDescription(); break; case M1_GARAND: - message = "M1 Garand | 8/40 rnds\n" + - "Pistol | 9/27 rnds \n" + - "2 Smoke Grenades"; + message = new M1GarandDescription().getDescription(); break; case SPRINGFIELD: - message = "Springfield | 5/35 rnds\n" + - "Pistol | 9/27 rnds \n" + - "1 Frag Grenades"; + message = new SpringfieldDescription().getDescription(); break; case MP40: - message = "MP40 | 32/160 rnds\n" + - "Pistol | 9/27 rnds \n" + - "2 Frag Grenades"; + message = new Mp40Description().getDescription(); break; case MP44: - message = "MP44 | 30/120 rnds\n" + - "Pistol | 9/27 rnds \n" + - "2 Smoke Grenades"; + message = new Mp44Description().getDescription(); break; case KAR98: - message = "KAR-98 | 5/25 rnds\n" + - "Pistol | 9/27 rnds \n" + - "1 Frag Grenade"; + message = new Kar98Description().getDescription(); break; case RISKER: - message = "MG-z | 21/42 rnds\n" + - "Pistol | 9/27 rnds"; + message = new RiskerDescription().getDescription(); break; case SHOTGUN: - message = "Shotgun | 5/35 rnds\n" + - "Pistol | 9/27 rnds"; + message = new ShotgunDescription().getDescription(); break; case ROCKET_LAUNCHER: - message = "M1 | 5 rnds\n" + - "Pistol | 9/27 rnds\n" + - "5 Frag Grenades"; + message = new RocketLauncherDescription().getDescription(); break; case FLAME_THROWER: - message = "Flame Thrower\n" + - "Pistol | 9/27 rnds\n" + - "2 Frag Grenades"; + message = new FlameThrowerDescription().getDescription(); break; default:; } From 26724753954a58379d050521c16526809ee9db80 Mon Sep 17 00:00:00 2001 From: cokacider Date: Sun, 6 May 2018 19:22:37 +0900 Subject: [PATCH 15/47] convert all tabs in WeaponClassDescription.java to 4 spaces --- .../client/gfx/WeaponClassDescription.java | 380 +++++++++--------- 1 file changed, 190 insertions(+), 190 deletions(-) diff --git a/src/seventh/client/gfx/WeaponClassDescription.java b/src/seventh/client/gfx/WeaponClassDescription.java index 568bff4..3a892d5 100644 --- a/src/seventh/client/gfx/WeaponClassDescription.java +++ b/src/seventh/client/gfx/WeaponClassDescription.java @@ -2,47 +2,47 @@ public abstract class WeaponClassDescription { - protected static final String THOMPSON = "Thompson | 30/180 rnds"; - protected static final String M1_GARAND = "M1 Garand | 8/40 rnds"; - protected static final String SPRINGFIELD = "Springfield | 5/35 rnds"; - protected static final String MP40 = "MP40 | 32/160 rnds"; - protected static final String MP44 = "MP44 | 30/120 rnds"; - protected static final String KAR98 = "KAR-98 | 5/25 rnds"; - protected static final String RISKER = "MG-z | 21/42 rnds"; - protected static final String SHOTGUN = "Shotgun | 5/35 rnds"; - protected static final String ROCKET_LAUNCHER = "M1 | 5 rnds"; - protected static final String FLAME_THROWER = "Flame Thrower"; - - protected static final String PISTOL = "Pistol | 9/27 rnds"; - + protected static final String THOMPSON = "Thompson | 30/180 rnds"; + protected static final String M1_GARAND = "M1 Garand | 8/40 rnds"; + protected static final String SPRINGFIELD = "Springfield | 5/35 rnds"; + protected static final String MP40 = "MP40 | 32/160 rnds"; + protected static final String MP44 = "MP44 | 30/120 rnds"; + protected static final String KAR98 = "KAR-98 | 5/25 rnds"; + protected static final String RISKER = "MG-z | 21/42 rnds"; + protected static final String SHOTGUN = "Shotgun | 5/35 rnds"; + protected static final String ROCKET_LAUNCHER = "M1 | 5 rnds"; + protected static final String FLAME_THROWER = "Flame Thrower"; + + protected static final String PISTOL = "Pistol | 9/27 rnds"; + public String getDescription() { - String description = ""; - boolean nothingInMessage = true; - - String mainWeaponMessage = getMainWeaponMessage(); - String subWeaponMessage = getSubWeaponMessage(); - String grenadeMassege = getGrenadeMessage(); - - if (mainWeaponMessage != null) { - description += mainWeaponMessage; - nothingInMessage = false; - } - - if (subWeaponMessage != null) { - if (!nothingInMessage) - description += "\n"; - description += subWeaponMessage; - nothingInMessage = false; - } - - if (grenadeMassege != null) { - if (!nothingInMessage) - description += "\n"; - description += grenadeMassege; - nothingInMessage = false; - } - - return description; + String description = ""; + boolean nothingInMessage = true; + + String mainWeaponMessage = getMainWeaponMessage(); + String subWeaponMessage = getSubWeaponMessage(); + String grenadeMassege = getGrenadeMessage(); + + if (mainWeaponMessage != null) { + description += mainWeaponMessage; + nothingInMessage = false; + } + + if (subWeaponMessage != null) { + if (!nothingInMessage) + description += "\n"; + description += subWeaponMessage; + nothingInMessage = false; + } + + if (grenadeMassege != null) { + if (!nothingInMessage) + description += "\n"; + description += grenadeMassege; + nothingInMessage = false; + } + + return description; } protected abstract String getMainWeaponMessage(); @@ -52,190 +52,190 @@ public String getDescription() { class ThompsonDescription extends WeaponClassDescription { - @Override - protected String getMainWeaponMessage() { - return THOMPSON; - } - - @Override - protected String getSubWeaponMessage() { - return PISTOL; - } - - @Override - protected String getGrenadeMessage() { - return "2 Frag Grenades"; - } - + @Override + protected String getMainWeaponMessage() { + return THOMPSON; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "2 Frag Grenades"; + } + } class M1GarandDescription extends WeaponClassDescription { - @Override - protected String getMainWeaponMessage() { - return M1_GARAND; - } - - @Override - protected String getSubWeaponMessage() { - return PISTOL; - } - - @Override - protected String getGrenadeMessage() { - return "2 Smoke Grenades"; - } - + @Override + protected String getMainWeaponMessage() { + return M1_GARAND; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "2 Smoke Grenades"; + } + } class SpringfieldDescription extends WeaponClassDescription { - @Override - protected String getMainWeaponMessage() { - return SPRINGFIELD; - } - - @Override - protected String getSubWeaponMessage() { - return PISTOL; - } - - @Override - protected String getGrenadeMessage() { - return "1 Frag Grenades"; - } - + @Override + protected String getMainWeaponMessage() { + return SPRINGFIELD; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "1 Frag Grenades"; + } + } class Mp40Description extends WeaponClassDescription { - @Override - protected String getMainWeaponMessage() { - return MP40; - } - - @Override - protected String getSubWeaponMessage() { - return PISTOL; - } - - @Override - protected String getGrenadeMessage() { - return "2 Frag Grenades"; - } - + @Override + protected String getMainWeaponMessage() { + return MP40; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "2 Frag Grenades"; + } + } class Mp44Description extends WeaponClassDescription { - @Override - protected String getMainWeaponMessage() { - return MP44; - } - - @Override - protected String getSubWeaponMessage() { - return PISTOL; - } - - @Override - protected String getGrenadeMessage() { - return "2 Smoke Grenades"; - } - + @Override + protected String getMainWeaponMessage() { + return MP44; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "2 Smoke Grenades"; + } + } class Kar98Description extends WeaponClassDescription { - @Override - protected String getMainWeaponMessage() { - return KAR98; - } - - @Override - protected String getSubWeaponMessage() { - return PISTOL; - } - - @Override - protected String getGrenadeMessage() { - return "1 Frag Grenade"; - } - + @Override + protected String getMainWeaponMessage() { + return KAR98; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "1 Frag Grenade"; + } + } class RiskerDescription extends WeaponClassDescription { - @Override - protected String getMainWeaponMessage() { - return RISKER; - } - - @Override - protected String getSubWeaponMessage() { - return PISTOL; - } - - @Override - protected String getGrenadeMessage() { - return null; - } - + @Override + protected String getMainWeaponMessage() { + return RISKER; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return null; + } + } class ShotgunDescription extends WeaponClassDescription { - @Override - protected String getMainWeaponMessage() { - return SHOTGUN; - } - - @Override - protected String getSubWeaponMessage() { - return PISTOL; - } - - @Override - protected String getGrenadeMessage() { - return null; - } - + @Override + protected String getMainWeaponMessage() { + return SHOTGUN; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return null; + } + } class RocketLauncherDescription extends WeaponClassDescription { - @Override - protected String getMainWeaponMessage() { - return ROCKET_LAUNCHER; - } - - @Override - protected String getSubWeaponMessage() { - return PISTOL; - } - - @Override - protected String getGrenadeMessage() { - return "5 Frag Grenades"; - } - + @Override + protected String getMainWeaponMessage() { + return ROCKET_LAUNCHER; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "5 Frag Grenades"; + } + } class FlameThrowerDescription extends WeaponClassDescription { - @Override - protected String getMainWeaponMessage() { - return FLAME_THROWER; - } - - @Override - protected String getSubWeaponMessage() { - return PISTOL; - } - - @Override - protected String getGrenadeMessage() { - return "2 Frag Grenades"; - } - + @Override + protected String getMainWeaponMessage() { + return FLAME_THROWER; + } + + @Override + protected String getSubWeaponMessage() { + return PISTOL; + } + + @Override + protected String getGrenadeMessage() { + return "2 Frag Grenades"; + } + } \ No newline at end of file From 05a1c3bc699d379c1e375c337f8de9499f024730 Mon Sep 17 00:00:00 2001 From: virginbabylon Date: Sun, 6 May 2018 23:06:34 +0900 Subject: [PATCH 16/47] 1.extract method, move method 2.ClienteGame.java public void applyGameUpdate() Game.java public void update() public boolean playerSwitchedTeam() PlayerAwardSystem.java public void roundEnded() public void addKill() 3.too many functions, duplicated codes in one method --- src/seventh/client/ClientGame.java | 121 ++++++++------ src/seventh/game/Game.java | 205 ++++++++++++++++-------- src/seventh/game/PlayerAwardSystem.java | 92 ++++++----- 3 files changed, 264 insertions(+), 154 deletions(-) diff --git a/src/seventh/client/ClientGame.java b/src/seventh/client/ClientGame.java index c16621c..a76b658 100644 --- a/src/seventh/client/ClientGame.java +++ b/src/seventh/client/ClientGame.java @@ -526,7 +526,7 @@ private void renderWorld(Canvas canvas, Camera camera, float alpha) { gameEffects.renderForeground(canvas, camera, alpha); map.renderForeground(canvas, camera, alpha); - canvas.setColor(0, 45); + canvas.setColor(0, 75); map.renderSolid(canvas, camera, alpha); gameEffects.renderLightSystem(canvas, camera, alpha); @@ -1292,43 +1292,31 @@ public void applyGameUpdate(GameUpdateMessage msg) { gameClock = netUpdate.time; - if(netUpdate.entities != null) { - int size = netUpdate.entities.length; - for(int i = 0; i < size; i++) { - NetEntity netEnt = netUpdate.entities[i]; - if(netEnt != null) { - if(entities.containsEntity(netEnt.id)) { - ClientEntity ent = entities.getEntity(netEnt.id); - if(netEnt.type == ent.getType()) { - ent.updateState(netEnt, gameClock); - } - else { - removeEntity(i); - createEntity(netEnt); - } - } - else { - createEntity(netEnt); - } - } - else { - - if( i < SeventhConstants.MAX_PERSISTANT_ENTITIES) { - /* if a persistant entity has been removed, lets - * remove it on the client side - */ - if(netUpdate.deadPersistantEntities.getBit(i)) { - removeEntity(i); - } - } - else { - removeEntity(i); - } + updateEntity(netUpdate); + + updateSound(netUpdate); + + updateSpectator(netUpdate); + } + + private void updateSpectator(NetGameUpdate netUpdate) { + if(netUpdate.spectatingPlayerId > -1 && !cameraController.isCameraRoaming()) { + int previousSpec = localPlayer.getSpectatingPlayerId(); + localPlayer.setSpectatingPlayerId(netUpdate.spectatingPlayerId); + if(previousSpec != netUpdate.spectatingPlayerId) { + ClientEntity ent = this.entities.getEntity(netUpdate.spectatingPlayerId); + if(ent!=null) { + camera.centerAroundNow(ent.getCenterPos()); } } } - - if(netUpdate.sounds != null) { + else { + localPlayer.setSpectatingPlayerId(Entity.INVALID_ENTITY_ID); + } + } + + private void updateSound(NetGameUpdate netUpdate) { + if(netUpdate.sounds != null) { int size = netUpdate.numberOfSounds; for(int i = 0; i < size; i++) { NetSound snd = netUpdate.sounds[i]; @@ -1394,21 +1382,45 @@ public void applyGameUpdate(GameUpdateMessage msg) { } } } - - if(netUpdate.spectatingPlayerId > -1 && !cameraController.isCameraRoaming()) { - int previousSpec = localPlayer.getSpectatingPlayerId(); - localPlayer.setSpectatingPlayerId(netUpdate.spectatingPlayerId); - if(previousSpec != netUpdate.spectatingPlayerId) { - ClientEntity ent = this.entities.getEntity(netUpdate.spectatingPlayerId); - if(ent!=null) { - camera.centerAroundNow(ent.getCenterPos()); + } + + private void updateEntity(NetGameUpdate netUpdate) { + if(netUpdate.entities != null) { + int size = netUpdate.entities.length; + for(int i = 0; i < size; i++) { + NetEntity netEnt = netUpdate.entities[i]; + if(netEnt != null) { + if(entities.containsEntity(netEnt.id)) { + ClientEntity ent = entities.getEntity(netEnt.id); + if(netEnt.type == ent.getType()) { + ent.updateState(netEnt, gameClock); + } + else { + removeEntity(i); + createEntity(netEnt); + } + } + else { + createEntity(netEnt); + } + } + else { + + if( i < SeventhConstants.MAX_PERSISTANT_ENTITIES) { + /* if a persistant entity has been removed, lets + * remove it on the client side + */ + if(netUpdate.deadPersistantEntities.getBit(i)) { + removeEntity(i); + } + } + else { + removeEntity(i); + } } } } - else { - localPlayer.setSpectatingPlayerId(Entity.INVALID_ENTITY_ID); - } - } + } public void applyGameStats(NetGameStats stats) { if(stats.playerStats != null) { @@ -1852,9 +1864,11 @@ public void flagCaptured(FlagCapturedMessage msg) { if(player!=null) { if(player.getTeam().equals(this.localPlayer.getTeam())) { Sounds.playGlobalSound(Sounds.flagCaptured); + postMessage("Flag captured!"); } else { Sounds.playGlobalSound(Sounds.enemyFlagCaptured); + postMessage("Enemy flag captured!"); } } } @@ -1869,9 +1883,11 @@ public void flagStolen(FlagStolenMessage msg) { if(player!=null) { if(player.getTeam().equals(this.localPlayer.getTeam())) { Sounds.playGlobalSound(Sounds.flagStolen); + postMessage("Flag stolen!"); } else { Sounds.playGlobalSound(Sounds.enemyFlagStolen); + postMessage("Enemy flag stolen!"); } } } @@ -1880,6 +1896,17 @@ public void flagStolen(FlagStolenMessage msg) { public void flagReturned(FlagReturnedMessage msg) { Sounds.playGlobalSound(Sounds.flagCaptured); + if(this.localPlayer != null) { + ClientPlayer player = this.players.getPlayer(msg.returnedBy); + if(player!=null) { + if(player.getTeam().equals(this.localPlayer.getTeam())) { + postMessage("Flag returned!"); + } + else { + postMessage("Enemy flag returned!"); + } + } + } } /** diff --git a/src/seventh/game/Game.java b/src/seventh/game/Game.java index 5306c5a..7b493eb 100644 --- a/src/seventh/game/Game.java +++ b/src/seventh/game/Game.java @@ -814,7 +814,17 @@ public GameType getGameType() { */ @Override public void update(TimeStep timeStep) { - for(int i = 0; i < entities.length; i++) { + updateEntity(timeStep); + this.aiSystem.update(timeStep); + this.gameTimers.update(timeStep); + this.gameTriggers.update(timeStep); + this.gameType.update(this, timeStep); + this.time = this.gameType.getRemainingTime(); + } + + + private void updateEntity(TimeStep timeStep) { + for(int i = 0; i < entities.length; i++) { Entity ent = entities[i]; if(ent!=null) { if(ent.isAlive()) { @@ -831,15 +841,8 @@ public void update(TimeStep timeStep) { else { deadFrames[i]++; } - } - - this.aiSystem.update(timeStep); - this.gameTimers.update(timeStep); - this.gameTriggers.update(timeStep); - - this.gameType.update(this, timeStep); - this.time = this.gameType.getRemainingTime(); - } + } + } /** * Invoked after an update, a hack to work @@ -957,7 +960,9 @@ public Vector2f findFreeSpot(PlayerEntity player) { int safety = 100000; while((map.rectCollides(player.getBounds()) || - map.hasWorldCollidableTile((int)player.getCenterPos().x, (int)player.getCenterPos().y)) && + map.hasWorldCollidableTile((int)player.getCenterPos().x, (int)player.getCenterPos().y) || + doesTouchOthers(player, false) || + doesTouchMapObject(player, false)) && safety>0) { int w = (player.getBounds().width + 5); @@ -1020,13 +1025,13 @@ public Vector2f findFreeRandomSpot(Entity entity, int x, int y, int width, int h } public Vector2f findFreeRandomSpot(Rectangle bounds, int x, int y, int width, int height) { - Vector2f pos = new Vector2f(x+random.nextInt(width), y+random.nextInt(height)); + Vector2f pos = new Vector2f(); Rectangle temp = new Rectangle(bounds); - temp.setLocation(pos); - + int loopChecker = 0; - while (map.rectCollides(temp) && !map.hasWorldCollidableTile(temp.x, temp.y) ) { + do { + pos.x = x + random.nextInt(width); pos.y = y + random.nextInt(height); temp.setLocation(pos); @@ -1036,6 +1041,9 @@ public Vector2f findFreeRandomSpot(Rectangle bounds, int x, int y, int width, in return null; } } + while(map.rectCollides(temp) || + map.hasWorldCollidableTile(temp.x, temp.y) || + doesTouchEntity(temp)); return pos; } @@ -1055,10 +1063,21 @@ public Vector2f findFreeRandomSpotNotIn(Entity entity, int x, int y, int width, Rectangle temp = new Rectangle(entity.getBounds()); temp.setLocation(pos); - while ((map.rectCollides(temp) && !map.hasWorldCollidableTile(temp.x, temp.y)) || notIn.intersects(temp)) { + int loopChecker = 0; + + while (map.rectCollides(temp) || + map.hasWorldCollidableTile(temp.x, temp.y) || + doesTouchEntity(temp) || + notIn.intersects(temp)) { + pos.x = x + random.nextInt(width); pos.y = y + random.nextInt(height); temp.setLocation(pos); + + // this bounds doesn't have a free spot + if(loopChecker++ > 500_000) { + return null; + } } return pos; @@ -1081,6 +1100,7 @@ public Vector2f findFreeRandomSpotNotIn(Entity entity, Rectangle bounds, OBB not } while (map.rectCollides(temp) || map.hasWorldCollidableTile(temp.x, temp.y) || + doesTouchEntity(temp) || notIn.expensiveIntersects(temp)); return pos; @@ -1266,52 +1286,56 @@ public boolean playerSwitchedTeam(int playerId, byte teamId) { if(Team.SPECTATOR_TEAM_ID != teamId) { player.stopSpectating(); } - - /* make sure the player has the teams weaponry */ - switch(player.getWeaponClass()) { - case THOMPSON: - player.setWeaponClass(Type.MP40); - break; - case MP40: - player.setWeaponClass(Type.THOMPSON); - break; - - case KAR98: - player.setWeaponClass(Type.SPRINGFIELD); - break; - case SPRINGFIELD: - player.setWeaponClass(Type.KAR98); - break; - - case MP44: - player.setWeaponClass(Type.M1_GARAND); - break; - case M1_GARAND: - player.setWeaponClass(Type.MP44); - - case SHOTGUN: - case ROCKET_LAUNCHER: - case RISKER: - case FLAME_THROWER: - break; - - /* make the player use the default weapon */ - default: { - switch(teamId) { - case Team.ALLIED_TEAM_ID: - player.setWeaponClass(Type.THOMPSON); - break; - case Team.AXIS_TEAM_ID: - player.setWeaponClass(Type.MP40); - break; - } - } - } + switchWeaponByTeam(teamId, player); } } return playerSwitched; } + + + private void switchWeaponByTeam(byte teamId, Player player) { + /* make sure the player has the teams weaponry */ + switch(player.getWeaponClass()) { + case THOMPSON: + player.setWeaponClass(Type.MP40); + break; + case MP40: + player.setWeaponClass(Type.THOMPSON); + break; + + case KAR98: + player.setWeaponClass(Type.SPRINGFIELD); + break; + case SPRINGFIELD: + player.setWeaponClass(Type.KAR98); + break; + + case MP44: + player.setWeaponClass(Type.M1_GARAND); + break; + case M1_GARAND: + player.setWeaponClass(Type.MP44); + + case SHOTGUN: + case ROCKET_LAUNCHER: + case RISKER: + case FLAME_THROWER: + break; + + /* make the player use the default weapon */ + default: { + switch(teamId) { + case Team.ALLIED_TEAM_ID: + break; + player.setWeaponClass(Type.THOMPSON); + case Team.AXIS_TEAM_ID: + player.setWeaponClass(Type.MP40); + break; + } + } + } + } /** * A player has requested to switch its weapon class @@ -1639,8 +1663,8 @@ public Bomb newBomb(BombTarget target) { * @param position * @return the bomb target */ - public BombTarget newBombTarget(Vector2f position) { - final BombTarget target = new BombTarget(position, this); + public BombTarget newBombTarget(Team owner, Vector2f position) { + final BombTarget target = new BombTarget(owner, position, this); target.onKill = new KilledListener() { @Override @@ -1937,15 +1961,20 @@ public boolean doesVehicleTouchPlayers(Vehicle vehicle) { return false; } - /* (non-Javadoc) - * @see seventh.game.GameInfo#doesTouchOthers(seventh.game.Entity) - */ @Override public boolean doesTouchOthers(Entity ent) { - for(int i = 0; i < this.entities.length; i++) { - Entity other = this.entities[i]; + return doesTouchOthers(ent, true); + } + + @Override + public boolean doesTouchOthers(Entity ent, boolean invokeTouch) { + for(int i = 0; i < this.vehicles.size(); i++) { + Entity other = this.vehicles.get(i); if(other != null) { - if(other != ent && /*other.bounds.intersects(ent.bounds)*/ ent.isTouching(other)) { + if(other != ent && other.isTouching(ent)) { + if(!invokeTouch) { + return true; + } if(ent.onTouch != null) { ent.onTouch.onTouch(ent, other); return true; @@ -1954,6 +1983,36 @@ public boolean doesTouchOthers(Entity ent) { } } + for(int i = 0; i < this.doors.size(); i++) { + Entity other = this.doors.get(i); + if(other != null) { + if(other != ent && other.isTouching(ent)) { + if(!invokeTouch) { + return true; + } + if(ent.onTouch != null) { + ent.onTouch.onTouch(ent, other); + return true; + } + } + } + } + + + return false; + } + + @Override + public boolean doesTouchEntity(Rectangle bounds) { + for(int i = 0; i < this.entities.length; i++) { + Entity other = this.entities[i]; + if(other != null) { + if(bounds.intersects(other.getBounds())) { + return true; + } + } + } + return false; } @@ -1978,13 +2037,23 @@ public boolean doesTouchPlayers(Entity ent) { } public boolean doesTouchMapObject(Entity ent) { + return doesTouchMapObject(ent, true); + } + + public boolean doesTouchMapObject(Entity ent, boolean invokeTouch) { List mapObjects = getMapObjects(); for(int i = 0; i < mapObjects.size(); i++) { MapObject object = mapObjects.get(i); if(object.isCollidable()) { - if(object.isTouching(ent) && ent.onMapObjectTouch != null) { - ent.onMapObjectTouch.onTouch(ent, object); - return true; + if(object.isTouching(ent)) { + if(!invokeTouch) { + return true; + } + + if(ent.onMapObjectTouch != null) { + ent.onMapObjectTouch.onTouch(ent, object); + return true; + } } } } diff --git a/src/seventh/game/PlayerAwardSystem.java b/src/seventh/game/PlayerAwardSystem.java index eac9f37..551d9b4 100644 --- a/src/seventh/game/PlayerAwardSystem.java +++ b/src/seventh/game/PlayerAwardSystem.java @@ -96,26 +96,12 @@ public void roundReset() { } public void roundEnded() { - if(deaths == 0) { - if(kills == 0) { - // send out coward award - dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Coward)); - } - else if(kills < 5) { - // send out - dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Excellence)); - } - else if(kills < 10) { - // send out - dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.BeastMode)); - } - else { - // send out - dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.FavreMode)); - } - } - - float ratio = 1.0f; + awardByKill(); + awardByRatio(); + } + + private void awardByRatio() { + float ratio = 1.0f; if(deaths>0) { ratio = kills / deaths; } @@ -136,27 +122,40 @@ else if(ratio > .60f) { dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Marksman)); } } - - } + } + + private void awardByKill() { + if(deaths == 0) { + if(kills == 0) { + // send out coward award + dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Coward)); + } + else if(kills < 5) { + // send out + dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Excellence)); + } + else if(kills < 10) { + // send out + dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.BeastMode)); + } + else { + // send out + dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.FavreMode)); + } + } + } public void addKill() { - this.killStreak++; - if(this.killStreak > this.highestKillStreak) { - this.highestKillStreak = this.killStreak; - } - - // if the kill streak is worthy, send out an event - switch(this.killStreak) { - case 3: - case 5: - case 10: - case 15: - dispatcher.queueEvent(new KillStreakEvent(this, player, this.killStreak)); - break; - } + awardByKillStreak(); // TODO - use game time, instead of wall time - long killTime = System.currentTimeMillis(); + awardByKillRoll(); + + this.kills++; + } + + private void awardByKillRoll() { + long killTime = System.currentTimeMillis(); if(killTime-this.lastKillTime < 3000) { this.killRoll++; @@ -171,9 +170,24 @@ public void addKill() { } this.lastKillTime = killTime; + } + + private void awardByKillStreak() { + this.killStreak++; + if(this.killStreak > this.highestKillStreak) { + this.highestKillStreak = this.killStreak; + } - this.kills++; - } + // if the kill streak is worthy, send out an event + switch(this.killStreak) { + case 3: + case 5: + case 10: + case 15: + dispatcher.queueEvent(new KillStreakEvent(this, player, this.killStreak)); + break; + } + } public void addDeath() { this.killStreak = 0; From d5814e2754e1d1945efd1bd83a62c2464e0b1b1b Mon Sep 17 00:00:00 2001 From: aikaran Date: Mon, 7 May 2018 00:33:33 +0900 Subject: [PATCH 17/47] add function comment --- src/seventh/ui/view/ProgressBarView.java | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/seventh/ui/view/ProgressBarView.java b/src/seventh/ui/view/ProgressBarView.java index 56c567a..9cde15d 100644 --- a/src/seventh/ui/view/ProgressBarView.java +++ b/src/seventh/ui/view/ProgressBarView.java @@ -51,6 +51,12 @@ public void render(Canvas canvas, Camera camera, float alpha) { } } + /** + * add a shadow effect on canvas with a rectangle bounds + * + * @param canvas + * @param bounds + */ private void addAShadowEffect(Canvas canvas, Rectangle bounds) { int x = bounds.x; int y = bounds.y; From f52efe1aaeae7f09459b699fcbcab97ec1f5d1e6 Mon Sep 17 00:00:00 2001 From: aikaran Date: Mon, 7 May 2018 00:49:37 +0900 Subject: [PATCH 18/47] Refactoring : Extract Method Target : ClientMain class in seventh Reason : I extracted the source codes by function. --- src/seventh/ClientMain.java | 34 ++++++++++++++++++++++++++++++---- 1 file changed, 30 insertions(+), 4 deletions(-) diff --git a/src/seventh/ClientMain.java b/src/seventh/ClientMain.java index 715e148..9cedd67 100644 --- a/src/seventh/ClientMain.java +++ b/src/seventh/ClientMain.java @@ -185,15 +185,34 @@ public static void logVideoSpecs(Logger console) { * @param console */ public static void logSystemSpecs(Logger console) { - Runtime runtime = Runtime.getRuntime(); + logSystemSpecsRuntime(console); + logSystemSpecsFileSystem(console); + logSystemSpecsSystemProperty(console); + } + + /** + * Prints out system specifications about runtime + * + * @param console + */ + private logSystemSpecsRuntime(Logger console) { final long MB = 1024 * 1024; + Runtime runtime = Runtime.getRuntime(); console.println(""); console.println("Seventh: " + SeventhGame.getVersion()); console.println("Available processors (cores): " + runtime.availableProcessors()); console.println("Free memory (MiB): " + runtime.freeMemory()/MB); console.println("Max memory (MiB): " + (runtime.maxMemory()==Long.MAX_VALUE ? "no limit" : Long.toString(runtime.maxMemory()/MB)) ); console.println("Available for JVM (MiB): " + runtime.totalMemory() / MB); - + } + + /** + * Prints out system specifications about filesystem root + * + * @param console + */ + private logSystemSpecsFileSystem(Logger console) { + final long MB = 1024 * 1024; /* Get a list of all filesystem roots on this system */ File[] roots = File.listRoots(); @@ -204,8 +223,15 @@ public static void logSystemSpecs(Logger console) { console.println("\tFree space (MiB): " + root.getFreeSpace()/MB); console.println("\tUsable space (MiB): " + root.getUsableSpace()/MB); } - - + } + + /** + * Prints out system specifications about system property + * + * @param console + */ + private logSystemSpecsSystemProperty(Logger console) { + final long MB = 1024 * 1024; console.println("Java Version: " + System.getProperty("java.version")); console.println("Java Vendor: " + System.getProperty("java.vendor")); console.println("Java VM Version: " + System.getProperty("java.vm.version")); From 7c3b799c98b150d110d7155bbc91411a4655495b Mon Sep 17 00:00:00 2001 From: bananapizza Date: Mon, 7 May 2018 10:29:12 +0900 Subject: [PATCH 19/47] 1. Refactoring Operation: Extract Method (contactDedicatedServer method) Refactoring Target: init method in GameServer class of seventh.server package Reason: to satisfy SRP 2. Refactoring Operation: Extract Method (printHeader,pringBody,printFooter method) Refactoring Target: dump method in BitPacker class of harenet package Reason: divide dump into 3 parts to satisfy SRP printFooter was duplicate code (dump,dumpBytes) 3. Refactoring Operation: Extract Method (removeDisconnectedPeer) Refactoring Target: disconnect method in Host class of harenet package Reason: decouple removing peer from disconnect to satisfy SRP --- src/harenet/BitPacker.java | 22 ++++++++++++---- src/harenet/Host.java | 26 ++++++++++++------- src/seventh/server/GameServer.java | 40 ++++++++++++++++++------------ 3 files changed, 58 insertions(+), 30 deletions(-) diff --git a/src/harenet/BitPacker.java b/src/harenet/BitPacker.java index 241f17c..89e73fb 100644 --- a/src/harenet/BitPacker.java +++ b/src/harenet/BitPacker.java @@ -559,16 +559,23 @@ public static void dumpBytes(byte[] value) { } } - System.out.println(); - System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); + printFooter(); } public void dump() { + printHeader(); + printBody(); + printFooter(); + } + + private void printHeader() { System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); System.out.println("| Dumping bitset, length: " + numBits); System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); + } - int count = 0; + private void printBody() { + int count = 0; for (int i = 0; i < numBits; i++) { System.out.print(data.getBit(i) ? "1" : "0"); @@ -583,8 +590,13 @@ public void dump() { } } - System.out.println(); + } + + private static void printFooter() { + System.out.println(); System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); - } + } + + } \ No newline at end of file diff --git a/src/harenet/Host.java b/src/harenet/Host.java index a1767a4..bd6e738 100644 --- a/src/harenet/Host.java +++ b/src/harenet/Host.java @@ -1,3 +1,4 @@ + /* * see license.txt */ @@ -279,19 +280,26 @@ void disconnect(Peer peer) { peers[id].send(new DisconnectMessage()); /* remove the peer if they are disconnected */ - if(peers[id].isDisconnected()) { - synchronized (this) { - peers[id] = null; - this.numberOfConnections--; - if(this.numberOfConnections < 0) { - this.numberOfConnections = 0; - } - } - } + removeDisconnetedPeer(id); } } } + /** + * @param id + */ + private void removeDisconnetedPeer(byte id) { + if(peers[id].isDisconnected()) { + synchronized (this) { + peers[id] = null; + this.numberOfConnections--; + if(this.numberOfConnections < 0) { + this.numberOfConnections = 0; + } + } + } + } + /** * Sends a {@link Message} to the peer * @param message diff --git a/src/seventh/server/GameServer.java b/src/seventh/server/GameServer.java index e027692..1b915c2 100644 --- a/src/seventh/server/GameServer.java +++ b/src/seventh/server/GameServer.java @@ -202,21 +202,7 @@ private void init(final ServerSeventhConfig config, /* if this is a dedicated server, we'll contact the * master server so that users know about this server */ - this.console.print("Initializing MasterServerRegistration..."); - this.registration = new MasterServerRegistration(this.serverContext); - if(settings.isDedicatedServer) { - this.registration.start(); - this.console.println("done!"); - } - else this.console.println(""); - - this.console.print("Initializing LANServerRegistration..."); - this.lanRegistration = new LANServerRegistration(this.serverContext); - if(settings.isLAN) { - this.lanRegistration.start(); - this.console.println("done!"); - } - else this.console.println(""); + contactDedicatedServer(settings.isDedicatedServer,settings.isLAN); /* attempt to attach a debugger */ if(config.isDebuggerEnabled()) { @@ -294,6 +280,28 @@ public void onExitState(State state) { console.println("Done initialzing the game server, ready to launch network..."); } + + + /** + * @param settings + */ + private void contactDedicatedServer(boolean isDedicatedServer,boolean isLAN) { + this.console.print("Initializing MasterServerRegistration..."); + this.registration = new MasterServerRegistration(this.serverContext); + if(isDedicatedServer) { + this.registration.start(); + this.console.println("done!"); + } + else this.console.println(""); + + this.console.print("Initializing LANServerRegistration..."); + this.lanRegistration = new LANServerRegistration(this.serverContext); + if(isLAN) { + this.lanRegistration.start(); + this.console.println("done!"); + } + else this.console.println(""); + } /** @@ -302,7 +310,7 @@ public void onExitState(State state) { * @param config * @return the {@link DebugableListener} if one is available, or null */ - private DebugableListener createDebugListener(ServerSeventhConfig config) { + private DebugableListener createDebugListener(ServerSeventhConfig config) { try { String className = config.getDebuggerClassName(); if(className != null && !"".equals(className)) { From 4140406810ea0e8664c3bc01a151d046ebe2d284 Mon Sep 17 00:00:00 2001 From: virginbabylon Date: Mon, 7 May 2018 10:54:12 +0900 Subject: [PATCH 20/47] 1.Replace Temp with Query 2.FastMath.java static public final int random() static public final float random() public static float a_sqrt public static float a_isqrt 3.placing the result of an expression in a local variable for later use in the code. --- src/seventh/math/FastMath.java | 35 +++++++++++++++++----------------- 1 file changed, 18 insertions(+), 17 deletions(-) diff --git a/src/seventh/math/FastMath.java b/src/seventh/math/FastMath.java index 0a4507e..6df2ffd 100644 --- a/src/seventh/math/FastMath.java +++ b/src/seventh/math/FastMath.java @@ -152,7 +152,7 @@ static public final float sqrt(float value) { * @return */ public static float a_isqrt(float x) { - float hx = x * 0.5f; + int ix; float r; @@ -164,7 +164,7 @@ public static float a_isqrt(float x) { // do some number of newton-ralphson steps, // each doubles the number of accurate // binary digits. - r = r * (1.5f - hx * r * r); + r = r * (1.5f - hx(x) * r * r); // r = r*(1.5f-hx*r*r); // r = r*(1.5f-hx*r*r); // r = r*(1.5f-hx*r*r); @@ -180,7 +180,6 @@ public static float a_isqrt(float x) { * @return */ public static float a_sqrt(float x) { - float hx = x * 0.5f; int ix; float r; @@ -192,7 +191,7 @@ public static float a_sqrt(float x) { // do some number of newton-ralphson steps, // each doubles the number of accurate // binary digits. - r = r * (1.5f - hx * r * r); + r = r * (1.5f - hx(x) * r * r); // r = r*(1.5f-hx*r*r); // r = r*(1.5f-hx*r*r); // r = r*(1.5f-hx*r*r); @@ -200,6 +199,11 @@ public static float a_sqrt(float x) { return r*x; // sqrt(x) } + private static float hx(float x) { + float hx = x * 0.5f; + return hx; + } + /** * Fixed point multiply. */ @@ -223,28 +227,25 @@ static public int divide(int x, int y) { * @param range * Must be >= 0. */ - static public final int random(int range) { - int seed = randomSeed * 1103515245 + 12345; + private static int seed() { + int seed = randomSeed * 1103515245 + 12345; randomSeed = seed; - return ((seed >>> 15) * (range + 1)) >>> 17; + return seed; + } + static public final int random(int range) { + return ((seed() >>> 15) * (range + 1)) >>> 17; } - + static public final int random(int start, int end) { - int seed = randomSeed * 1103515245 + 12345; - randomSeed = seed; - return (((seed >>> 15) * ((end - start) + 1)) >>> 17) + start; + return (((seed() >>> 15) * ((end - start) + 1)) >>> 17) + start; } static public final boolean randomBoolean() { - int seed = randomSeed * 1103515245 + 12345; - randomSeed = seed; - return seed > 0; + return seed() > 0; } static public final float random() { - int seed = randomSeed * 1103515245 + 12345; - randomSeed = seed; - return (seed >>> 8) * (1f / (1 << 24)); + return (seed() >>> 8) * (1f / (1 << 24)); } static public int nextPowerOfTwo(int value) { From 02d040b967528425b8584a6913467116c470e0a4 Mon Sep 17 00:00:00 2001 From: bananapizza Date: Mon, 7 May 2018 11:25:18 +0900 Subject: [PATCH 21/47] Extract printBitArray method to remove duplicate code. --- src/harenet/BitArray.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/harenet/BitArray.java b/src/harenet/BitArray.java index 32babe3..e8704c4 100644 --- a/src/harenet/BitArray.java +++ b/src/harenet/BitArray.java @@ -128,6 +128,10 @@ public int size() { return this.data.length * WORD_SIZE; } + public void printBitArray(BitArray bitArray) { + System.out.println("NumberOfBytes:" + bitArray.numberOfBytes() + " : " + bitArray.size() + " : " + bitArray); + } + public static void main(String[] args) { BitArray a = new BitArray(255); @@ -136,7 +140,7 @@ public static void main(String[] args) { a.setBit(i); } - System.out.println("NumberOfBytes:" + a.numberOfBytes() + " : " + a.size() + " : " + a); + printBitArray(a); BitArray b = new BitArray(SeventhConstants.MAX_PERSISTANT_ENTITIES - 1); @@ -145,6 +149,6 @@ public static void main(String[] args) { b.setBit(i); } - System.out.println("NumberOfBytes:" + b.numberOfBytes() + " : " + b.size() + " : " + b); + printBitArray(b); } } From 26f6245b1bb31b7122d72224891fd2314479864b Mon Sep 17 00:00:00 2001 From: bananapizza Date: Mon, 7 May 2018 12:34:41 +0900 Subject: [PATCH 22/47] Refactoring dumptBytes. --- src/harenet/BitPacker.java | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/harenet/BitPacker.java b/src/harenet/BitPacker.java index 89e73fb..55bae83 100644 --- a/src/harenet/BitPacker.java +++ b/src/harenet/BitPacker.java @@ -533,10 +533,19 @@ public BitPacker pad() { public static void dumpBytes(byte[] value) { + int length = value.length; + printByteHeader(length); + printByteBody(length); + printFooter(); + } + + private void printByteHeader(int length) { System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); - System.out.println("| Dumping bytes, length: " + (value.length * 8) + " (" + value.length + " byte(s))"); + System.out.println("| Dumping bytes, length: " + (length * 8) + " (" + length + " byte(s))"); System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); - + } + + private void printByteBody(int length) { int count = 0; for (int j = 0; j < value.length; j++) { @@ -559,7 +568,6 @@ public static void dumpBytes(byte[] value) { } } - printFooter(); } public void dump() { From 87cc6ab38b577c8b95f1976e45dfeb7e8e58f900 Mon Sep 17 00:00:00 2001 From: terry2511 Date: Mon, 7 May 2018 22:09:32 +0900 Subject: [PATCH 23/47] Refactoring ClientGame.java --- src/seventh/client/ClientGame.java | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/seventh/client/ClientGame.java b/src/seventh/client/ClientGame.java index c16621c..54fed39 100644 --- a/src/seventh/client/ClientGame.java +++ b/src/seventh/client/ClientGame.java @@ -1352,18 +1352,7 @@ public void applyGameUpdate(GameUpdateMessage msg) { /* dampen the sound of the local players footsteps, * otherwise it's too loud */ - switch(snd.getSoundType()) { - case SURFACE_DIRT: - case SURFACE_GRASS: - case SURFACE_METAL: - case SURFACE_NORMAL: - case SURFACE_SAND: - case SURFACE_WATER: - case SURFACE_WOOD: - Sounds.playSound(snd, pos.x, pos.y, 0.35f ); - break; - default: Sounds.playSound(snd, pos.x, pos.y ); - } + setSoundType(snd, pos); } else { Sounds.playSound(snd, pos.x, pos.y); @@ -1409,6 +1398,21 @@ public void applyGameUpdate(GameUpdateMessage msg) { localPlayer.setSpectatingPlayerId(Entity.INVALID_ENTITY_ID); } } + + private void setSoundType(NetSound snd, Vector2f pos) { + switch(snd.getSoundType()) { + case SURFACE_DIRT: + case SURFACE_GRASS: + case SURFACE_METAL: + case SURFACE_NORMAL: + case SURFACE_SAND: + case SURFACE_WATER: + case SURFACE_WOOD: + Sounds.playSound(snd, pos.x, pos.y, 0.35f ); + break; + default: Sounds.playSound(snd, pos.x, pos.y ); + } + } public void applyGameStats(NetGameStats stats) { if(stats.playerStats != null) { From 32c8b17bb168a03da53fc7fb19fd13209eccc34b Mon Sep 17 00:00:00 2001 From: virginbabylon Date: Mon, 7 May 2018 23:04:26 +0900 Subject: [PATCH 24/47] 1.extract method, move method 2.ClienteGame.java public void applyGameUpdate() Game.java public void update() public boolean playerSwitchedTeam() PlayerAwardSystem.java public void roundEnded() public void addKill() 3.too many functions, duplicated codes in one method 1.Replace Temp with Query 2.FastMath.java static public final int random() static public final float random() public static float a_sqrt public static float a_isqrt 3.placing the result of an expression in a local variable for later use in the code. --- src/seventh/client/ClientGame.java | 2 +- src/seventh/game/Game.java | 2 +- src/seventh/game/PlayerAwardSystem.java | 2 +- src/seventh/math/FastMath.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/seventh/client/ClientGame.java b/src/seventh/client/ClientGame.java index a76b658..7f2393b 100644 --- a/src/seventh/client/ClientGame.java +++ b/src/seventh/client/ClientGame.java @@ -116,7 +116,7 @@ * @author Tony * */ -public class ClientGame { +public class ClientGame { private final SeventhGame app; private final Map map; diff --git a/src/seventh/game/Game.java b/src/seventh/game/Game.java index 7b493eb..ad42294 100644 --- a/src/seventh/game/Game.java +++ b/src/seventh/game/Game.java @@ -821,7 +821,7 @@ public void update(TimeStep timeStep) { this.gameType.update(this, timeStep); this.time = this.gameType.getRemainingTime(); } - + private void updateEntity(TimeStep timeStep) { for(int i = 0; i < entities.length; i++) { diff --git a/src/seventh/game/PlayerAwardSystem.java b/src/seventh/game/PlayerAwardSystem.java index 551d9b4..860e69c 100644 --- a/src/seventh/game/PlayerAwardSystem.java +++ b/src/seventh/game/PlayerAwardSystem.java @@ -19,7 +19,7 @@ import seventh.shared.EventDispatcher; import seventh.shared.SeventhConstants; -/** +/** * Keeps track of player stats for kill streaks and bonuses * * @author Tony diff --git a/src/seventh/math/FastMath.java b/src/seventh/math/FastMath.java index 6df2ffd..09a92f7 100644 --- a/src/seventh/math/FastMath.java +++ b/src/seventh/math/FastMath.java @@ -13,7 +13,7 @@ * Riven on JavaGaming.org for sin/cos/atan2 tables.
* Roquen on JavaGaming.org for random numbers.
* pjt33 on JavaGaming.org for fixed point.
- * Jim Shima for atan2_fast.
+ * Jim Shima for atan2_fast.
* *

* Taken from JavaGaming.org from Nate From eb745b9b7dfe9f3a344874f237fa380c253c90ed Mon Sep 17 00:00:00 2001 From: virginbabylon Date: Mon, 7 May 2018 23:20:34 +0900 Subject: [PATCH 25/47] 1.extract method, move method 2.ClienteGame.java public void applyGameUpdate() Game.java public void update() public boolean playerSwitchedTeam() PlayerAwardSystem.java public void roundEnded() public void addKill() 3.too many functions, duplicated codes in one method 1.Replace Temp with Query 2.FastMath.java static public final int random() static public final float random() public static float a_sqrt public static float a_isqrt 3.placing the result of an expression in a local variable for later use in the code. --- src/seventh/client/ClientGame.java | 2 +- src/seventh/game/Game.java | 2 +- src/seventh/game/PlayerAwardSystem.java | 2 +- src/seventh/math/FastMath.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/seventh/client/ClientGame.java b/src/seventh/client/ClientGame.java index 7f2393b..b0cb07b 100644 --- a/src/seventh/client/ClientGame.java +++ b/src/seventh/client/ClientGame.java @@ -116,7 +116,7 @@ * @author Tony * */ -public class ClientGame { +public class ClientGame { private final SeventhGame app; private final Map map; diff --git a/src/seventh/game/Game.java b/src/seventh/game/Game.java index ad42294..fc9451a 100644 --- a/src/seventh/game/Game.java +++ b/src/seventh/game/Game.java @@ -814,7 +814,7 @@ public GameType getGameType() { */ @Override public void update(TimeStep timeStep) { - updateEntity(timeStep); + updateEntity(timeStep); this.aiSystem.update(timeStep); this.gameTimers.update(timeStep); this.gameTriggers.update(timeStep); diff --git a/src/seventh/game/PlayerAwardSystem.java b/src/seventh/game/PlayerAwardSystem.java index 860e69c..3f67f41 100644 --- a/src/seventh/game/PlayerAwardSystem.java +++ b/src/seventh/game/PlayerAwardSystem.java @@ -16,7 +16,7 @@ import seventh.game.events.RoundEndedListener; import seventh.game.events.RoundStartedEvent; import seventh.game.events.RoundStartedListener; -import seventh.shared.EventDispatcher; +import seventh.shared.EventDispatcher; import seventh.shared.SeventhConstants; /** diff --git a/src/seventh/math/FastMath.java b/src/seventh/math/FastMath.java index 09a92f7..2043b87 100644 --- a/src/seventh/math/FastMath.java +++ b/src/seventh/math/FastMath.java @@ -15,7 +15,7 @@ * pjt33 on JavaGaming.org for fixed point.
* Jim Shima for atan2_fast.
* - *

+ *

* Taken from JavaGaming.org from Nate * * @author Nate From 2dbea2dd15e51b992488464e2592464d8c5ca8a6 Mon Sep 17 00:00:00 2001 From: virginbabylon Date: Mon, 7 May 2018 23:35:02 +0900 Subject: [PATCH 26/47] 1.extract method, move method 2.ClienteGame.java public void applyGameUpdate() Game.java public void update() public boolean playerSwitchedTeam() PlayerAwardSystem.java public void roundEnded() public void addKill() 3.too many functions, duplicated codes in one method 1.Replace Temp with Query 2.FastMath.java static public final int random() static public final float random() public static float a_sqrt public static float a_isqrt 3.placing the result of an expression in a local variable for later use in the code. --- src/seventh/client/ClientGame.java | 2 +- src/seventh/game/Game.java | 2 +- src/seventh/game/PlayerAwardSystem.java | 2 +- src/seventh/math/FastMath.java | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/seventh/client/ClientGame.java b/src/seventh/client/ClientGame.java index b0cb07b..843d833 100644 --- a/src/seventh/client/ClientGame.java +++ b/src/seventh/client/ClientGame.java @@ -115,7 +115,7 @@ * * @author Tony * - */ + */ public class ClientGame { private final SeventhGame app; diff --git a/src/seventh/game/Game.java b/src/seventh/game/Game.java index fc9451a..52e9142 100644 --- a/src/seventh/game/Game.java +++ b/src/seventh/game/Game.java @@ -112,7 +112,7 @@ * */ public class Game implements GameInfo, Debugable, Updatable { - + /** * Null Node Data. diff --git a/src/seventh/game/PlayerAwardSystem.java b/src/seventh/game/PlayerAwardSystem.java index 3f67f41..d7b9ac1 100644 --- a/src/seventh/game/PlayerAwardSystem.java +++ b/src/seventh/game/PlayerAwardSystem.java @@ -24,7 +24,7 @@ * * @author Tony * - */ + */ public class PlayerAwardSystem { /** diff --git a/src/seventh/math/FastMath.java b/src/seventh/math/FastMath.java index 2043b87..3f09d4f 100644 --- a/src/seventh/math/FastMath.java +++ b/src/seventh/math/FastMath.java @@ -9,7 +9,7 @@ /** * Utility and fast math functions. * - * Thanks to:
+ * Thanks to:
* Riven on JavaGaming.org for sin/cos/atan2 tables.
* Roquen on JavaGaming.org for random numbers.
* pjt33 on JavaGaming.org for fixed point.
From 1b6bb5c8835102953a1e4fe5c4a9f83f9cd7d9ff Mon Sep 17 00:00:00 2001 From: virginbabylon Date: Mon, 7 May 2018 23:58:10 +0900 Subject: [PATCH 27/47] 1.extract method, move method 2.ClienteGame.java public void applyGameUpdate() Game.java public void update() public boolean playerSwitchedTeam() PlayerAwardSystem.java public void roundEnded() public void addKill() 3.too many functions, duplicated codes in one method 1.Replace Temp with Query 2.FastMath.java static public final int random() static public final float random() public static float a_sqrt public static float a_isqrt 3.placing the result of an expression in a local variable for later use in the code. --- src/seventh/client/ClientGame.java | 36 +++++++++++++++--------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/src/seventh/client/ClientGame.java b/src/seventh/client/ClientGame.java index 843d833..17d271c 100644 --- a/src/seventh/client/ClientGame.java +++ b/src/seventh/client/ClientGame.java @@ -115,8 +115,8 @@ * * @author Tony * - */ -public class ClientGame { + */ +public class ClientGame { private final SeventhGame app; private final Map map; @@ -526,7 +526,7 @@ private void renderWorld(Canvas canvas, Camera camera, float alpha) { gameEffects.renderForeground(canvas, camera, alpha); map.renderForeground(canvas, camera, alpha); - canvas.setColor(0, 75); + canvas.setColor(0, 45); map.renderSolid(canvas, camera, alpha); gameEffects.renderLightSystem(canvas, camera, alpha); @@ -1421,6 +1421,21 @@ private void updateEntity(NetGameUpdate netUpdate) { } } } + + private void setSoundType(NetSound snd, Vector2f pos) { + switch(snd.getSoundType()) { + case SURFACE_DIRT: + case SURFACE_GRASS: + case SURFACE_METAL: + case SURFACE_NORMAL: + case SURFACE_SAND: + case SURFACE_WATER: + case SURFACE_WOOD: + Sounds.playSound(snd, pos.x, pos.y, 0.35f ); + break; + default: Sounds.playSound(snd, pos.x, pos.y ); + } + } public void applyGameStats(NetGameStats stats) { if(stats.playerStats != null) { @@ -1864,11 +1879,9 @@ public void flagCaptured(FlagCapturedMessage msg) { if(player!=null) { if(player.getTeam().equals(this.localPlayer.getTeam())) { Sounds.playGlobalSound(Sounds.flagCaptured); - postMessage("Flag captured!"); } else { Sounds.playGlobalSound(Sounds.enemyFlagCaptured); - postMessage("Enemy flag captured!"); } } } @@ -1883,11 +1896,9 @@ public void flagStolen(FlagStolenMessage msg) { if(player!=null) { if(player.getTeam().equals(this.localPlayer.getTeam())) { Sounds.playGlobalSound(Sounds.flagStolen); - postMessage("Flag stolen!"); } else { Sounds.playGlobalSound(Sounds.enemyFlagStolen); - postMessage("Enemy flag stolen!"); } } } @@ -1896,17 +1907,6 @@ public void flagStolen(FlagStolenMessage msg) { public void flagReturned(FlagReturnedMessage msg) { Sounds.playGlobalSound(Sounds.flagCaptured); - if(this.localPlayer != null) { - ClientPlayer player = this.players.getPlayer(msg.returnedBy); - if(player!=null) { - if(player.getTeam().equals(this.localPlayer.getTeam())) { - postMessage("Flag returned!"); - } - else { - postMessage("Enemy flag returned!"); - } - } - } } /** From 04631b3ccb08498666cc94290fc49139d3dc30ee Mon Sep 17 00:00:00 2001 From: aikaran Date: Tue, 8 May 2018 14:42:59 +0900 Subject: [PATCH 28/47] correct the function type --- src/seventh/ClientMain.java | 7 +++---- src/seventh/ui/view/ProgressBarView.java | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/src/seventh/ClientMain.java b/src/seventh/ClientMain.java index 9cedd67..289b1a9 100644 --- a/src/seventh/ClientMain.java +++ b/src/seventh/ClientMain.java @@ -195,7 +195,7 @@ public static void logSystemSpecs(Logger console) { * * @param console */ - private logSystemSpecsRuntime(Logger console) { + private static void logSystemSpecsRuntime(Logger console) { final long MB = 1024 * 1024; Runtime runtime = Runtime.getRuntime(); console.println(""); @@ -211,7 +211,7 @@ private logSystemSpecsRuntime(Logger console) { * * @param console */ - private logSystemSpecsFileSystem(Logger console) { + private static void logSystemSpecsFileSystem(Logger console) { final long MB = 1024 * 1024; /* Get a list of all filesystem roots on this system */ File[] roots = File.listRoots(); @@ -230,8 +230,7 @@ private logSystemSpecsFileSystem(Logger console) { * * @param console */ - private logSystemSpecsSystemProperty(Logger console) { - final long MB = 1024 * 1024; + private static void logSystemSpecsSystemProperty(Logger console) { console.println("Java Version: " + System.getProperty("java.version")); console.println("Java Vendor: " + System.getProperty("java.vendor")); console.println("Java VM Version: " + System.getProperty("java.vm.version")); diff --git a/src/seventh/ui/view/ProgressBarView.java b/src/seventh/ui/view/ProgressBarView.java index 9cde15d..e5e9dc1 100644 --- a/src/seventh/ui/view/ProgressBarView.java +++ b/src/seventh/ui/view/ProgressBarView.java @@ -57,7 +57,7 @@ public void render(Canvas canvas, Camera camera, float alpha) { * @param canvas * @param bounds */ - private void addAShadowEffect(Canvas canvas, Rectangle bounds) { + private static void addAShadowEffect(Canvas canvas, Rectangle bounds) { int x = bounds.x; int y = bounds.y; From c170b80530a8bd001e53c4cc9b361067a39380c5 Mon Sep 17 00:00:00 2001 From: aikaran Date: Mon, 4 Jun 2018 13:37:56 +0900 Subject: [PATCH 29/47] Design Pattern : Strategy Pattern Target Class : seventh.shared Arrays class Reason : Arrays class implement quicksort and using it. --- src/seventh/shared/Arrays.java | 49 ++++++----------------- src/seventh/shared/QuickSortStrategy.java | 40 ++++++++++++++++++ src/seventh/shared/SortStrategy.java | 7 ++++ 3 files changed, 59 insertions(+), 37 deletions(-) create mode 100644 src/seventh/shared/QuickSortStrategy.java create mode 100644 src/seventh/shared/SortStrategy.java diff --git a/src/seventh/shared/Arrays.java b/src/seventh/shared/Arrays.java index 2ce7d30..d9e7713 100644 --- a/src/seventh/shared/Arrays.java +++ b/src/seventh/shared/Arrays.java @@ -12,7 +12,17 @@ * */ public class Arrays { - + private static SortStrategy sortStrategy; + + /** + * Set the strategy. + * + * @param newSortStrategy + */ + public void setStrategy(SortStrategy newSortStrategy) { + this.sortStrategy = newSortStrategy; + } + /** * Counts the amount of used elements in the array * @@ -57,42 +67,7 @@ public static T[] sort(T[] array, Comparator comp) { return array; } - quicksort(array, comp, 0, array.length - 1); + sortStrategy.sort(array, comp, 0, array.length - 1); return array; } - - private static void quicksort(T[] array, Comparator comp, int low, int high) { - int i = low; - int j = high; - - T pivot = array[low + (high - low) / 2]; - while (i <= j) { - while (comp.compare(array[i], pivot) < 0) { - i++; - } - while (comp.compare(array[j], pivot) > 0) { - j--; - } - - if (i <= j) { - swap(array, i, j); - i++; - j--; - } - } - - if (low < j) { - quicksort(array, comp, low, j); - } - - if (i < high) { - quicksort(array, comp, i, high); - } - } - - private static void swap(T[] array, int i, int j) { - T temp = array[i]; - array[i] = array[j]; - array[j] = temp; - } } diff --git a/src/seventh/shared/QuickSortStrategy.java b/src/seventh/shared/QuickSortStrategy.java new file mode 100644 index 0000000..9fe3e1f --- /dev/null +++ b/src/seventh/shared/QuickSortStrategy.java @@ -0,0 +1,40 @@ +package seventh.shared; + +import java.util.Comparator; + +public class QuickSortStrategy implements SortStrategy { + public void sort(T[] array, Comparator comp, int low, int high) { + int i = low; + int j = high; + + T pivot = array[low + (high - low) / 2]; + while (i <= j) { + while (comp.compare(array[i], pivot) < 0) { + i++; + } + while (comp.compare(array[j], pivot) > 0) { + j--; + } + + if (i <= j) { + swap(array, i, j); + i++; + j--; + } + } + + if (low < j) { + sort(array, comp, low, j); + } + + if (i < high) { + sort(array, comp, i, high); + } + } + + private static void swap(T[] array, int i, int j) { + T temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } +} diff --git a/src/seventh/shared/SortStrategy.java b/src/seventh/shared/SortStrategy.java new file mode 100644 index 0000000..860fcf7 --- /dev/null +++ b/src/seventh/shared/SortStrategy.java @@ -0,0 +1,7 @@ +package seventh.shared; + +import java.util.Comparator; + +public interface SortStrategy { + public void sort(T[] array, Comparator comp, int beg, int end) ; +} \ No newline at end of file From 9069b99c35caec3a551ad5bccb72c6e0da115f1b Mon Sep 17 00:00:00 2001 From: aikaran Date: Mon, 4 Jun 2018 14:42:57 +0900 Subject: [PATCH 30/47] fix some error --- src/seventh/shared/Arrays.java | 4 ++-- src/seventh/shared/SortStrategy.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/seventh/shared/Arrays.java b/src/seventh/shared/Arrays.java index d9e7713..44169c9 100644 --- a/src/seventh/shared/Arrays.java +++ b/src/seventh/shared/Arrays.java @@ -12,7 +12,7 @@ * */ public class Arrays { - private static SortStrategy sortStrategy; + private SortStrategy sortStrategy; /** * Set the strategy. @@ -62,7 +62,7 @@ public static void clear(T[] array) { * @param comp * @return the supplied array */ - public static T[] sort(T[] array, Comparator comp) { + public T[] sort(T[] array, Comparator comp) { if (array == null || array.length == 0) { return array; } diff --git a/src/seventh/shared/SortStrategy.java b/src/seventh/shared/SortStrategy.java index 860fcf7..73cbbca 100644 --- a/src/seventh/shared/SortStrategy.java +++ b/src/seventh/shared/SortStrategy.java @@ -3,5 +3,5 @@ import java.util.Comparator; public interface SortStrategy { - public void sort(T[] array, Comparator comp, int beg, int end) ; + public void sort(T[] array, Comparator comp, int beg, int end); } \ No newline at end of file From bb1153fcb1f8dfc3900dfe48dfbdb0b4d0ca7d45 Mon Sep 17 00:00:00 2001 From: cokacider Date: Mon, 4 Jun 2018 20:07:57 +0900 Subject: [PATCH 31/47] Apply a design pattern (Template Method Pattern) 1. Name of applied design pattern - Template Method Pattern 2. target - methods in World class getNorthZone getNorthWestZone getNorthEastZone getEastZone getSouthZone getSouthWestZone getSouthEastZone getWestZone 3. reason - to remove duplicated codes. --- src/seventh/ai/basic/World.java | 173 ++++++++++++++++++++++++-------- 1 file changed, 133 insertions(+), 40 deletions(-) diff --git a/src/seventh/ai/basic/World.java b/src/seventh/ai/basic/World.java index 275a126..647ab83 100644 --- a/src/seventh/ai/basic/World.java +++ b/src/seventh/ai/basic/World.java @@ -451,67 +451,160 @@ public Zone findAdjacentZone(Zone zone, int minDistance) { } private Zone getNorthZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x; - int adjacentZoneY = bounds.y - (bounds.height/2 + fuzzy + minDistance); - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new NorthZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getNorthWestZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x - (bounds.width/2 + fuzzy + minDistance); - int adjacentZoneY = bounds.y - (bounds.height/2 + fuzzy + minDistance); - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new NorthWestZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getNorthEastZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); - int adjacentZoneY = bounds.y - (bounds.height/2 + fuzzy + minDistance); - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new NorthEastZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getEastZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); - int adjacentZoneY = bounds.y; - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new EastZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getSouthZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x; - int adjacentZoneY = bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new SouthZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getSouthWestZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x - (bounds.width/2 + fuzzy + minDistance); - int adjacentZoneY = bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new SouthWestZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getSouthEastZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); - int adjacentZoneY = bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new SouthEastZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getWestZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x - (bounds.width/2 + fuzzy + minDistance); - int adjacentZoneY = bounds.y; - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new WestZone().getAdjacentZone(bounds, fuzzy, minDistance); + } + + private abstract class AdjacentZone { + public Zone getAdjacentZone(Rectangle bounds, int fuzzy, int minDistance) { + + int adjacentZoneX = getAdjacentZoneX(bounds, fuzzy, minDistance); + int adjacentZoneY = getAdjacentZoneY(bounds, fuzzy, minDistance); + Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); + return adjacentZone; + } + + protected abstract int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance); + protected abstract int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance); + } + + private class NorthZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x; + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y - (bounds.height/2 + fuzzy + minDistance); + } + + } + + private class NorthWestZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x - (bounds.width/2 + fuzzy + minDistance); + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y - (bounds.height/2 + fuzzy + minDistance); + } + + } + + private class NorthEastZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y - (bounds.height/2 + fuzzy + minDistance); + } + + } + + private class EastZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y; + } + + } + + private class SouthZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x; + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); + } + + } + + private class SouthWestZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x - (bounds.width/2 + fuzzy + minDistance); + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); + } + + } + + private class SouthEastZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); + } + + } + + private class WestZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x - (bounds.width/2 + fuzzy + minDistance); + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y; + } + } /** From 1d2f4c8a707117d7f77406981279593c0c01e521 Mon Sep 17 00:00:00 2001 From: cokacider Date: Mon, 4 Jun 2018 20:16:12 +0900 Subject: [PATCH 32/47] all tabs in World.java convert to 4 spaces --- src/seventh/ai/basic/World.java | 158 ++++++++++++++++---------------- 1 file changed, 79 insertions(+), 79 deletions(-) diff --git a/src/seventh/ai/basic/World.java b/src/seventh/ai/basic/World.java index 647ab83..58a3a28 100644 --- a/src/seventh/ai/basic/World.java +++ b/src/seventh/ai/basic/World.java @@ -483,128 +483,128 @@ private Zone getWestZone(Rectangle bounds, int fuzzy, int minDistance) { } private abstract class AdjacentZone { - public Zone getAdjacentZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = getAdjacentZoneX(bounds, fuzzy, minDistance); + public Zone getAdjacentZone(Rectangle bounds, int fuzzy, int minDistance) { + + int adjacentZoneX = getAdjacentZoneX(bounds, fuzzy, minDistance); int adjacentZoneY = getAdjacentZoneY(bounds, fuzzy, minDistance); Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); return adjacentZone; - } - - protected abstract int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance); - protected abstract int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance); + } + + protected abstract int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance); + protected abstract int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance); } private class NorthZone extends AdjacentZone { - @Override - protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.x; - } + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x; + } - @Override - protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.y - (bounds.height/2 + fuzzy + minDistance); - } - + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y - (bounds.height/2 + fuzzy + minDistance); + } + } private class NorthWestZone extends AdjacentZone { - @Override - protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.x - (bounds.width/2 + fuzzy + minDistance); - } + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x - (bounds.width/2 + fuzzy + minDistance); + } - @Override - protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.y - (bounds.height/2 + fuzzy + minDistance); - } - + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y - (bounds.height/2 + fuzzy + minDistance); + } + } private class NorthEastZone extends AdjacentZone { - @Override - protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); - } + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); + } - @Override - protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.y - (bounds.height/2 + fuzzy + minDistance); - } - + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y - (bounds.height/2 + fuzzy + minDistance); + } + } private class EastZone extends AdjacentZone { - @Override - protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); - } + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); + } - @Override - protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.y; - } - + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y; + } + } private class SouthZone extends AdjacentZone { - @Override - protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.x; - } + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x; + } - @Override - protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); - } - + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); + } + } private class SouthWestZone extends AdjacentZone { - @Override - protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.x - (bounds.width/2 + fuzzy + minDistance); - } + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x - (bounds.width/2 + fuzzy + minDistance); + } - @Override - protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); - } - + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); + } + } private class SouthEastZone extends AdjacentZone { - @Override - protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); - } + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); + } - @Override - protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); - } - + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); + } + } private class WestZone extends AdjacentZone { - @Override - protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.x - (bounds.width/2 + fuzzy + minDistance); - } + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x - (bounds.width/2 + fuzzy + minDistance); + } - @Override - protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { - return bounds.y; - } - + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y; + } + } /** From d48731307000cc8ad413e0f10ee4fa162217010f Mon Sep 17 00:00:00 2001 From: cokacider Date: Tue, 5 Jun 2018 13:51:14 +0900 Subject: [PATCH 33/47] Apply a design pattern (Abstract Factory Pattern) 1. Name of applied design pattern - Abstract Factory Pattern 2. target - add TeamStrategyFactory abstract class, DefaultAISystemTeamStrategyFactory class. - delete switch context in init(GameInfo) method in DefaultAISystem class and add factory context. 3. reason - make it easy to add another AISystem and maintain AIStrategy codes. --- src/seventh/ai/basic/DefaultAISystem.java | 26 ++------ .../DefaultAISystemTeamStrategyFactory.java | 51 ++++++++++++++++ .../teamstrategy/TeamStrategyFactory.java | 60 +++++++++++++++++++ 3 files changed, 116 insertions(+), 21 deletions(-) create mode 100644 src/seventh/ai/basic/teamstrategy/DefaultAISystemTeamStrategyFactory.java create mode 100644 src/seventh/ai/basic/teamstrategy/TeamStrategyFactory.java diff --git a/src/seventh/ai/basic/DefaultAISystem.java b/src/seventh/ai/basic/DefaultAISystem.java index fcdfdfb..665ef49 100644 --- a/src/seventh/ai/basic/DefaultAISystem.java +++ b/src/seventh/ai/basic/DefaultAISystem.java @@ -19,9 +19,11 @@ import seventh.ai.basic.commands.AICommands; import seventh.ai.basic.teamstrategy.CaptureTheFlagTeamStrategy; import seventh.ai.basic.teamstrategy.CommanderTeamStrategy; +import seventh.ai.basic.teamstrategy.DefaultAISystemTeamStrategyFactory; import seventh.ai.basic.teamstrategy.ObjectiveTeamStrategy; import seventh.ai.basic.teamstrategy.TDMTeamStrategy; import seventh.ai.basic.teamstrategy.TeamStrategy; +import seventh.ai.basic.teamstrategy.TeamStrategyFactory; import seventh.game.GameInfo; import seventh.game.PlayerInfo; import seventh.game.PlayerInfos; @@ -169,27 +171,9 @@ public void init(final GameInfo game) { GameType gameType = game.getGameType(); - switch(gameType.getType()) { - case CTF: - this.alliedAIStrategy = new CaptureTheFlagTeamStrategy(this, gameType.getAlliedTeam()); - this.axisAIStrategy = new CaptureTheFlagTeamStrategy(this, gameType.getAxisTeam()); - break; - case OBJ: - this.alliedAIStrategy = new ObjectiveTeamStrategy(this, gameType.getAlliedTeam()); - this.axisAIStrategy = new ObjectiveTeamStrategy(this, gameType.getAxisTeam()); - break; - case CMD: - this.alliedAIStrategy = new CommanderTeamStrategy((CommanderGameType)gameType, this, gameType.getAlliedTeam()); - this.axisAIStrategy = new CommanderTeamStrategy((CommanderGameType)gameType, this, gameType.getAxisTeam()); - break; - case TDM: - default: - this.alliedAIStrategy = new TDMTeamStrategy(this, gameType.getAlliedTeam()); - this.axisAIStrategy = new TDMTeamStrategy(this, gameType.getAxisTeam()); - break; - - } - + TeamStrategyFactory teamStrategyFactory = new DefaultAISystemTeamStrategyFactory(); + this.alliedAIStrategy = teamStrategyFactory.createAlliedAIStrategy(this, gameType); + this.axisAIStrategy = teamStrategyFactory.createAxisAIStrategy(this, gameType); PlayerInfos players = game.getPlayerInfos(); players.forEachPlayerInfo(new PlayerInfoIterator() { diff --git a/src/seventh/ai/basic/teamstrategy/DefaultAISystemTeamStrategyFactory.java b/src/seventh/ai/basic/teamstrategy/DefaultAISystemTeamStrategyFactory.java new file mode 100644 index 0000000..d8b1993 --- /dev/null +++ b/src/seventh/ai/basic/teamstrategy/DefaultAISystemTeamStrategyFactory.java @@ -0,0 +1,51 @@ +package seventh.ai.basic.teamstrategy; + +import seventh.ai.AISystem; +import seventh.ai.basic.DefaultAISystem; +import seventh.game.type.GameType; +import seventh.game.type.cmd.CommanderGameType; + +public class DefaultAISystemTeamStrategyFactory extends TeamStrategyFactory { + + @Override + protected TeamStrategy createCTFAlliedAIStrategy(AISystem aiSystem, GameType gameType) { + return new CaptureTheFlagTeamStrategy((DefaultAISystem)aiSystem, gameType.getAlliedTeam()); + } + + @Override + protected TeamStrategy createCTFAxisAIStrategy(AISystem aiSystem, GameType gameType) { + return new CaptureTheFlagTeamStrategy((DefaultAISystem)aiSystem, gameType.getAxisTeam()); + } + + @Override + protected TeamStrategy createOBJAlliedAIStrategy(AISystem aiSystem, GameType gameType) { + return new ObjectiveTeamStrategy((DefaultAISystem)aiSystem, gameType.getAlliedTeam()); + } + + @Override + protected TeamStrategy createOBJAxisAIStrategy(AISystem aiSystem, GameType gameType) { + return new ObjectiveTeamStrategy((DefaultAISystem)aiSystem, gameType.getAxisTeam()); + } + + @Override + protected TeamStrategy createCMDAlliedAIStrategy(AISystem aiSystem, GameType gameType) { + return new CommanderTeamStrategy((CommanderGameType)gameType, (DefaultAISystem)aiSystem, gameType.getAlliedTeam()); + } + + @Override + protected TeamStrategy createCMDAxisAIStrategy(AISystem aiSystem, GameType gameType) { + return new CommanderTeamStrategy((CommanderGameType)gameType, (DefaultAISystem)aiSystem, gameType.getAxisTeam()); + } + + @Override + protected TeamStrategy createTDMAlliedAIStrategy(AISystem aiSystem, GameType gameType) { + return new TDMTeamStrategy((DefaultAISystem)aiSystem, gameType.getAlliedTeam()); + } + + @Override + protected TeamStrategy createTDMAxisAIStrategy(AISystem aiSystem, GameType gameType) { + return new TDMTeamStrategy((DefaultAISystem)aiSystem, gameType.getAxisTeam()); + } + + +} diff --git a/src/seventh/ai/basic/teamstrategy/TeamStrategyFactory.java b/src/seventh/ai/basic/teamstrategy/TeamStrategyFactory.java new file mode 100644 index 0000000..2f5b54e --- /dev/null +++ b/src/seventh/ai/basic/teamstrategy/TeamStrategyFactory.java @@ -0,0 +1,60 @@ +package seventh.ai.basic.teamstrategy; + +import seventh.ai.AISystem; +import seventh.game.type.GameType; + +public abstract class TeamStrategyFactory { + + public TeamStrategy createAlliedAIStrategy(AISystem aiSystem, GameType gameType) { + TeamStrategy teamStrategy; + switch(gameType.getType()) { + case CTF: + teamStrategy = createCTFAlliedAIStrategy(aiSystem, gameType); + break; + case OBJ: + teamStrategy = createOBJAlliedAIStrategy(aiSystem, gameType); + break; + case CMD: + teamStrategy = createCMDAlliedAIStrategy(aiSystem, gameType); + break; + case TDM: + default: + teamStrategy = createTDMAlliedAIStrategy(aiSystem, gameType); + break; + } + return teamStrategy; + } + + public TeamStrategy createAxisAIStrategy(AISystem aiSystem, GameType gameType) { + TeamStrategy teamStrategy; + switch(gameType.getType()) { + case CTF: + teamStrategy = createCTFAxisAIStrategy(aiSystem, gameType); + break; + case OBJ: + teamStrategy = createOBJAxisAIStrategy(aiSystem, gameType); + break; + case CMD: + teamStrategy = createCMDAxisAIStrategy(aiSystem, gameType); + break; + case TDM: + default: + teamStrategy = createTDMAxisAIStrategy(aiSystem, gameType); + break; + } + return teamStrategy; + } + + protected abstract TeamStrategy createCTFAlliedAIStrategy(AISystem aiSystem, GameType gameType); + protected abstract TeamStrategy createCTFAxisAIStrategy(AISystem aiSystem, GameType gameType); + + protected abstract TeamStrategy createOBJAlliedAIStrategy(AISystem aiSystem, GameType gameType); + protected abstract TeamStrategy createOBJAxisAIStrategy(AISystem aiSystem, GameType gameType); + + protected abstract TeamStrategy createCMDAlliedAIStrategy(AISystem aiSystem, GameType gameType); + protected abstract TeamStrategy createCMDAxisAIStrategy(AISystem aiSystem, GameType gameType); + + protected abstract TeamStrategy createTDMAlliedAIStrategy(AISystem aiSystem, GameType gameType); + protected abstract TeamStrategy createTDMAxisAIStrategy(AISystem aiSystem, GameType gameType); + +} From 4bd1aaeeeb1df10f4ce1862c3b54e415fd0b77f2 Mon Sep 17 00:00:00 2001 From: aikaran Date: Tue, 5 Jun 2018 14:34:36 +0900 Subject: [PATCH 34/47] StrategyPattern seventh.shared.Arrays class separate implementation of sorting method from Arrays --- src/seventh/shared/Arrays.java | 6 +----- src/seventh/shared/NoSortStrategy.java | 9 +++++++++ src/seventh/shared/QuickSortStrategy.java | 10 +++++++--- src/seventh/shared/SortStrategy.java | 2 +- 4 files changed, 18 insertions(+), 9 deletions(-) create mode 100644 src/seventh/shared/NoSortStrategy.java diff --git a/src/seventh/shared/Arrays.java b/src/seventh/shared/Arrays.java index 44169c9..bbd55d1 100644 --- a/src/seventh/shared/Arrays.java +++ b/src/seventh/shared/Arrays.java @@ -63,11 +63,7 @@ public static void clear(T[] array) { * @return the supplied array */ public T[] sort(T[] array, Comparator comp) { - if (array == null || array.length == 0) { - return array; - } - - sortStrategy.sort(array, comp, 0, array.length - 1); + sortStrategy.sort(array, comp); return array; } } diff --git a/src/seventh/shared/NoSortStrategy.java b/src/seventh/shared/NoSortStrategy.java new file mode 100644 index 0000000..20fea9a --- /dev/null +++ b/src/seventh/shared/NoSortStrategy.java @@ -0,0 +1,9 @@ +package seventh.shared; + +import java.util.Comparator; + +public class NoSortStrategy implements SortStrategy { + public void sort(T[] array, Comparator comp) { + return ; + } +} diff --git a/src/seventh/shared/QuickSortStrategy.java b/src/seventh/shared/QuickSortStrategy.java index 9fe3e1f..8d76187 100644 --- a/src/seventh/shared/QuickSortStrategy.java +++ b/src/seventh/shared/QuickSortStrategy.java @@ -3,7 +3,11 @@ import java.util.Comparator; public class QuickSortStrategy implements SortStrategy { - public void sort(T[] array, Comparator comp, int low, int high) { + public void sort(T[] array, Comparator comp) { + quickSort(array, comp, 0, array.length-1); + } + + private static void quickSort(T[] array, Comparator comp, int low, int high) { int i = low; int j = high; @@ -24,11 +28,11 @@ public void sort(T[] array, Comparator comp, int low, int high) { } if (low < j) { - sort(array, comp, low, j); + quickSort(array, comp, low, j); } if (i < high) { - sort(array, comp, i, high); + quickSort(array, comp, i, high); } } diff --git a/src/seventh/shared/SortStrategy.java b/src/seventh/shared/SortStrategy.java index 73cbbca..c54f504 100644 --- a/src/seventh/shared/SortStrategy.java +++ b/src/seventh/shared/SortStrategy.java @@ -3,5 +3,5 @@ import java.util.Comparator; public interface SortStrategy { - public void sort(T[] array, Comparator comp, int beg, int end); + public void sort(T[] array, Comparator comp); } \ No newline at end of file From 12b61fda11c97bf14e528f94614d9306acda308a Mon Sep 17 00:00:00 2001 From: aikaran Date: Tue, 5 Jun 2018 20:11:53 +0900 Subject: [PATCH 35/47] Fork again --- src/harenet/BitArray.java | 8 +- src/harenet/BitPacker.java | 40 +-- src/harenet/Host.java | 26 +- src/seventh/ClientMain.java | 47 +-- src/seventh/ai/basic/DefaultAISystem.java | 26 +- src/seventh/ai/basic/World.java | 171 ++++++++--- .../DefaultAISystemTeamStrategyFactory.java | 51 ++++ .../teamstrategy/TeamStrategyFactory.java | 60 ++++ src/seventh/client/ClientGame.java | 149 +++++----- src/seventh/client/SeventhGame.java | 14 +- .../client/entities/ClientBombTarget.java | 2 +- src/seventh/client/entities/ClientBullet.java | 6 +- .../entities/ClientControllableEntity.java | 144 +++++++++- .../client/entities/ClientDroppedItem.java | 6 +- src/seventh/client/entities/ClientEntity.java | 6 +- src/seventh/client/entities/ClientFire.java | 2 +- src/seventh/client/entities/ClientFlag.java | 24 +- .../client/entities/ClientGrenade.java | 2 +- .../client/entities/ClientLightBulb.java | 4 +- .../client/entities/ClientPlayerEntity.java | 36 +-- .../client/entities/vehicles/ClientTank.java | 8 +- src/seventh/client/gfx/CompoundCursor.java | 42 ++- src/seventh/client/gfx/Cursor.java | 99 ++++++- src/seventh/client/gfx/ImageCursor.java | 2 +- src/seventh/client/gfx/WeaponClassDialog.java | 171 +++++------ .../client/gfx/effects/ClientGameEffects.java | 2 +- .../gfx/effects/particle_system/Emitters.java | 2 +- src/seventh/client/gfx/hud/Hud.java | 33 +-- src/seventh/client/gfx/hud/Scoreboard.java | 2 +- .../client/inputs/CameraController.java | 66 +++-- .../client/inputs/ControllerInput.java | 20 +- src/seventh/client/inputs/InputMap.java | 12 +- src/seventh/client/inputs/Inputs.java | 6 +- .../client/inputs/JoystickGameController.java | 5 +- src/seventh/client/inputs/KeyMap.java | 2 +- .../client/inputs/KeyboardGameController.java | 1 + src/seventh/client/screens/MenuScreen.java | 4 +- src/seventh/client/screens/OptionsScreen.java | 147 +++++----- .../client/weapon/ClientSpringfield.java | 2 +- src/seventh/game/Game.java | 111 ++++--- src/seventh/game/GameInfo.java | 3 + src/seventh/game/PlayerAwardSystem.java | 98 +++---- src/seventh/game/entities/BombTarget.java | 13 +- src/seventh/game/entities/Door.java | 61 ++-- src/seventh/game/entities/Entity.java | 11 +- src/seventh/game/entities/PlayerEntity.java | 30 +- src/seventh/game/net/NetPlayer.java | 3 - .../game/type/AbstractTeamGameType.java | 11 + src/seventh/game/type/GameType.java | 3 + .../game/type/obj/BombTargetObjective.java | 4 +- .../game/type/obj/ObjectiveGameType.java | 2 + .../game/type/obj/ObjectiveScript.java | 186 +++++------- src/seventh/map/DefaultMapObjectFactory.java | 4 +- src/seventh/map/Layer.java | 8 +- src/seventh/map/Map.java | 22 +- src/seventh/map/OrthoMap.java | 270 +++++++++--------- src/seventh/map/Tile.java | 145 ++++++---- src/seventh/map/TiledMapLoader.java | 20 +- src/seventh/map/Tileset.java | 4 +- src/seventh/map/TilesetAtlas.java | 6 +- src/seventh/math/Circle.java | 20 +- src/seventh/math/FastMath.java | 67 +++-- src/seventh/math/FloatUtil.java | 6 +- src/seventh/math/Line.java | 18 +- src/seventh/math/MathLeolaLibrary.java | 8 +- src/seventh/math/Matrix2f.java | 3 +- src/seventh/math/OBB.java | 42 +-- src/seventh/math/Pair.java | 4 +- src/seventh/math/Rectangle.java | 14 +- src/seventh/math/Tri.java | 52 +--- src/seventh/math/Triangle.java | 32 +-- src/seventh/math/Vector2f.java | 18 +- src/seventh/math/Vector3f.java | 4 +- .../network/messages/BombExplodedMessage.java | 3 - src/seventh/network/messages/BufferIO.java | 12 +- src/seventh/server/GameServer.java | 68 ++--- src/seventh/server/InGameState.java | 8 +- src/seventh/server/ServerNetworkProtocol.java | 4 +- .../server/SeventhScriptingCommonLibrary.java | 10 +- src/seventh/shared/Arrays.java | 2 +- src/seventh/ui/Button.java | 18 +- src/seventh/ui/Checkbox.java | 6 +- src/seventh/ui/DefaultStyling.java | 2 +- src/seventh/ui/LevelButton.java | 2 - src/seventh/ui/ListBox.java | 4 +- src/seventh/ui/MessageBoard.java | 2 +- src/seventh/ui/Slider.java | 8 +- src/seventh/ui/TextBox.java | 18 +- src/seventh/ui/UserInterfaceManager.java | 4 +- src/seventh/ui/Widget.java | 20 +- src/seventh/ui/view/ButtonView.java | 4 +- src/seventh/ui/view/ImageButtonView.java | 6 +- src/seventh/ui/view/ImagePanelView.java | 2 +- src/seventh/ui/view/LabelView.java | 6 +- src/seventh/ui/view/ListBoxView.java | 15 +- src/seventh/ui/view/ProgressBarView.java | 46 ++- src/seventh/ui/view/TextBoxView.java | 7 +- src/test/harenet/ByteBufferIOBufferTest.java | 25 ++ 98 files changed, 1692 insertions(+), 1363 deletions(-) create mode 100644 src/seventh/ai/basic/teamstrategy/DefaultAISystemTeamStrategyFactory.java create mode 100644 src/seventh/ai/basic/teamstrategy/TeamStrategyFactory.java diff --git a/src/harenet/BitArray.java b/src/harenet/BitArray.java index e8704c4..32babe3 100644 --- a/src/harenet/BitArray.java +++ b/src/harenet/BitArray.java @@ -128,10 +128,6 @@ public int size() { return this.data.length * WORD_SIZE; } - public void printBitArray(BitArray bitArray) { - System.out.println("NumberOfBytes:" + bitArray.numberOfBytes() + " : " + bitArray.size() + " : " + bitArray); - } - public static void main(String[] args) { BitArray a = new BitArray(255); @@ -140,7 +136,7 @@ public static void main(String[] args) { a.setBit(i); } - printBitArray(a); + System.out.println("NumberOfBytes:" + a.numberOfBytes() + " : " + a.size() + " : " + a); BitArray b = new BitArray(SeventhConstants.MAX_PERSISTANT_ENTITIES - 1); @@ -149,6 +145,6 @@ public static void main(String[] args) { b.setBit(i); } - printBitArray(b); + System.out.println("NumberOfBytes:" + b.numberOfBytes() + " : " + b.size() + " : " + b); } } diff --git a/src/harenet/BitPacker.java b/src/harenet/BitPacker.java index 55bae83..6e41085 100644 --- a/src/harenet/BitPacker.java +++ b/src/harenet/BitPacker.java @@ -451,7 +451,7 @@ public long getLong(int length) { for (int i = 0; i < length; i++) { checkPosition(); - value |= (data.getBit(position++) ? 1 : 0) << (i % Long.SIZE); + value |= (data.getBit(position++) ? 1L : 0L) << (i % Long.SIZE); } return value; @@ -483,10 +483,10 @@ public double getDouble(int length) { for (int i = 0; i < length; i++) { checkPosition(); - value |= (data.getBit(position++) ? 1 : 0) << (i % Double.SIZE); + value |= (data.getBit(position++) ? 1L : 0L) << (i % Double.SIZE); } - return Double.doubleToLongBits(value); + return Double.longBitsToDouble(value); } public boolean getBoolean() { @@ -533,19 +533,10 @@ public BitPacker pad() { public static void dumpBytes(byte[] value) { - int length = value.length; - printByteHeader(length); - printByteBody(length); - printFooter(); - } - - private void printByteHeader(int length) { System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); - System.out.println("| Dumping bytes, length: " + (length * 8) + " (" + length + " byte(s))"); + System.out.println("| Dumping bytes, length: " + (value.length * 8) + " (" + value.length + " byte(s))"); System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); - } - - private void printByteBody(int length) { + int count = 0; for (int j = 0; j < value.length; j++) { @@ -568,22 +559,16 @@ private void printByteBody(int length) { } } + System.out.println(); + System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); } public void dump() { - printHeader(); - printBody(); - printFooter(); - } - - private void printHeader() { System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); System.out.println("| Dumping bitset, length: " + numBits); System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); - } - private void printBody() { - int count = 0; + int count = 0; for (int i = 0; i < numBits; i++) { System.out.print(data.getBit(i) ? "1" : "0"); @@ -598,13 +583,8 @@ private void printBody() { } } - } - - private static void printFooter() { - System.out.println(); + System.out.println(); System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); - } - - + } } \ No newline at end of file diff --git a/src/harenet/Host.java b/src/harenet/Host.java index bd6e738..a1767a4 100644 --- a/src/harenet/Host.java +++ b/src/harenet/Host.java @@ -1,4 +1,3 @@ - /* * see license.txt */ @@ -280,26 +279,19 @@ void disconnect(Peer peer) { peers[id].send(new DisconnectMessage()); /* remove the peer if they are disconnected */ - removeDisconnetedPeer(id); + if(peers[id].isDisconnected()) { + synchronized (this) { + peers[id] = null; + this.numberOfConnections--; + if(this.numberOfConnections < 0) { + this.numberOfConnections = 0; + } + } + } } } } - /** - * @param id - */ - private void removeDisconnetedPeer(byte id) { - if(peers[id].isDisconnected()) { - synchronized (this) { - peers[id] = null; - this.numberOfConnections--; - if(this.numberOfConnections < 0) { - this.numberOfConnections = 0; - } - } - } - } - /** * Sends a {@link Message} to the peer * @param message diff --git a/src/seventh/ClientMain.java b/src/seventh/ClientMain.java index 289b1a9..0b69474 100644 --- a/src/seventh/ClientMain.java +++ b/src/seventh/ClientMain.java @@ -152,7 +152,7 @@ public void uncaughtException(Thread t, Throwable e) { } finally { // System.exit(0); - if(config!=null) { + if(config != null) { //config.save(CLIENT_CFG_PATH); } } @@ -160,7 +160,7 @@ public void uncaughtException(Thread t, Throwable e) { public static void logVideoSpecs(Logger console) { try { - if(Gdx.graphics!=null) { + if(Gdx.graphics != null) { console.println("GL30: " + Gdx.graphics.isGL30Available()); console.println("OpenGL Version: " + Gdx.gl.glGetString(GL20.GL_VERSION)); console.println("OpenGL Vendor: " + Gdx.gl.glGetString(GL20.GL_VENDOR)); @@ -185,52 +185,27 @@ public static void logVideoSpecs(Logger console) { * @param console */ public static void logSystemSpecs(Logger console) { - logSystemSpecsRuntime(console); - logSystemSpecsFileSystem(console); - logSystemSpecsSystemProperty(console); - } - - /** - * Prints out system specifications about runtime - * - * @param console - */ - private static void logSystemSpecsRuntime(Logger console) { + Runtime runtime = Runtime.getRuntime(); final long MB = 1024 * 1024; - Runtime runtime = Runtime.getRuntime(); console.println(""); console.println("Seventh: " + SeventhGame.getVersion()); console.println("Available processors (cores): " + runtime.availableProcessors()); - console.println("Free memory (MiB): " + runtime.freeMemory()/MB); - console.println("Max memory (MiB): " + (runtime.maxMemory()==Long.MAX_VALUE ? "no limit" : Long.toString(runtime.maxMemory()/MB)) ); + console.println("Free memory (MiB): " + runtime.freeMemory() / MB); + console.println("Max memory (MiB): " + (runtime.maxMemory() == Long.MAX_VALUE ? "no limit" : Long.toString(runtime.maxMemory() / MB)) ); console.println("Available for JVM (MiB): " + runtime.totalMemory() / MB); - } - - /** - * Prints out system specifications about filesystem root - * - * @param console - */ - private static void logSystemSpecsFileSystem(Logger console) { - final long MB = 1024 * 1024; + /* Get a list of all filesystem roots on this system */ File[] roots = File.listRoots(); /* For each filesystem root, print some info */ for (File root : roots) { console.println("File system root: " + root.getAbsolutePath()); - console.println("\tTotal space (MiB): " + root.getTotalSpace()/MB); - console.println("\tFree space (MiB): " + root.getFreeSpace()/MB); - console.println("\tUsable space (MiB): " + root.getUsableSpace()/MB); + console.println("\tTotal space (MiB): " + root.getTotalSpace() / MB); + console.println("\tFree space (MiB): " + root.getFreeSpace() / MB); + console.println("\tUsable space (MiB): " + root.getUsableSpace() / MB); } - } - - /** - * Prints out system specifications about system property - * - * @param console - */ - private static void logSystemSpecsSystemProperty(Logger console) { + + console.println("Java Version: " + System.getProperty("java.version")); console.println("Java Vendor: " + System.getProperty("java.vendor")); console.println("Java VM Version: " + System.getProperty("java.vm.version")); diff --git a/src/seventh/ai/basic/DefaultAISystem.java b/src/seventh/ai/basic/DefaultAISystem.java index fcdfdfb..665ef49 100644 --- a/src/seventh/ai/basic/DefaultAISystem.java +++ b/src/seventh/ai/basic/DefaultAISystem.java @@ -19,9 +19,11 @@ import seventh.ai.basic.commands.AICommands; import seventh.ai.basic.teamstrategy.CaptureTheFlagTeamStrategy; import seventh.ai.basic.teamstrategy.CommanderTeamStrategy; +import seventh.ai.basic.teamstrategy.DefaultAISystemTeamStrategyFactory; import seventh.ai.basic.teamstrategy.ObjectiveTeamStrategy; import seventh.ai.basic.teamstrategy.TDMTeamStrategy; import seventh.ai.basic.teamstrategy.TeamStrategy; +import seventh.ai.basic.teamstrategy.TeamStrategyFactory; import seventh.game.GameInfo; import seventh.game.PlayerInfo; import seventh.game.PlayerInfos; @@ -169,27 +171,9 @@ public void init(final GameInfo game) { GameType gameType = game.getGameType(); - switch(gameType.getType()) { - case CTF: - this.alliedAIStrategy = new CaptureTheFlagTeamStrategy(this, gameType.getAlliedTeam()); - this.axisAIStrategy = new CaptureTheFlagTeamStrategy(this, gameType.getAxisTeam()); - break; - case OBJ: - this.alliedAIStrategy = new ObjectiveTeamStrategy(this, gameType.getAlliedTeam()); - this.axisAIStrategy = new ObjectiveTeamStrategy(this, gameType.getAxisTeam()); - break; - case CMD: - this.alliedAIStrategy = new CommanderTeamStrategy((CommanderGameType)gameType, this, gameType.getAlliedTeam()); - this.axisAIStrategy = new CommanderTeamStrategy((CommanderGameType)gameType, this, gameType.getAxisTeam()); - break; - case TDM: - default: - this.alliedAIStrategy = new TDMTeamStrategy(this, gameType.getAlliedTeam()); - this.axisAIStrategy = new TDMTeamStrategy(this, gameType.getAxisTeam()); - break; - - } - + TeamStrategyFactory teamStrategyFactory = new DefaultAISystemTeamStrategyFactory(); + this.alliedAIStrategy = teamStrategyFactory.createAlliedAIStrategy(this, gameType); + this.axisAIStrategy = teamStrategyFactory.createAxisAIStrategy(this, gameType); PlayerInfos players = game.getPlayerInfos(); players.forEachPlayerInfo(new PlayerInfoIterator() { diff --git a/src/seventh/ai/basic/World.java b/src/seventh/ai/basic/World.java index 275a126..58a3a28 100644 --- a/src/seventh/ai/basic/World.java +++ b/src/seventh/ai/basic/World.java @@ -451,67 +451,160 @@ public Zone findAdjacentZone(Zone zone, int minDistance) { } private Zone getNorthZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x; - int adjacentZoneY = bounds.y - (bounds.height/2 + fuzzy + minDistance); - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new NorthZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getNorthWestZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x - (bounds.width/2 + fuzzy + minDistance); - int adjacentZoneY = bounds.y - (bounds.height/2 + fuzzy + minDistance); - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new NorthWestZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getNorthEastZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); - int adjacentZoneY = bounds.y - (bounds.height/2 + fuzzy + minDistance); - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new NorthEastZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getEastZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); - int adjacentZoneY = bounds.y; - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new EastZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getSouthZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x; - int adjacentZoneY = bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new SouthZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getSouthWestZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x - (bounds.width/2 + fuzzy + minDistance); - int adjacentZoneY = bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new SouthWestZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getSouthEastZone(Rectangle bounds, int fuzzy, int minDistance) { - - int adjacentZoneX = bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); - int adjacentZoneY = bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; + return new SouthEastZone().getAdjacentZone(bounds, fuzzy, minDistance); } private Zone getWestZone(Rectangle bounds, int fuzzy, int minDistance) { + return new WestZone().getAdjacentZone(bounds, fuzzy, minDistance); + } + + private abstract class AdjacentZone { + public Zone getAdjacentZone(Rectangle bounds, int fuzzy, int minDistance) { + + int adjacentZoneX = getAdjacentZoneX(bounds, fuzzy, minDistance); + int adjacentZoneY = getAdjacentZoneY(bounds, fuzzy, minDistance); + Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); + return adjacentZone; + } + + protected abstract int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance); + protected abstract int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance); + } + + private class NorthZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x; + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y - (bounds.height/2 + fuzzy + minDistance); + } + + } + + private class NorthWestZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x - (bounds.width/2 + fuzzy + minDistance); + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y - (bounds.height/2 + fuzzy + minDistance); + } + + } + + private class NorthEastZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y - (bounds.height/2 + fuzzy + minDistance); + } + + } + + private class EastZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y; + } + + } + + private class SouthZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x; + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); + } + + } + + private class SouthWestZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x - (bounds.width/2 + fuzzy + minDistance); + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); + } + + } + + private class SouthEastZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x + (bounds.width+(bounds.width/2) + fuzzy + minDistance); + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y + (bounds.height+(bounds.height/2) + fuzzy + minDistance); + } + + } + + private class WestZone extends AdjacentZone { + + @Override + protected int getAdjacentZoneX(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.x - (bounds.width/2 + fuzzy + minDistance); + } + + @Override + protected int getAdjacentZoneY(Rectangle bounds, int fuzzy, int minDistance) { + return bounds.y; + } - int adjacentZoneX = bounds.x - (bounds.width/2 + fuzzy + minDistance); - int adjacentZoneY = bounds.y; - Zone adjacentZone = getZone(adjacentZoneX, adjacentZoneY); - return adjacentZone; } /** diff --git a/src/seventh/ai/basic/teamstrategy/DefaultAISystemTeamStrategyFactory.java b/src/seventh/ai/basic/teamstrategy/DefaultAISystemTeamStrategyFactory.java new file mode 100644 index 0000000..d8b1993 --- /dev/null +++ b/src/seventh/ai/basic/teamstrategy/DefaultAISystemTeamStrategyFactory.java @@ -0,0 +1,51 @@ +package seventh.ai.basic.teamstrategy; + +import seventh.ai.AISystem; +import seventh.ai.basic.DefaultAISystem; +import seventh.game.type.GameType; +import seventh.game.type.cmd.CommanderGameType; + +public class DefaultAISystemTeamStrategyFactory extends TeamStrategyFactory { + + @Override + protected TeamStrategy createCTFAlliedAIStrategy(AISystem aiSystem, GameType gameType) { + return new CaptureTheFlagTeamStrategy((DefaultAISystem)aiSystem, gameType.getAlliedTeam()); + } + + @Override + protected TeamStrategy createCTFAxisAIStrategy(AISystem aiSystem, GameType gameType) { + return new CaptureTheFlagTeamStrategy((DefaultAISystem)aiSystem, gameType.getAxisTeam()); + } + + @Override + protected TeamStrategy createOBJAlliedAIStrategy(AISystem aiSystem, GameType gameType) { + return new ObjectiveTeamStrategy((DefaultAISystem)aiSystem, gameType.getAlliedTeam()); + } + + @Override + protected TeamStrategy createOBJAxisAIStrategy(AISystem aiSystem, GameType gameType) { + return new ObjectiveTeamStrategy((DefaultAISystem)aiSystem, gameType.getAxisTeam()); + } + + @Override + protected TeamStrategy createCMDAlliedAIStrategy(AISystem aiSystem, GameType gameType) { + return new CommanderTeamStrategy((CommanderGameType)gameType, (DefaultAISystem)aiSystem, gameType.getAlliedTeam()); + } + + @Override + protected TeamStrategy createCMDAxisAIStrategy(AISystem aiSystem, GameType gameType) { + return new CommanderTeamStrategy((CommanderGameType)gameType, (DefaultAISystem)aiSystem, gameType.getAxisTeam()); + } + + @Override + protected TeamStrategy createTDMAlliedAIStrategy(AISystem aiSystem, GameType gameType) { + return new TDMTeamStrategy((DefaultAISystem)aiSystem, gameType.getAlliedTeam()); + } + + @Override + protected TeamStrategy createTDMAxisAIStrategy(AISystem aiSystem, GameType gameType) { + return new TDMTeamStrategy((DefaultAISystem)aiSystem, gameType.getAxisTeam()); + } + + +} diff --git a/src/seventh/ai/basic/teamstrategy/TeamStrategyFactory.java b/src/seventh/ai/basic/teamstrategy/TeamStrategyFactory.java new file mode 100644 index 0000000..2f5b54e --- /dev/null +++ b/src/seventh/ai/basic/teamstrategy/TeamStrategyFactory.java @@ -0,0 +1,60 @@ +package seventh.ai.basic.teamstrategy; + +import seventh.ai.AISystem; +import seventh.game.type.GameType; + +public abstract class TeamStrategyFactory { + + public TeamStrategy createAlliedAIStrategy(AISystem aiSystem, GameType gameType) { + TeamStrategy teamStrategy; + switch(gameType.getType()) { + case CTF: + teamStrategy = createCTFAlliedAIStrategy(aiSystem, gameType); + break; + case OBJ: + teamStrategy = createOBJAlliedAIStrategy(aiSystem, gameType); + break; + case CMD: + teamStrategy = createCMDAlliedAIStrategy(aiSystem, gameType); + break; + case TDM: + default: + teamStrategy = createTDMAlliedAIStrategy(aiSystem, gameType); + break; + } + return teamStrategy; + } + + public TeamStrategy createAxisAIStrategy(AISystem aiSystem, GameType gameType) { + TeamStrategy teamStrategy; + switch(gameType.getType()) { + case CTF: + teamStrategy = createCTFAxisAIStrategy(aiSystem, gameType); + break; + case OBJ: + teamStrategy = createOBJAxisAIStrategy(aiSystem, gameType); + break; + case CMD: + teamStrategy = createCMDAxisAIStrategy(aiSystem, gameType); + break; + case TDM: + default: + teamStrategy = createTDMAxisAIStrategy(aiSystem, gameType); + break; + } + return teamStrategy; + } + + protected abstract TeamStrategy createCTFAlliedAIStrategy(AISystem aiSystem, GameType gameType); + protected abstract TeamStrategy createCTFAxisAIStrategy(AISystem aiSystem, GameType gameType); + + protected abstract TeamStrategy createOBJAlliedAIStrategy(AISystem aiSystem, GameType gameType); + protected abstract TeamStrategy createOBJAxisAIStrategy(AISystem aiSystem, GameType gameType); + + protected abstract TeamStrategy createCMDAlliedAIStrategy(AISystem aiSystem, GameType gameType); + protected abstract TeamStrategy createCMDAxisAIStrategy(AISystem aiSystem, GameType gameType); + + protected abstract TeamStrategy createTDMAlliedAIStrategy(AISystem aiSystem, GameType gameType); + protected abstract TeamStrategy createTDMAxisAIStrategy(AISystem aiSystem, GameType gameType); + +} diff --git a/src/seventh/client/ClientGame.java b/src/seventh/client/ClientGame.java index 4b3705d..d27965d 100644 --- a/src/seventh/client/ClientGame.java +++ b/src/seventh/client/ClientGame.java @@ -526,7 +526,7 @@ private void renderWorld(Canvas canvas, Camera camera, float alpha) { gameEffects.renderForeground(canvas, camera, alpha); map.renderForeground(canvas, camera, alpha); - canvas.setColor(0, 45); + canvas.setColor(0, 75); map.renderSolid(canvas, camera, alpha); gameEffects.renderLightSystem(canvas, camera, alpha); @@ -1292,31 +1292,43 @@ public void applyGameUpdate(GameUpdateMessage msg) { gameClock = netUpdate.time; - updateEntity(netUpdate); - - updateSound(netUpdate); - - updateSpectator(netUpdate); - } - - private void updateSpectator(NetGameUpdate netUpdate) { - if(netUpdate.spectatingPlayerId > -1 && !cameraController.isCameraRoaming()) { - int previousSpec = localPlayer.getSpectatingPlayerId(); - localPlayer.setSpectatingPlayerId(netUpdate.spectatingPlayerId); - if(previousSpec != netUpdate.spectatingPlayerId) { - ClientEntity ent = this.entities.getEntity(netUpdate.spectatingPlayerId); - if(ent!=null) { - camera.centerAroundNow(ent.getCenterPos()); + if(netUpdate.entities != null) { + int size = netUpdate.entities.length; + for(int i = 0; i < size; i++) { + NetEntity netEnt = netUpdate.entities[i]; + if(netEnt != null) { + if(entities.containsEntity(netEnt.id)) { + ClientEntity ent = entities.getEntity(netEnt.id); + if(netEnt.type == ent.getType()) { + ent.updateState(netEnt, gameClock); + } + else { + removeEntity(i); + createEntity(netEnt); + } + } + else { + createEntity(netEnt); + } + } + else { + + if( i < SeventhConstants.MAX_PERSISTANT_ENTITIES) { + /* if a persistant entity has been removed, lets + * remove it on the client side + */ + if(netUpdate.deadPersistantEntities.getBit(i)) { + removeEntity(i); + } + } + else { + removeEntity(i); + } } } } - else { - localPlayer.setSpectatingPlayerId(Entity.INVALID_ENTITY_ID); - } - } - - private void updateSound(NetGameUpdate netUpdate) { - if(netUpdate.sounds != null) { + + if(netUpdate.sounds != null) { int size = netUpdate.numberOfSounds; for(int i = 0; i < size; i++) { NetSound snd = netUpdate.sounds[i]; @@ -1340,7 +1352,18 @@ private void updateSound(NetGameUpdate netUpdate) { /* dampen the sound of the local players footsteps, * otherwise it's too loud */ - setSoundType(snd, pos); + switch(snd.getSoundType()) { + case SURFACE_DIRT: + case SURFACE_GRASS: + case SURFACE_METAL: + case SURFACE_NORMAL: + case SURFACE_SAND: + case SURFACE_WATER: + case SURFACE_WOOD: + Sounds.playSound(snd, pos.x, pos.y, 0.35f ); + break; + default: Sounds.playSound(snd, pos.x, pos.y ); + } } else { Sounds.playSound(snd, pos.x, pos.y); @@ -1371,60 +1394,21 @@ private void updateSound(NetGameUpdate netUpdate) { } } } - } - - private void updateEntity(NetGameUpdate netUpdate) { - if(netUpdate.entities != null) { - int size = netUpdate.entities.length; - for(int i = 0; i < size; i++) { - NetEntity netEnt = netUpdate.entities[i]; - if(netEnt != null) { - if(entities.containsEntity(netEnt.id)) { - ClientEntity ent = entities.getEntity(netEnt.id); - if(netEnt.type == ent.getType()) { - ent.updateState(netEnt, gameClock); - } - else { - removeEntity(i); - createEntity(netEnt); - } - } - else { - createEntity(netEnt); - } - } - else { - - if( i < SeventhConstants.MAX_PERSISTANT_ENTITIES) { - /* if a persistant entity has been removed, lets - * remove it on the client side - */ - if(netUpdate.deadPersistantEntities.getBit(i)) { - removeEntity(i); - } - } - else { - removeEntity(i); - } + + if(netUpdate.spectatingPlayerId > -1 && !cameraController.isCameraRoaming()) { + int previousSpec = localPlayer.getSpectatingPlayerId(); + localPlayer.setSpectatingPlayerId(netUpdate.spectatingPlayerId); + if(previousSpec != netUpdate.spectatingPlayerId) { + ClientEntity ent = this.entities.getEntity(netUpdate.spectatingPlayerId); + if(ent!=null) { + camera.centerAroundNow(ent.getCenterPos()); } } } - - - private void setSoundType(NetSound snd, Vector2f pos) { - switch(snd.getSoundType()) { - case SURFACE_DIRT: - case SURFACE_GRASS: - case SURFACE_METAL: - case SURFACE_NORMAL: - case SURFACE_SAND: - case SURFACE_WATER: - case SURFACE_WOOD: - Sounds.playSound(snd, pos.x, pos.y, 0.35f ); - break; - default: Sounds.playSound(snd, pos.x, pos.y ); - } - } + else { + localPlayer.setSpectatingPlayerId(Entity.INVALID_ENTITY_ID); + } + } public void applyGameStats(NetGameStats stats) { if(stats.playerStats != null) { @@ -1868,9 +1852,11 @@ public void flagCaptured(FlagCapturedMessage msg) { if(player!=null) { if(player.getTeam().equals(this.localPlayer.getTeam())) { Sounds.playGlobalSound(Sounds.flagCaptured); + postMessage("Flag captured!"); } else { Sounds.playGlobalSound(Sounds.enemyFlagCaptured); + postMessage("Enemy flag captured!"); } } } @@ -1885,9 +1871,11 @@ public void flagStolen(FlagStolenMessage msg) { if(player!=null) { if(player.getTeam().equals(this.localPlayer.getTeam())) { Sounds.playGlobalSound(Sounds.flagStolen); + postMessage("Flag stolen!"); } else { Sounds.playGlobalSound(Sounds.enemyFlagStolen); + postMessage("Enemy flag stolen!"); } } } @@ -1896,6 +1884,17 @@ public void flagStolen(FlagStolenMessage msg) { public void flagReturned(FlagReturnedMessage msg) { Sounds.playGlobalSound(Sounds.flagCaptured); + if(this.localPlayer != null) { + ClientPlayer player = this.players.getPlayer(msg.returnedBy); + if(player!=null) { + if(player.getTeam().equals(this.localPlayer.getTeam())) { + postMessage("Flag returned!"); + } + else { + postMessage("Enemy flag returned!"); + } + } + } } /** diff --git a/src/seventh/client/SeventhGame.java b/src/seventh/client/SeventhGame.java index 64cdec2..d36dc6c 100644 --- a/src/seventh/client/SeventhGame.java +++ b/src/seventh/client/SeventhGame.java @@ -300,7 +300,12 @@ private void setHWCursorVisible(boolean visible) { try { /* make sure the mouse doesn't move off the screen */ - Gdx.input.setCursorCatched(true); + seventh.client.gfx.Cursor cursor = this.uiManager.getCursor(); + cursor.setClampEnabled(config.getVideo().isFullscreen()); + Gdx.input.setCursorCatched(config.getVideo().isFullscreen()); + + //Gdx.input.setCursorCatched(true); + //Gdx.input.setCursorPosition(getScreenWidth()/2, getScreenHeight()/2); Cursor emptyCursor = null; if (Mouse.isCreated()) { @@ -347,7 +352,6 @@ public void create() { } Gdx.input.setInputProcessor(this.inputs); -// Gdx.input.setCursorCatched(true); initControllers(); videoReload(); @@ -380,7 +384,7 @@ private void initControllers() { } private void videoReload() { - Gdx.input.setCursorPosition(getScreenWidth()/2, getScreenHeight()/2); + Gdx.input.setCursorPosition(getScreenWidth()/2, getScreenHeight()/2); setHWCursorVisible(false); this.inputs.addProcessor(new Inputs() { @@ -399,6 +403,7 @@ public boolean keyUp(int key) { setVSync(config.getVideo().isVsync()); + this.canvas = new GdxCanvas(); try { this.canvas.loadFont("./assets/gfx/fonts/Courier New.ttf", "Courier New"); @@ -413,8 +418,6 @@ public boolean keyUp(int key) { catch (IOException e) { Cons.println("*** Unable to load font: " + e); } - - setHWCursorVisible(false); } /* (non-Javadoc) @@ -716,7 +719,6 @@ public void resize(int width, int height) { * Restarts the video */ public void restartVideo() { - setHWCursorVisible(false); videoReload(); } diff --git a/src/seventh/client/entities/ClientBombTarget.java b/src/seventh/client/entities/ClientBombTarget.java index 75cc4c6..ffa884f 100644 --- a/src/seventh/client/entities/ClientBombTarget.java +++ b/src/seventh/client/entities/ClientBombTarget.java @@ -56,7 +56,7 @@ public ClientBombTarget(ClientGame game, Vector2f pos) { @Override public void onRemove(ClientEntity me, ClientGame game) { - if(activeSound!=null) { + if(activeSound != null) { activeSound.stop(); } } diff --git a/src/seventh/client/entities/ClientBullet.java b/src/seventh/client/entities/ClientBullet.java index 2c20b30..5dc9d5f 100644 --- a/src/seventh/client/entities/ClientBullet.java +++ b/src/seventh/client/entities/ClientBullet.java @@ -62,8 +62,8 @@ public void onRemove(ClientEntity me, ClientGame game) { Vector2f.Vector2fPerpendicular(direction, offset); // randomly position the emitter position - Vector2f.Vector2fMS(victim.getCenterPos(), direction, 6+game.getRandom().nextInt(5), bloodPos); - float moveBy = rand.nextBoolean() ? -rand.nextInt(10) : rand.nextInt(10); + Vector2f.Vector2fMS(victim.getCenterPos(), direction, 6 + game.getRandom().nextInt(5), bloodPos); + float moveBy = rand.nextBoolean() ? -(rand.nextInt(10)) : rand.nextInt(10); Vector2f.Vector2fMA(bloodPos, offset, moveBy, bloodPos); game.addBackgroundEffect(Emitters.newBulletImpactFleshEmitter(bloodPos, direction)); @@ -161,7 +161,7 @@ private void emitBulletCasing(int ownerId) { if(ent instanceof ClientPlayerEntity) { ClientPlayerEntity playerEntity = (ClientPlayerEntity)ent; ClientWeapon weapon = playerEntity.getWeapon(); - if(weapon!=null && weapon.isAutomatic()) { + if(weapon != null && weapon.isAutomatic()) { playerEntity.emitBulletCasing(); } } diff --git a/src/seventh/client/entities/ClientControllableEntity.java b/src/seventh/client/entities/ClientControllableEntity.java index 4369a1c..c0600a1 100644 --- a/src/seventh/client/entities/ClientControllableEntity.java +++ b/src/seventh/client/entities/ClientControllableEntity.java @@ -39,6 +39,8 @@ public abstract class ClientControllableEntity extends ClientEntity { protected Rectangle hearingBounds; protected Rectangle visualBounds; + private Vector2f xCollisionTilePos, yCollisionTilePos; + /** * @param game * @param pos @@ -50,6 +52,9 @@ public ClientControllableEntity(ClientGame game, Vector2f pos) { this.renderPos = new Vector2f(pos); this.cache = new Vector2f(); + this.xCollisionTilePos = new Vector2f(); + this.yCollisionTilePos = new Vector2f(); + this.isControlledByLocalPlayer = false; @@ -151,6 +156,94 @@ public boolean inEarShot(ClientEntity ent) { return hearingBounds.intersects(ent.getBounds()); } + + /** + * Adjusts the y movement if the player is at the edge of a collidable tile and there + * is a free space + * + * @param collisionTilePos + * @param deltaX + * @param currentX + * @param currentY + * @return the adjusted y to move + */ + private int adjustY(Vector2f collisionTilePos, float deltaX, int currentX, int currentY) { + Map map = game.getMap(); + Tile collisionTile = map.getWorldCollidableTile((int)collisionTilePos.x, (int)collisionTilePos.y); + if(collisionTile != null) { + //DebugDraw.drawRectRelative(collisionTile.getBounds(), 0xff00ff00); + + int xIndex = collisionTile.getXIndex(); + int yIndex = collisionTile.getYIndex(); + + int offset = 32; + + if(!map.checkTileBounds(xIndex, yIndex - 1) && !map.hasCollidableTile(xIndex, yIndex - 1)) { + if(currentY < (collisionTile.getY() - (bounds.height - offset))) { + //DebugDraw.drawRectRelative(map.getTile(0, xIndex, yIndex-1).getBounds(), 0xafff0000); + return currentY - 1; + } + } + + if(!map.checkTileBounds(xIndex, yIndex + 1) && !map.hasCollidableTile(xIndex, yIndex + 1)) { + if(currentY > (collisionTile.getY() + (collisionTile.getHeight() - offset))) { + //DebugDraw.drawRectRelative(map.getTile(0, xIndex, yIndex+1).getBounds(), 0xaf0000ff); + return currentY + 1; + } + } + } + + return currentY; + } + + + /** + * Adjusts the x movement if the player is at the edge of a collidable tile and there + * is a free space + * + * @param collisionTilePos + * @param deltaY + * @param currentX + * @param currentY + * @return the adjusted x to move + */ + private int adjustX(Vector2f collisionTilePos, float deltaY, int currentX, int currentY) { + Map map = game.getMap(); + Tile collisionTile = map.getWorldCollidableTile((int)collisionTilePos.x, (int)collisionTilePos.y); + if(collisionTile != null) { + //DebugDraw.drawRectRelative(collisionTile.getBounds(), 0xff00ff00); + + int xIndex = collisionTile.getXIndex(); + int yIndex = collisionTile.getYIndex(); + + int offset = 32; + + if(!map.checkTileBounds(xIndex - 1, yIndex) && !map.hasCollidableTile(xIndex - 1, yIndex)) { + if(currentX+bounds.width < (collisionTile.getX() + offset)) { + //DebugDraw.drawRectRelative(map.getTile(0, xIndex-1, yIndex).getBounds(), 0xafff0000); + return currentX - 1; + } + } + + if(!map.checkTileBounds(xIndex + 1, yIndex) && !map.hasCollidableTile(xIndex + 1, yIndex)) { + if(currentX > (collisionTile.getX() + collisionTile.getWidth() - offset)) { + //DebugDraw.drawRectRelative(map.getTile(0, xIndex+1, yIndex).getBounds(), 0xaf0000ff); + return currentX + 1; + } + } + } + + return currentX; + } + + /** + * Continue to check Y coordinate if X was blocked + * @return true if we should continue collision checks + */ + protected boolean continueIfBlock() { + return true; + } + /** * Does client side movement prediction * @@ -167,16 +260,59 @@ public void movementPrediction(Map map, TimeStep timeStep, Vector2f vel) { float newX = predictedPos.x + deltaX; float newY = predictedPos.y + deltaY; - bounds.x = (int)newX; - if( map.rectCollides(bounds) || collidesAgainstEntity(bounds) || collidesAgainstMapObject(bounds)) { + boolean isBlocked = false; + boolean isBlockedByEntity = false; + + bounds.x = (int)newX; + if(map.rectCollides(bounds, 1, xCollisionTilePos)) { + bounds.x = (int)predictedPos.x; + newX = predictedPos.x; + isBlocked = true; + } + else if(collidesAgainstEntity(bounds) || collidesAgainstMapObject(bounds)) { bounds.x = (int)predictedPos.x; newX = predictedPos.x; + isBlocked = true; + isBlockedByEntity = true; } - bounds.y = (int)newY; - if( map.rectCollides(bounds) || collidesAgainstEntity(bounds) || collidesAgainstMapObject(bounds)) { + bounds.y = (int)newY; + if(map.rectCollides(bounds, 1, yCollisionTilePos)) { + bounds.y = (int)predictedPos.y; + newY = predictedPos.y; + isBlocked = true; + } + else if(collidesAgainstEntity(bounds) || collidesAgainstMapObject(bounds)) { bounds.y = (int)predictedPos.y; newY = predictedPos.y; + isBlocked = true; + isBlockedByEntity = true; + } + + if(isBlocked) { + /* some things want to stop dead it their tracks + * if a component is blocked + */ + if(!continueIfBlock()) { + bounds.setLocation(pos); + + newX = pos.x; + newY = pos.y; + } + + /* + * Otherwise determine if the character + * is a couple pixels off and is snagged on + * a corner, if so auto adjust them + */ + else if (!isBlockedByEntity) { + if(deltaX != 0 && deltaY == 0) { + newY = adjustY(xCollisionTilePos, deltaX, (int)(predictedPos.x + deltaX), bounds.y); + } + else if(deltaX == 0 && deltaY != 0) { + newX = adjustX(yCollisionTilePos, deltaY, bounds.x, (int)(predictedPos.y + deltaY)); + } + } } predictedPos.set(newX, newY); diff --git a/src/seventh/client/entities/ClientDroppedItem.java b/src/seventh/client/entities/ClientDroppedItem.java index 015350b..c86b2ec 100644 --- a/src/seventh/client/entities/ClientDroppedItem.java +++ b/src/seventh/client/entities/ClientDroppedItem.java @@ -100,7 +100,7 @@ public void setDroppedItem(Type item) { default: { } } - if(weapon!=null) { + if(weapon != null) { weapon.scale(-0.65f); weapon.rotate( (float)Math.toDegrees(this.orientation)); } @@ -109,11 +109,11 @@ public void setDroppedItem(Type item) { @Override public void render(Canvas canvas, Camera camera, float alpha) { - if(weapon!=null) { + if(weapon != null) { Vector2f cameraPos = camera.getRenderPosition(alpha); float x = (pos.x - cameraPos.x); float y = (pos.y - cameraPos.y); - weapon.setPosition(x-54f, y-24f); + weapon.setPosition(x - 54f, y - 24f); canvas.fillCircle(10f, (int)x, (int)y, 0xafafafff);//0x3f4a4f8f); canvas.drawSprite(weapon); diff --git a/src/seventh/client/entities/ClientEntity.java b/src/seventh/client/entities/ClientEntity.java index 19d3af1..dc5f8e3 100644 --- a/src/seventh/client/entities/ClientEntity.java +++ b/src/seventh/client/entities/ClientEntity.java @@ -1,5 +1,5 @@ /* - * see license.txt + * see license.txt */ package seventh.client.entities; @@ -160,7 +160,7 @@ public void updateState(NetEntity state, long time) { this.bounds.setLocation(pos); this.orientation = (float)Math.toRadians(state.orientation); - this.facing.set(1,0); + this.facing.set(1, 0); Vector2f.Vector2fRotate(facing, orientation, facing); this.updateReceived = true; @@ -218,7 +218,7 @@ protected void updateSounds(Sound[] sounds) { * @param sound */ public void attachSound(Sound sound) { - if(this.attachedSounds==null) { + if(this.attachedSounds == null) { this.attachedSounds = new Sound[8]; } diff --git a/src/seventh/client/entities/ClientFire.java b/src/seventh/client/entities/ClientFire.java index d1308cd..c5cf8cc 100644 --- a/src/seventh/client/entities/ClientFire.java +++ b/src/seventh/client/entities/ClientFire.java @@ -43,7 +43,7 @@ public ClientFire(ClientGame game, Vector2f pos) { public void onRemove(ClientEntity me, ClientGame game) { // fade the fire sound off - if(sound!=null) { + if(sound != null) { game.addForegroundEffect(new Effect() { float volume = sound.getVolume(); diff --git a/src/seventh/client/entities/ClientFlag.java b/src/seventh/client/entities/ClientFlag.java index a15bc35..f3c4afd 100644 --- a/src/seventh/client/entities/ClientFlag.java +++ b/src/seventh/client/entities/ClientFlag.java @@ -82,19 +82,21 @@ public void update(TimeStep timeStep) { long clockTime = timeStep.getGameClock(); - if (carrier != null && carrier.isAlive()) { - long lastUpdate = carrier.getEntity().getLastUpdate(); + if(this.isRelativelyUpdated()) { + fadeAlphaColor = 255; - if ((lastUpdate+150) < clockTime) { - fadeAlphaColor = 255 - ((int)(clockTime-lastUpdate)/3); - if (fadeAlphaColor < 0) fadeAlphaColor = 0; - } - else { - fadeAlphaColor = 255; + if (carrier != null && carrier.isAlive()) { + long lastUpdate = carrier.getEntity().getLastUpdate(); + + if ((lastUpdate+150) < clockTime) { + fadeAlphaColor = 255 - ((int)(clockTime-lastUpdate)/3); + if (fadeAlphaColor < 0) fadeAlphaColor = 0; + } } + } else { - fadeAlphaColor = 255; + fadeAlphaColor = 0; } } @@ -106,7 +108,7 @@ public void render(Canvas canvas, Camera camera, float alpha) { if(flagImg != null) { Vector2f cameraPos = camera.getRenderPosition(alpha); Vector2f flagPos = pos; - if (fadeAlphaColor>0 && carrier != null && carrier.isAlive()) { + if (fadeAlphaColor > 0 && carrier != null && carrier.isAlive()) { flagPos = carrier.getEntity().getRenderPos(alpha); //flagPos.x = flagPos.x + carrier.getEntity().bounds.width/2; //flagPos.y = flagPos.y + carrier.getEntity().bounds.height/2; @@ -115,7 +117,7 @@ public void render(Canvas canvas, Camera camera, float alpha) { float x = (flagPos.x - cameraPos.x); float y = (flagPos.y - cameraPos.y); flagImg.setPosition(x, y); - flagImg.setAlpha(fadeAlphaColor/255.0f); + flagImg.setAlpha(fadeAlphaColor / 255.0f); canvas.drawRawSprite(flagImg); } diff --git a/src/seventh/client/entities/ClientGrenade.java b/src/seventh/client/entities/ClientGrenade.java index df2491d..e9cc305 100644 --- a/src/seventh/client/entities/ClientGrenade.java +++ b/src/seventh/client/entities/ClientGrenade.java @@ -97,7 +97,7 @@ public void render(Canvas canvas, Camera camera, float alpha) { } - if(prevState==null || scale > 1) { + if(prevState == null || scale > 1) { this.orientation += rate * spinDirection; } diff --git a/src/seventh/client/entities/ClientLightBulb.java b/src/seventh/client/entities/ClientLightBulb.java index e147c7c..fa2fd15 100644 --- a/src/seventh/client/entities/ClientLightBulb.java +++ b/src/seventh/client/entities/ClientLightBulb.java @@ -49,8 +49,8 @@ public void updateState(NetEntity state, long time) { super.updateState(state, time); NetLight netLight = (NetLight)state; - light.setColor( (float)(netLight.r/255.0f), (float)(netLight.g/255.0f), (float)(netLight.b/255.0f)); - light.setLuminacity((float)(netLight.luminacity/255.0f)); + light.setColor( (float)(netLight.r / 255.0f), (float)(netLight.g / 255.0f), (float)(netLight.b / 255.0f)); + light.setLuminacity((float)(netLight.luminacity / 255.0f)); light.setLightSize(netLight.size); } diff --git a/src/seventh/client/entities/ClientPlayerEntity.java b/src/seventh/client/entities/ClientPlayerEntity.java index c875de9..4014df3 100644 --- a/src/seventh/client/entities/ClientPlayerEntity.java +++ b/src/seventh/client/entities/ClientPlayerEntity.java @@ -58,8 +58,6 @@ public class ClientPlayerEntity extends ClientControllableEntity { private final ClientWeapon[] WEAPONS = new ClientWeapon[11]; private int health; - private int stamina; - private long invinceableTime; private PlayerSprite sprite; @@ -108,7 +106,7 @@ public ClientPlayerEntity(ClientGame game, ClientPlayer player, Vector2f pos) { this.bounds.width = 24;//16; this.bounds.height = 24; - this.selectionBounds = new Rectangle(40,40); + this.selectionBounds = new Rectangle(40, 40); this.bulletCasingPos = new Vector2f(); this.damaged = new boolean[8]; @@ -191,7 +189,7 @@ public Light getMussleFlash() { public void emitBulletCasing() { - if(!this.isOperatingVehicle() && (this.lastUpdate+200 > this.gameClock)) { + if(!this.isOperatingVehicle() && (this.lastUpdate + 200 > this.gameClock)) { Vector2f.Vector2fMA(getCenterPos(), getFacing(), 10.0f, this.bulletCasingPos); this.effects.spawnBulletCasing(this.bulletCasingPos, getOrientation()); } @@ -261,14 +259,7 @@ public byte getNumberOfGrenades() { public boolean isSmokeGrenades() { return isSmokeGrenades; } - - /** - * @return the stamina - */ - public int getStamina() { - return stamina; - } - + /** * @param team */ @@ -297,7 +288,7 @@ public void changeTeam(ClientTeam team) { protected int calculateMovementSpeed() { int speed = PLAYER_SPEED; int mSpeed = speed; - if(currentState==State.WALKING) { + if(currentState == State.WALKING) { mSpeed = (int)( (float)speed * WALK_SPEED_FACTOR); } else if(currentState == State.SPRINTING) { @@ -344,7 +335,6 @@ public void updateState(NetEntity state, long time) { } this.health = ps.health; - this.stamina = ps.stamina; this.numberOfGrenades = ps.grenades; this.isSmokeGrenades = ps.isSmokeGrenades; @@ -472,7 +462,7 @@ protected void updateWeaponState(NetWeapon netWeapon, long time) { } } - if(weapon!=null) { + if(weapon != null) { weapon.updateState(netWeapon, time); } } @@ -502,8 +492,8 @@ public void update(TimeStep timeStep) { this.sprite.update(timeStep); - if ((lastUpdate+150) < clockTime && !isControlledByLocalPlayer()) { - fadeAlphaColor = 255 - ((int)(clockTime-lastUpdate)/3); + if ((lastUpdate + 150) < clockTime && !isControlledByLocalPlayer()) { + fadeAlphaColor = 255 - ((int)(clockTime - lastUpdate) / 3); if (fadeAlphaColor < 0) fadeAlphaColor = 0; } else { @@ -524,7 +514,7 @@ public void update(TimeStep timeStep) { Vector2f.Vector2fMA(mussleFlash.getPos(), getFacing(), 40.0f, mussleFlash.getPos()); mussleFlash.setOrientation(getOrientation()); - mussleFlash.setLuminacity((fadeAlphaColor-150)/255.0f); + mussleFlash.setLuminacity((fadeAlphaColor - 150) / 255.0f); mussleFlash.setLuminacity(0.9f); mussleFlash.setColor(0.7f,.7f,0.5f); @@ -537,7 +527,7 @@ public void update(TimeStep timeStep) { * would cause damageDelta to be < 0) */ if((previousNetUpdate+400) >= clockTime) { - for(int i = 0; i < this.damaged.length;i++) { + for(int i = 0; i < this.damaged.length; i++) { if(this.damaged[i]) { onDamage(); this.damaged[i] = false; @@ -545,7 +535,7 @@ public void update(TimeStep timeStep) { } } else { - for(int i = 0; i < this.damaged.length;i++) { + for(int i = 0; i < this.damaged.length; i++) { this.damaged[i] = false; } } @@ -668,7 +658,7 @@ public void kill(Type meansOfDeath, Vector2f locationOfDeath) { - if(anim!=null) { + if(anim != null) { // Objective game type keeps the dead bodies around boolean persist = this.game.getGameType().equals(GameType.Type.OBJ); @@ -690,7 +680,7 @@ public void kill(Type meansOfDeath, Vector2f locationOfDeath) { */ @Override public void render(Canvas canvas, Camera camera, float alpha) { - canvas.setCompositeAlpha(fadeAlphaColor/255.0f); + canvas.setCompositeAlpha(fadeAlphaColor / 255.0f); canvas.setColor(teamColor, fadeAlphaColor); //states[currentState].render(canvas, camera) @@ -708,7 +698,7 @@ public void render(Canvas canvas, Camera camera, float alpha) { if (invinceableTime > 0 || isSelected()) { canvas.setColor(teamColor, 122); canvas.fillCircle(20, rx - (bounds.width/2f), ry - (bounds.height/2f), null); - canvas.drawCircle(21, rx - (bounds.width/2f)-1f, ry - (bounds.height/2f)-1f, 0xff000000); + canvas.drawCircle(21, rx - (bounds.width/2f) - 1f, ry - (bounds.height/2f) - 1f, 0xff000000); } } diff --git a/src/seventh/client/entities/vehicles/ClientTank.java b/src/seventh/client/entities/vehicles/ClientTank.java index a75d3a4..5128ba3 100644 --- a/src/seventh/client/entities/vehicles/ClientTank.java +++ b/src/seventh/client/entities/vehicles/ClientTank.java @@ -113,9 +113,9 @@ public void updateState(NetEntity state, long time) { NetTank netTank = (NetTank)state; this.currentState = State.fromNetValue(netTank.state); - if(this.currentState==State.DESTROYED) { + if(this.currentState == State.DESTROYED) { TankSprite tankSprite = getTankSprite(); - if(tankSprite != null&&!tankSprite.isDestroyed()) { + if(tankSprite != null && !tankSprite.isDestroyed()) { tankSprite.setDestroyed(true); game.addForegroundEffect(new RenderableEffect(tankSprite) { @@ -164,7 +164,7 @@ public void update(TimeStep timeStep, ParticleData particles) { if(netTank.operatorId != SeventhConstants.INVALID_PLAYER_ID) { ClientPlayer clientPlayer = game.getPlayers().getPlayer(netTank.operatorId); - if(clientPlayer!=null) { + if(clientPlayer != null) { setOperator(clientPlayer.getEntity()); } } @@ -280,7 +280,7 @@ public void update(TimeStep timeStep) { float distanceSq = (nextState.posX - previousTrackMark.x) * (nextState.posX - previousTrackMark.x) + (nextState.posY - previousTrackMark.y) * (nextState.posY - previousTrackMark.y); - if(distanceSq > 12*12) { + if(distanceSq > 12 * 12) { previousTrackMark.set(nextState.posX, nextState.posY); // left track diff --git a/src/seventh/client/gfx/CompoundCursor.java b/src/seventh/client/gfx/CompoundCursor.java index 7c55bef..a96205b 100644 --- a/src/seventh/client/gfx/CompoundCursor.java +++ b/src/seventh/client/gfx/CompoundCursor.java @@ -44,7 +44,29 @@ public CompoundCursor activateB() { this.active = b; return this; } - + + @Override + public boolean isClampEnabled() { + return this.active.isClampEnabled(); + } + + @Override + public void setClampEnabled(boolean isClampEnabled) { + this.a.setClampEnabled(isClampEnabled); + this.b.setClampEnabled(isClampEnabled); + } + + @Override + public boolean isInverted() { + return this.active.isInverted(); + } + + @Override + public void setInverted(boolean isInverted) { + this.a.setInverted(isInverted); + this.b.setInverted(isInverted); + } + @Override public float getAccuracy() { return this.active.getAccuracy(); @@ -64,6 +86,11 @@ public int getColor() { public Vector2f getCursorPos() { return this.active.getCursorPos(); } + + @Override + public Vector2f getPreviousCursorPos() { + return this.active.getPreviousCursorPos(); + } @Override public float getMouseSensitivity() { @@ -104,6 +131,18 @@ public void moveTo(int x, int y) { this.a.moveTo(x, y); this.b.moveTo(x, y); } + + @Override + public void snapTo(int x, int y) { + this.a.snapTo(x, y); + this.b.snapTo(x, y); + } + + @Override + public void snapTo(Vector2f screenPos) { + this.a.snapTo(screenPos); + this.b.snapTo(screenPos); + } @Override public void setAccuracy(float accuracy) { @@ -146,3 +185,4 @@ public void render(Canvas canvas) { protected void doRender(Canvas canvas) { } } + diff --git a/src/seventh/client/gfx/Cursor.java b/src/seventh/client/gfx/Cursor.java index d803587..eab8378 100644 --- a/src/seventh/client/gfx/Cursor.java +++ b/src/seventh/client/gfx/Cursor.java @@ -18,7 +18,7 @@ */ public abstract class Cursor implements Updatable { - private Vector2f cursorPos; + private Vector2f cursorPos, previousCursorPos; private Rectangle bounds; private boolean isVisible; @@ -29,6 +29,7 @@ public abstract class Cursor implements Updatable { private int prevX, prevY; private boolean isInverted; + private boolean isClampEnabled; /** * @param bounds @@ -37,10 +38,26 @@ public abstract class Cursor implements Updatable { public Cursor(Rectangle bounds) { this.bounds = bounds; this.cursorPos = new Vector2f(); + this.previousCursorPos = new Vector2f(); this.isVisible = true; this.mouseSensitivity = 1.0f; this.accuracy = 1.0f; this.isInverted = false; + this.isClampEnabled = true; + } + + /** + * @return the isClampEnabled + */ + public boolean isClampEnabled() { + return isClampEnabled; + } + + /** + * @param isClampEnabled the isClampEnabled to set + */ + public void setClampEnabled(boolean isClampEnabled) { + this.isClampEnabled = isClampEnabled; } /** @@ -133,6 +150,40 @@ private void moveNativeMouse(int x, int y) { * move outside of the screen */ private void clamp() { + int width = SeventhGame.DEFAULT_MINIMIZED_SCREEN_WIDTH; + int height = SeventhGame.DEFAULT_MINIMIZED_SCREEN_HEIGHT; + + if(!this.isClampEnabled) { + if(this.cursorPos.x < 0 || + this.cursorPos.y < 0 || + this.cursorPos.x > width || + this.cursorPos.y > height) { + + Gdx.input.setCursorCatched(false); + + this.prevX = (int) this.previousCursorPos.x; + this.prevY = (int) this.previousCursorPos.y; + + int windowWidth = Gdx.graphics.getWidth(); + int windowHeight = Gdx.graphics.getHeight(); + + int nativeMouseX = (int) ((this.cursorPos.x/(float)width) * (float)windowWidth); + int nativeMouseY = (int) ((this.cursorPos.y/(float)height) * (float)windowHeight); + + nativeMouseX = Math.min(windowWidth, nativeMouseX); + nativeMouseY = Math.min(windowHeight, nativeMouseY); + + nativeMouseX = Math.max(0, nativeMouseX); + nativeMouseY = Math.max(0, nativeMouseY); + + moveNativeMouse(nativeMouseX, nativeMouseY); + } + else { + Gdx.input.setCursorCatched(true); + } + + } + if(this.cursorPos.x < 0) { this.cursorPos.x = 0f; } @@ -141,9 +192,6 @@ private void clamp() { this.cursorPos.y = 0f; } - int width = SeventhGame.DEFAULT_MINIMIZED_SCREEN_WIDTH; - int height = SeventhGame.DEFAULT_MINIMIZED_SCREEN_HEIGHT; - if(this.cursorPos.x > width) { this.cursorPos.x = width; } @@ -151,6 +199,7 @@ private void clamp() { if(this.cursorPos.y > height) { this.cursorPos.y = height; } + } /** @@ -197,16 +246,43 @@ public void setVisible(boolean isVisible) { } /** - * Moves the cursor to the specified location + * Instantly moves the cursor to the specified location. * * @param x * @param y */ - public void moveTo(int x, int y) { - if(isVisible()) { + public void snapTo(int x, int y) { + this.cursorPos.set(x, y); + this.previousCursorPos.set(this.cursorPos); + } + + + /** + * Instantly moves the cursor to the specified location. + * + * @param screenPos + */ + public void snapTo(Vector2f screenPos) { + snapTo((int)screenPos.x, (int)screenPos.y); + } + + /** + * Moves the cursor towards the specified location + * + * @param x + * @param y + */ + public void moveTo(int x, int y) { + // convert window coordinates to game screen coordinates + x = (int) (((float)x / (float)Gdx.graphics.getWidth()) * (float)SeventhGame.DEFAULT_MINIMIZED_SCREEN_WIDTH); + y = (int) (((float)y / (float)Gdx.graphics.getHeight()) * (float)SeventhGame.DEFAULT_MINIMIZED_SCREEN_HEIGHT); + + if(isVisible()) { float deltaX = this.mouseSensitivity * (this.prevX - x); float deltaY = this.mouseSensitivity * (this.prevY - y); + this.previousCursorPos.set(this.cursorPos); + if(this.isInverted) { this.cursorPos.x += deltaX; this.cursorPos.y += deltaY; @@ -234,6 +310,8 @@ public void moveByDelta(float dx, float dy) { this.prevX = (int)cursorPos.x; this.prevY = (int)cursorPos.y; + this.previousCursorPos.set(this.cursorPos); + if(this.isInverted) { this.cursorPos.x -= deltaX; this.cursorPos.y -= deltaY; @@ -267,6 +345,13 @@ public Vector2f getCursorPos() { return cursorPos; } + /** + * @return the previousCursorPos + */ + public Vector2f getPreviousCursorPos() { + return previousCursorPos; + } + /** * Draws the cursor on the screen * diff --git a/src/seventh/client/gfx/ImageCursor.java b/src/seventh/client/gfx/ImageCursor.java index ba210e0..d897eb0 100644 --- a/src/seventh/client/gfx/ImageCursor.java +++ b/src/seventh/client/gfx/ImageCursor.java @@ -64,6 +64,6 @@ public void update(TimeStep timeStep) { @Override protected void doRender(Canvas canvas) { Vector2f cursorPos = getCursorPos(); - canvas.drawImage(cursorImg, (int)cursorPos.x - imageOffset.x, (int)cursorPos.y - imageOffset.y, null); + canvas.drawImage(cursorImg, (int)cursorPos.x - imageOffset.x, (int)cursorPos.y - imageOffset.y, null); } } diff --git a/src/seventh/client/gfx/WeaponClassDialog.java b/src/seventh/client/gfx/WeaponClassDialog.java index 6295eb0..5f8c8ce 100644 --- a/src/seventh/client/gfx/WeaponClassDialog.java +++ b/src/seventh/client/gfx/WeaponClassDialog.java @@ -30,8 +30,6 @@ public class WeaponClassDialog extends Widget { private Label title; private Theme theme; - private static final int NUMBER_OF_WEAPON_CLASSES = 7; - private Button[] weaponClasses; private Label[] weaponClassDescriptions; private Button cancel; @@ -49,8 +47,8 @@ public WeaponClassDialog(InGameOptionsDialog owner, ClientConnection network, Th this.team = ClientTeam.ALLIES; this.theme = theme; - this.weaponClasses = new Button[NUMBER_OF_WEAPON_CLASSES]; - this.weaponClassDescriptions = new Label[NUMBER_OF_WEAPON_CLASSES]; + this.weaponClasses = new Button[7]; + this.weaponClassDescriptions = new Label[7]; createUI(); } @@ -91,20 +89,6 @@ private void createUI() { Rectangle bounds = getBounds(); - setupTitleLabel(bounds); - - refreshButtons(); - - setupCancelButton(bounds); - - addWidget(cancel); - addWidget(title); - } - - /** - * @param bounds - */ - private void setupTitleLabel(final Rectangle bounds) { this.title = new Label("Select a Weapon"); this.title.setTheme(theme); //this.title.setForegroundColor(0xffffffff); @@ -114,12 +98,9 @@ private void setupTitleLabel(final Rectangle bounds) { this.title.setFont(theme.getSecondaryFontName()); this.title.setHorizontalTextAlignment(TextAlignment.CENTER); this.title.setTextSize(22); - } - - /** - * @param bounds - */ - private void setupCancelButton(final Rectangle bounds) { + + refreshButtons(); + this.cancel = new Button(); this.cancel.setText("Cancel"); this.cancel.setBounds(new Rectangle(0,0,100,40)); @@ -137,16 +118,21 @@ public void onButtonClicked(ButtonEvent event) { owner.close(); } }); + + addWidget(cancel); + addWidget(title); } private Vector2f refreshButtons() { + Rectangle bounds = getBounds(); + + Vector2f pos = new Vector2f(); + pos.x = bounds.x + 120; + pos.y = bounds.y + 50; + + int yInc = 50; - initWeaponClasses(); - return setupWeaponClasses(); - } - - private void initWeaponClasses() { for(int i = 0; i < weaponClasses.length; i++) { if( this.weaponClasses[i] != null ) { removeWidget(weaponClasses[i]); @@ -158,108 +144,97 @@ private void initWeaponClasses() { this.weaponClassDescriptions[i] = null; } } - } - - private Vector2f setupWeaponClasses() { - Rectangle bounds = getBounds(); - Vector2f pos = new Vector2f(); - pos.x = bounds.x + 120; - pos.y = bounds.y + 50; - - int yInc = 50; switch(team) { case AXIS: - for (int weaponClassIndex = 0; weaponClassIndex < NUMBER_OF_WEAPON_CLASSES; weaponClassIndex++) { - setupAXISWeaponClass(weaponClassIndex, pos); - if (weaponClassIndex < NUMBER_OF_WEAPON_CLASSES - 1) { - pos.y += yInc; - } - } + this.weaponClasses[0] =setupButton(pos, Type.MP40); + this.weaponClassDescriptions[0] = setupLabel(pos, Type.MP40); pos.y += yInc; + + this.weaponClasses[1] =setupButton(pos, Type.MP44); + this.weaponClassDescriptions[1] = setupLabel(pos, Type.MP44); pos.y += yInc; + + this.weaponClasses[2] =setupButton(pos, Type.KAR98); + this.weaponClassDescriptions[2] = setupLabel(pos, Type.KAR98); pos.y += yInc; break; case ALLIES: default: - for (int weaponClassIndex = 0; weaponClassIndex < NUMBER_OF_WEAPON_CLASSES; weaponClassIndex++) { - setupALLIESWeaponClass(weaponClassIndex, pos); - if (weaponClassIndex < NUMBER_OF_WEAPON_CLASSES - 1) { - pos.y += yInc; - } - } - break; - } + this.weaponClasses[0] =setupButton(pos, Type.THOMPSON); + this.weaponClassDescriptions[0] = setupLabel(pos, Type.THOMPSON); pos.y += yInc; - return pos; - } - - private static final Type[] AXIS_WEAPON_TYPES = { - // AXIS only - Type.MP40, - Type.MP44, - Type.KAR98, - - // AXIS, ALLIES share - Type.RISKER, - Type.SHOTGUN, - Type.ROCKET_LAUNCHER, - Type.FLAME_THROWER - }; - - private static final Type[] ALLIES_WEAPON_TYPES = { - // ALLIES only - Type.THOMPSON, - Type.M1_GARAND, - Type.SPRINGFIELD, + this.weaponClasses[1] =setupButton(pos, Type.M1_GARAND); + this.weaponClassDescriptions[1] = setupLabel(pos, Type.M1_GARAND); pos.y += yInc; + + this.weaponClasses[2] =setupButton(pos, Type.SPRINGFIELD); + this.weaponClassDescriptions[2] = setupLabel(pos, Type.SPRINGFIELD); pos.y += yInc; + break; - // AXIS, ALLIES share - Type.RISKER, - Type.SHOTGUN, - Type.ROCKET_LAUNCHER, - Type.FLAME_THROWER - }; - - private void setupAXISWeaponClass(int weaponClassIndex, Vector2f pos) { - this.weaponClasses[weaponClassIndex] = setupButton(pos, AXIS_WEAPON_TYPES[weaponClassIndex]); - this.weaponClassDescriptions[weaponClassIndex] = setupLabel(pos, AXIS_WEAPON_TYPES[weaponClassIndex]); - } - - private void setupALLIESWeaponClass(int weaponClassIndex, Vector2f pos) { - this.weaponClasses[weaponClassIndex] = setupButton(pos, ALLIES_WEAPON_TYPES[weaponClassIndex]); - this.weaponClassDescriptions[weaponClassIndex] = setupLabel(pos, ALLIES_WEAPON_TYPES[weaponClassIndex]); + } + this.weaponClasses[3] =setupButton(pos, Type.RISKER); + this.weaponClassDescriptions[3] = setupLabel(pos, Type.RISKER); pos.y += yInc; + + this.weaponClasses[4] =setupButton(pos, Type.SHOTGUN); + this.weaponClassDescriptions[4] = setupLabel(pos, Type.SHOTGUN); pos.y += yInc; + + this.weaponClasses[5] =setupButton(pos, Type.ROCKET_LAUNCHER); + this.weaponClassDescriptions[5] = setupLabel(pos, Type.ROCKET_LAUNCHER); pos.y += yInc; + + this.weaponClasses[6] =setupButton(pos, Type.FLAME_THROWER); + this.weaponClassDescriptions[6] = setupLabel(pos, Type.FLAME_THROWER); + + return pos; } private String getClassDescription(Type type) { String message = ""; switch(type) { case THOMPSON: - message = new ThompsonDescription().getDescription(); + message = "Thompson | 30/180 rnds\n" + + "Pistol | 9/27 rnds \n" + + "2 Frag Grenades"; break; case M1_GARAND: - message = new M1GarandDescription().getDescription(); + message = "M1 Garand | 8/40 rnds\n" + + "Pistol | 9/27 rnds \n" + + "2 Smoke Grenades"; break; case SPRINGFIELD: - message = new SpringfieldDescription().getDescription(); + message = "Springfield | 5/35 rnds\n" + + "Pistol | 9/27 rnds \n" + + "1 Frag Grenades"; break; case MP40: - message = new Mp40Description().getDescription(); + message = "MP40 | 32/160 rnds\n" + + "Pistol | 9/27 rnds \n" + + "2 Frag Grenades"; break; case MP44: - message = new Mp44Description().getDescription(); + message = "MP44 | 30/120 rnds\n" + + "Pistol | 9/27 rnds \n" + + "2 Smoke Grenades"; break; case KAR98: - message = new Kar98Description().getDescription(); + message = "KAR-98 | 5/25 rnds\n" + + "Pistol | 9/27 rnds \n" + + "1 Frag Grenade"; break; case RISKER: - message = new RiskerDescription().getDescription(); + message = "MG-z | 21/42 rnds\n" + + "Pistol | 9/27 rnds"; break; case SHOTGUN: - message = new ShotgunDescription().getDescription(); + message = "Shotgun | 5/35 rnds\n" + + "Pistol | 9/27 rnds"; break; case ROCKET_LAUNCHER: - message = new RocketLauncherDescription().getDescription(); + message = "M1 | 5 rnds\n" + + "Pistol | 9/27 rnds\n" + + "5 Frag Grenades"; break; case FLAME_THROWER: - message = new FlameThrowerDescription().getDescription(); + message = "Flame Thrower\n" + + "Pistol | 9/27 rnds\n" + + "2 Frag Grenades"; break; default:; } diff --git a/src/seventh/client/gfx/effects/ClientGameEffects.java b/src/seventh/client/gfx/effects/ClientGameEffects.java index 7d38b95..ecb17cc 100644 --- a/src/seventh/client/gfx/effects/ClientGameEffects.java +++ b/src/seventh/client/gfx/effects/ClientGameEffects.java @@ -63,7 +63,7 @@ public ClientGameEffects(Random random) { this.playerBloodEmitters = new Emitter[SeventhConstants.MAX_PLAYERS*3]; for(int i = 0; i < this.playerBloodEmitters.length; i++) { - this.playerBloodEmitters[i] = Emitters.newBloodEmitter(new Vector2f(), 5, 10_000, 30) + this.playerBloodEmitters[i] = Emitters.newBloodEmitter(new Vector2f(), 5, 20_000, 30) .kill(); } diff --git a/src/seventh/client/gfx/effects/particle_system/Emitters.java b/src/seventh/client/gfx/effects/particle_system/Emitters.java index 07fb1d0..0a4a7a9 100644 --- a/src/seventh/client/gfx/effects/particle_system/Emitters.java +++ b/src/seventh/client/gfx/effects/particle_system/Emitters.java @@ -103,7 +103,7 @@ public static Emitter newBloodEmitter(Vector2f pos, int maxParticles, int emitte emitter.addParticleUpdater(new KillUpdater()); emitter.addParticleUpdater(new MovementParticleUpdater(0, 2)); - emitter.addParticleUpdater(new AlphaDecayUpdater(0f, 0.9878f)); + emitter.addParticleUpdater(new AlphaDecayUpdater(0f, 0.994898f)); emitter.addParticleRenderer(new SpriteParticleRenderer()); return emitter; diff --git a/src/seventh/client/gfx/hud/Hud.java b/src/seventh/client/gfx/hud/Hud.java index a5c207b..59fc5c8 100644 --- a/src/seventh/client/gfx/hud/Hud.java +++ b/src/seventh/client/gfx/hud/Hud.java @@ -375,11 +375,9 @@ public void render(Canvas canvas, Camera camera, float alpha) { } drawHealth(canvas, ent.getHealth()); - drawStamina(canvas, ent.getStamina()); } else { drawHealth(canvas, 0); - drawStamina(canvas, 0); } @@ -455,10 +453,10 @@ private void drawGrenadeIcons(Canvas canvas, int numberOfGrenades) { int imageWidth = sprite.getRegionWidth(); - canvas.drawImage(sprite, 10, canvas.getHeight() - sprite.getRegionHeight() - 40, 0xffffff00); + canvas.drawImage(sprite, 10, canvas.getHeight() - sprite.getRegionHeight() - 20, 0xffffff00); canvas.setFont("Consola", 14); canvas.boldFont(); - RenderFont.drawShadedString(canvas, "x " + numberOfGrenades, imageWidth+20, canvas.getHeight() - 50, 0xffffff00); + RenderFont.drawShadedString(canvas, "x " + numberOfGrenades, imageWidth+20, canvas.getHeight() - 30, 0xffffff00); } @@ -615,33 +613,6 @@ private void drawHealth(Canvas canvas, int health) { } - private void drawStamina(Canvas canvas, int stamina) { - int x = 15; - int y = canvas.getHeight() - 25; - - canvas.fillRect( x, y, 100, 15, 0x8f4a5f8f ); - if (stamina > 0) { - canvas.fillRect( x, y, (100 * stamina/100), 15, 0xff3a9aFF ); - } - - // add a shadow effect - canvas.drawLine( x, y+1, x+100, y+1, 0x8f000000 ); - canvas.drawLine( x, y+2, x+100, y+2, 0x5f000000 ); - canvas.drawLine( x, y+3, x+100, y+3, 0x2f000000 ); - canvas.drawLine( x, y+4, x+100, y+4, 0x0f000000 ); - canvas.drawLine( x, y+5, x+100, y+5, 0x0b000000 ); - - y = y+15; - canvas.drawLine( x, y-5, x+100, y-5, 0x0b000000 ); - canvas.drawLine( x, y-4, x+100, y-4, 0x0f000000 ); - canvas.drawLine( x, y-3, x+100, y-3, 0x2f000000 ); - canvas.drawLine( x, y-2, x+100, y-2, 0x5f000000 ); - canvas.drawLine( x, y-1, x+100, y-1, 0x8f000000 ); - - canvas.drawRect( x, y-15, 101, 15, 0xff000000 ); - canvas.drawSprite(Art.staminaIcon, x + 108, y - 14, null); - } - private void drawBombProgressBar(Canvas canvas, Camera camera) { this.bombProgressBarView.render(canvas, camera, 0); } diff --git a/src/seventh/client/gfx/hud/Scoreboard.java b/src/seventh/client/gfx/hud/Scoreboard.java index c9d5a7a..d51f04a 100644 --- a/src/seventh/client/gfx/hud/Scoreboard.java +++ b/src/seventh/client/gfx/hud/Scoreboard.java @@ -132,7 +132,7 @@ private int drawTeam(Canvas canvas, List team, int x, int y) { } if(player == game.getLocalPlayer()) { - canvas.fillRect(x-5, y-15, 650, 20, 0x5fffffff); + canvas.fillRect(x-5, y-15, 680, 20, 0x5fffffff); } String output = String.format("%-30s %-13d %-13d %-10d %-8d %-13d", diff --git a/src/seventh/client/inputs/CameraController.java b/src/seventh/client/inputs/CameraController.java index 451f906..d17056f 100644 --- a/src/seventh/client/inputs/CameraController.java +++ b/src/seventh/client/inputs/CameraController.java @@ -54,8 +54,10 @@ public class CameraController implements Updatable { private int viewportWidth, viewportHeight; private boolean isCameraRoaming, isFastCamera; - private boolean isCameraActive; + private boolean isCameraActive; private boolean isIronSights; + + private int previousKeys; private Cursor cursor; @@ -81,7 +83,7 @@ public CameraController(ClientGame game) { this.cameraShakeBounds = new Rectangle(600, 600); this.playerVelocity = new Vector2f(); - + this.bounds = new Rectangle(); this.viewportWidth = this.camera.getViewPort().width; this.viewportHeight = this.camera.getViewPort().height; @@ -151,7 +153,7 @@ public void onVideoReload(Camera camera) { * @return the isCameraRoaming */ public boolean isCameraRoaming() { - return isCameraRoaming && (this.localPlayer.isPureSpectator()||this.localPlayer.isCommander()); + return isCameraRoaming && (this.localPlayer.isPureSpectator() || this.localPlayer.isCommander()); } /* (non-Javadoc) @@ -174,14 +176,14 @@ private void applyPlayerMouseInput(float mx, float my) { if(mx < threshold) { this.playerVelocity.x = -1; } - else if(mx > this.viewportWidth-threshold) { + else if(mx > this.viewportWidth - threshold) { this.playerVelocity.x = 1; } if(my < threshold) { this.playerVelocity.y = -1; } - else if(my > this.viewportHeight-threshold) { + else if(my > this.viewportHeight - threshold) { this.playerVelocity.y = 1; } } @@ -301,18 +303,24 @@ private void updateCameraForRoamingMovements(TimeStep timeStep) { double dt = timeStep.asFraction(); int newX = (int)Math.round(pos.x + playerVelocity.x * movementSpeed * dt); - int newY = (int)Math.round(pos.y + playerVelocity.y * movementSpeed * dt); + int newY = (int)Math.round(pos.y + playerVelocity.y * movementSpeed * dt); + bounds.x = newX; - if( cameraForRoamingMovementsIsOutOfMap() ) { + if( map.checkBounds(bounds.x, bounds.y) || + ((bounds.x < bounds.width/2) || (bounds.y < bounds.height/2)) || + map.checkBounds(bounds.x + bounds.width/2, bounds.y + bounds.height/2) ) { bounds.x = (int)pos.x; - } + } + bounds.y = newY; - if( cameraForRoamingMovementsIsOutOfMap() ) { + if( map.checkBounds(bounds.x, bounds.y) || + ((bounds.x < bounds.width/2) || (bounds.y < bounds.height/2)) || + map.checkBounds(bounds.x + bounds.width/2, bounds.y + bounds.height/2) ) { bounds.y = (int)pos.y; } - + pos.x = bounds.x; pos.y = bounds.y; @@ -323,21 +331,6 @@ private void updateCameraForRoamingMovements(TimeStep timeStep) { Sounds.setPosition(cameraCenterAround); } } - - /** - * To remove duplicated code and for readability in updateCameraForRoamingMovements(TimeStep timeStep) function - * - */ - private boolean cameraForRoamingMovementsIsOutOfMap() { - final boolean boundsXYIsOutOfMap = map.checkBounds(bounds.x, bounds.y); - final boolean boundsXIsLowerThanViewPortCenterX = bounds.x < bounds.width / 2; - final boolean boundsYIsLowerThanViewPortCenterY = bounds.y < bounds.height / 2; - final boolean boundsCenterIsOutOfMap = map.checkBounds(bounds.x + bounds.width/2, bounds.y + bounds.height/2); - - return boundsXYIsOutOfMap || - (boundsXIsLowerThanViewPortCenterX || boundsYIsLowerThanViewPortCenterY) || - boundsCenterIsOutOfMap; - } /** @@ -346,10 +339,10 @@ private boolean cameraForRoamingMovementsIsOutOfMap() { * @param timeStep */ private void updateCameraForPlayerMovements(TimeStep timeStep) { - if(this.localPlayer.isAlive()||this.localPlayer.isSpectating()) { + if(this.localPlayer.isAlive() || this.localPlayer.isSpectating()) { ClientControllableEntity entity = game.getLocalPlayerFollowingEntity(); - if(entity!=null) { + if(entity != null) { if( entity.isOperatingVehicle() ) { entity = entity.getVehicle(); } @@ -358,22 +351,27 @@ private void updateCameraForPlayerMovements(TimeStep timeStep) { cursor.setAccuracy(entity.getAimingAccuracy()); - if(!this.localPlayer.isSpectating() && this.isCameraActive && (this.config.getFollowReticleEnabled() || this.isIronSights) ) { - Vector2f.Vector2fMA(entity.getCenterPos(), entity.getFacing(), config.getFollowReticleOffset(), cameraCenterAround); - + boolean adjustCameraView = !this.localPlayer.isSpectating() && this.isCameraActive && + (this.config.getFollowReticleEnabled() || this.isIronSights); + + + if(adjustCameraView) { + Vector2f.Vector2fMA(entity.getCenterPos(), entity.getFacing(), config.getFollowReticleOffset(), cameraCenterAround); + // smooth out the camera previousCameraPos.set(cameraCenterAround); Vector2f.Vector2fLerp(cameraCenterAround, previousCameraPos, 0.15f, cameraCenterAround); + } - else { + else { cameraCenterAround.set(entity.getCenterPos()); } - //cameraCenterAround.set(entity.getPos()); Vector2f.Vector2fRound(cameraCenterAround, cameraCenterAround);; camera.centerAround(cameraCenterAround); - Sounds.setPosition(cameraCenterAround); + Sounds.setPosition(entity.getCenterPos()); + /* Calculates the Fog Of War */ @@ -384,7 +382,7 @@ private void updateCameraForPlayerMovements(TimeStep timeStep) { /* only calculate every 100 ms */ nextFOWUpdate = 100; - } + } } } } diff --git a/src/seventh/client/inputs/ControllerInput.java b/src/seventh/client/inputs/ControllerInput.java index 3536bc8..130598c 100644 --- a/src/seventh/client/inputs/ControllerInput.java +++ b/src/seventh/client/inputs/ControllerInput.java @@ -71,7 +71,7 @@ public static ControllerButtons fromKey(int key) { // adjust offset from the keyboard keys key -= NumberOfKeyboardKeys; - if(key>-1&&key -1 && key < values.length) { return values[key]; } return null; @@ -160,7 +160,7 @@ public boolean isLeftTriggerDown() { * @return true if the right trigger is down. */ public boolean isRightTriggerDown() { - return this.triggers < -this.triggerSensitivity; + return this.triggers < -(this.triggerSensitivity); } /** @@ -251,28 +251,28 @@ public boolean isButtonDown(ControllerButtons button) { } public boolean isXAxisMovedLeftOnLeftJoystick() { - return movements[1] < -this.leftJoystickSensitivity; + return movements[1] < -(this.leftJoystickSensitivity); } public boolean isXAxisMovedRightOnLeftJoystick() { return movements[1] > this.leftJoystickSensitivity; } public boolean isXAxisMovedLeftOnRightJoystick() { - return movements[3] < -this.rightJoystickSensitivity; + return movements[3] < -(this.rightJoystickSensitivity); } public boolean isXAxisMovedRightOnRightJoystick() { return movements[3] > this.rightJoystickSensitivity; } public boolean isYAxisMovedUpOnLeftJoystick() { - return movements[0] < -this.leftJoystickSensitivity; + return movements[0] < -(this.leftJoystickSensitivity); } public boolean isYAxisMovedDownOnLeftJoystick() { return movements[0] > this.leftJoystickSensitivity; } public boolean isYAxisMovedUpOnRightJoystick() { - return movements[2] < -this.rightJoystickSensitivity; + return movements[2] < -(this.rightJoystickSensitivity); } public boolean isYAxisMovedDownOnRightJoystick() { return movements[2] > this.rightJoystickSensitivity; @@ -347,7 +347,7 @@ public void connected(Controller controller) { @Override public boolean buttonUp(Controller controller, int button) { - if(button >-1 && button < this.buttons.length) + if(button > -1 && button < this.buttons.length) this.buttons[button] = false; System.out.println("ButtonUp:" + button); @@ -356,7 +356,7 @@ public boolean buttonUp(Controller controller, int button) { @Override public boolean buttonDown(Controller controller, int button) { - if(button >-1 && button < this.buttons.length) + if(button > -1 && button < this.buttons.length) this.buttons[button] = true; // System.out.println("ButtonDown:" + button); @@ -365,11 +365,11 @@ public boolean buttonDown(Controller controller, int button) { @Override public boolean axisMoved(Controller controller, int axisCode, float value) { - if(axisCode==4) { + if(axisCode == 4) { triggers = value; } - if(axisCode<4) { + if(axisCode < 4) { movements[axisCode] = value; } diff --git a/src/seventh/client/inputs/InputMap.java b/src/seventh/client/inputs/InputMap.java index d5a723c..fafa570 100644 --- a/src/seventh/client/inputs/InputMap.java +++ b/src/seventh/client/inputs/InputMap.java @@ -51,7 +51,7 @@ public boolean scrolled(int notches) { if(notches < 0) { if(this.scroller[0] != null) { Action action = this.actions.get(scroller[0]); - if(action!=null) { + if(action != null) { action.action(); } } @@ -59,7 +59,7 @@ public boolean scrolled(int notches) { else { if(this.scroller[1] != null) { Action action = this.actions.get(scroller[1]); - if(action!=null) { + if(action != null) { action.action(); } } @@ -120,7 +120,7 @@ public void pollInput() { int key = keys.next(); if(isKeyDown(keys.next())) { Action action = this.actions.get(this.keymap.get(key)); - if(action!=null) { + if(action != null) { action.action(); } } @@ -131,7 +131,7 @@ public void pollInput() { int button = keys.next(); if(isButtonDown(keys.next())) { Action action = this.actions.get(this.buttonmap.get(button)); - if(action!=null) { + if(action != null) { action.action(); } } @@ -143,7 +143,7 @@ public void pollInput() { int button = keys.next(); if(controllerInput.isButtonDown(keys.next())) { Action action = this.actions.get(this.controllermap.get(button)); - if(action!=null) { + if(action != null) { action.action(); } } @@ -155,7 +155,7 @@ public void pollInput() { String name = povButtons[i]; if(name != null) { Action action = this.actions.get(name); - if(action!=null) { + if(action != null) { action.action(); break; } diff --git a/src/seventh/client/inputs/Inputs.java b/src/seventh/client/inputs/Inputs.java index 8f11094..53121ea 100644 --- a/src/seventh/client/inputs/Inputs.java +++ b/src/seventh/client/inputs/Inputs.java @@ -44,7 +44,7 @@ public void clearKeys() { * Clears the state of all buttons */ public void clearButtons() { - for(int i = 0; i < mouseButtons.length;i++) { + for(int i = 0; i < mouseButtons.length; i++) { mouseButtons[i] = false; } } @@ -123,7 +123,7 @@ public boolean touchUp(int x, int y, int pointer, int button) { */ @Override public boolean keyDown(int key) { - if(key>=0 && key= 0 && key < this.keys.length) { this.keys[key] = true; } return false; @@ -134,7 +134,7 @@ public boolean keyDown(int key) { */ @Override public boolean keyUp(int key) { - if(key>=0 && key= 0 && key < this.keys.length) { this.keys[key] = false; } return false; diff --git a/src/seventh/client/inputs/JoystickGameController.java b/src/seventh/client/inputs/JoystickGameController.java index 6f14a39..fc0831c 100644 --- a/src/seventh/client/inputs/JoystickGameController.java +++ b/src/seventh/client/inputs/JoystickGameController.java @@ -27,7 +27,7 @@ public JoystickGameController() { @Override public boolean buttonDown(Controller controller, int button) { boolean result = super.buttonDown(controller, button); - if(button >-1 && button < this.isButtonReleased.length) + if(button > -1 && button < this.isButtonReleased.length) this.isButtonReleased[button] = false; return result; } @@ -36,7 +36,7 @@ public boolean buttonDown(Controller controller, int button) { public boolean buttonUp(Controller controller, int button) { boolean result = super.buttonUp(controller, button); - if(button >-1 && button < this.isButtonReleased.length) + if(button > -1 && button < this.isButtonReleased.length) this.isButtonReleased[button] = true; return result; } @@ -225,6 +225,7 @@ public int pollInputs(TimeStep timeStep, KeyMap keyMap, Cursor cursor, int input if (isButtonDown(keyMap.getIronSightsBtn())) { inputKeys |= Actions.IRON_SIGHTS.getMask(); + inputKeys |= Actions.WALK.getMask(); } if (isButtonDown(keyMap.getMeleeAttackBtn())) { diff --git a/src/seventh/client/inputs/KeyMap.java b/src/seventh/client/inputs/KeyMap.java index bedd4f2..87f194a 100644 --- a/src/seventh/client/inputs/KeyMap.java +++ b/src/seventh/client/inputs/KeyMap.java @@ -940,7 +940,7 @@ public void setTeamSayKey(int teamSayKey) { * @param key */ public void setKey(String keymap, int key) { - if(key>NumberOfKeyboardKeys) { + if(key > NumberOfKeyboardKeys) { joystick.setObject(keymap, Leola.toLeoObject(keyToString(key))); } else { diff --git a/src/seventh/client/inputs/KeyboardGameController.java b/src/seventh/client/inputs/KeyboardGameController.java index 1199a4e..1f35ed8 100644 --- a/src/seventh/client/inputs/KeyboardGameController.java +++ b/src/seventh/client/inputs/KeyboardGameController.java @@ -51,6 +51,7 @@ public int pollInputs(TimeStep timeStep, KeyMap keyMap, Cursor cursor, int input if(isKeyOrButtonDown(keyMap.getIronSightsKey())) { inputKeys |= Actions.IRON_SIGHTS.getMask(); + inputKeys |= Actions.WALK.getMask(); } if(isKeyOrButtonDown(keyMap.getFireKey())) { diff --git a/src/seventh/client/screens/MenuScreen.java b/src/seventh/client/screens/MenuScreen.java index 84bfa24..b2db7c2 100644 --- a/src/seventh/client/screens/MenuScreen.java +++ b/src/seventh/client/screens/MenuScreen.java @@ -250,7 +250,7 @@ public void execute(Console console, String... args) { @Override public void enter() { menuPanel.show(); - Sounds.playGlobalSound(Sounds.uiNavigate); + Sounds.playGlobalSound(Sounds.uiNavigate); } /* (non-Javadoc) @@ -259,7 +259,7 @@ public void enter() { @Override public void exit() { menuPanel.hide(); - Sounds.playGlobalSound(Sounds.uiNavigate); + Sounds.playGlobalSound(Sounds.uiNavigate); } diff --git a/src/seventh/client/screens/OptionsScreen.java b/src/seventh/client/screens/OptionsScreen.java index 7c5f117..a538070 100644 --- a/src/seventh/client/screens/OptionsScreen.java +++ b/src/seventh/client/screens/OptionsScreen.java @@ -84,8 +84,8 @@ public class OptionsScreen implements Screen { private boolean isFullscreen; private int displayModeIndex; - - + private Button applyBtn; + /** * */ @@ -115,79 +115,66 @@ private void createUI() { Vector2f uiPos = new Vector2f(200, app.getScreenHeight() - 20); - Button saveBtn = setupButton(uiPos, "Save", false); - saveBtn.getBounds().setSize(140, 80); - saveBtn.getTextLabel().setFont(theme.getPrimaryFontName()); - saveBtn.addOnButtonClickedListener(new OnButtonClickedListener() { + if(applyBtn != null) { + applyBtn.destroy(); + } + + applyBtn = setupButton(uiPos, "Apply", false); + applyBtn.setVisible(false); + applyBtn.getBounds().setSize(140, 80); + applyBtn.getTextLabel().setFont(theme.getPrimaryFontName()); + applyBtn.addOnButtonClickedListener(new OnButtonClickedListener() { @Override public void onButtonClicked(ButtonEvent event) { - try { - VideoConfig vConfig = app.getConfig().getVideo(); - if(isFullscreen != app.isFullscreen()) { - vConfig.setFullscreen(isFullscreen); - - if(!isFullscreen) { - vConfig.setWidth(SeventhGame.DEFAULT_MINIMIZED_SCREEN_WIDTH); - vConfig.setHeight(SeventhGame.DEFAULT_MINIMIZED_SCREEN_HEIGHT); - Gdx.graphics.setDisplayMode(SeventhGame.DEFAULT_MINIMIZED_SCREEN_WIDTH, SeventhGame.DEFAULT_MINIMIZED_SCREEN_HEIGHT, isFullscreen); - } - else if (mode!=null) { - vConfig.setWidth(mode.width); - vConfig.setHeight(mode.height); - Gdx.graphics.setDisplayMode(mode.width, mode.height, true); - } - else { - Gdx.graphics.setDisplayMode(app.getScreenWidth(), app.getScreenHeight(), true); - } - app.restartVideo(); + + VideoConfig vConfig = app.getConfig().getVideo(); + if(isFullscreen != app.isFullscreen()) { + vConfig.setFullscreen(isFullscreen); + + boolean success = false; + + if(!isFullscreen) { + vConfig.setWidth(SeventhGame.DEFAULT_MINIMIZED_SCREEN_WIDTH); + vConfig.setHeight(SeventhGame.DEFAULT_MINIMIZED_SCREEN_HEIGHT); + success = Gdx.graphics.setDisplayMode(SeventhGame.DEFAULT_MINIMIZED_SCREEN_WIDTH, SeventhGame.DEFAULT_MINIMIZED_SCREEN_HEIGHT, isFullscreen); } - else if(mode!=null) { - if(app.isFullscreen()) { - vConfig.setWidth(mode.width); - vConfig.setHeight(mode.height); - Gdx.graphics.setDisplayMode(mode.width, mode.height, true); - app.restartVideo(); - } + else if (mode!=null) { + vConfig.setWidth(mode.width); + vConfig.setHeight(mode.height); + success = Gdx.graphics.setDisplayMode(mode.width, mode.height, true); + } + else { + success = Gdx.graphics.setDisplayMode(app.getScreenWidth(), app.getScreenHeight(), true); } - if(nameTxtBox!=null) { - String name = nameTxtBox.getText(); - String cfgName = app.getConfig().getPlayerName(); - if(name != null && cfgName != null) { - if(!name.equals(cfgName)) { - // change the configuration file - // and if we are connected to a server, - // let the server know we changed our name - app.getConfig().setPlayerName(name); - Cons.getImpl().execute("name", name); - } + if(success) { + app.restartVideo(); + } + } + else if(mode!=null) { + if(app.isFullscreen()) { + vConfig.setWidth(mode.width); + vConfig.setHeight(mode.height); + if(Gdx.graphics.setDisplayMode(mode.width, mode.height, true)) { + app.restartVideo(); } } - - app.getConfig().setMouseSensitivity(uiManager.getCursor().getMouseSensitivity()); - - app.getConfig().save(); - } catch (IOException e) { - Cons.println("Unable to save the configuration file:"); - Cons.println(e); - - app.getTerminal().open(); } - app.popScreen(); - Sounds.playGlobalSound(Sounds.uiNavigate); + + applyBtn.setVisible(false); } }); uiPos.x = app.getScreenWidth() - 80; - Button cancelBtn = setupButton(uiPos, "Cancel", false); - cancelBtn.getBounds().setSize(140, 80); - cancelBtn.getTextLabel().setFont(theme.getPrimaryFontName()); - cancelBtn.addOnButtonClickedListener(new OnButtonClickedListener() { + Button backBtn = setupButton(uiPos, "Back", false); + backBtn.getBounds().setSize(140, 80); + backBtn.getTextLabel().setFont(theme.getPrimaryFontName()); + backBtn.addOnButtonClickedListener(new OnButtonClickedListener() { @Override - public void onButtonClicked(ButtonEvent event) { + public void onButtonClicked(ButtonEvent event) { app.popScreen(); Sounds.playGlobalSound(Sounds.uiNavigate); } @@ -287,17 +274,18 @@ public void onButtonClicked(ButtonEvent event) { uiPos.x = 560; uiPos.y -= 8; + final Cursor cursor = uiManager.getCursor(); + mouseSensitivitySlider.setTheme(theme); mouseSensitivitySlider.getBounds().setSize(100, 5); mouseSensitivitySlider.getBounds().setLocation(uiPos); // valid ranges from 0.5 to 2.0 - int handlePos = (int)((uiManager.getCursor().getMouseSensitivity()/2f) * 100.0f); + int handlePos = (int)((cursor.getMouseSensitivity()/2f) * 100.0f); mouseSensitivitySlider.moveHandle(handlePos); mouseSensitivitySlider.addSliderMoveListener(new OnSliderMovedListener() { @Override - public void onSliderMoved(SliderMovedEvent event) { - Cursor cursor = uiManager.getCursor(); + public void onSliderMoved(SliderMovedEvent event) { int value = event.getSlider().getIndex(); float sensitivity = value / 50f; @@ -357,6 +345,7 @@ public void onButtonClicked(ButtonEvent event) { mode = displayModes[displayModeIndex]; resBtn.setText("Resolution: '" + mode.width+"x" + mode.height + "'"); + applyBtn.setVisible(true); } }); @@ -368,6 +357,7 @@ public void onButtonClicked(ButtonEvent event) { public void onButtonClicked(ButtonEvent event) { isFullscreen = !isFullscreen; fullscreenBtn.setText("Fullscreen: '" + isFullscreen + "'"); + applyBtn.setVisible(true); } }); @@ -379,7 +369,7 @@ public void onButtonClicked(ButtonEvent event) { public void onButtonClicked(ButtonEvent event) { app.setVSync(!app.isVSync()); app.getConfig().getVideo().setVsync(app.isVSync()); - vsyncBtn.setText("VSync: '" + app.isVSync() + "'"); + vsyncBtn.setText("VSync: '" + app.isVSync() + "'"); } }); @@ -579,7 +569,7 @@ public void onButtonClicked(ButtonEvent event) { isKeyModifyOn++; } }); - } + } this.optionsPanel.addWidget(btn); this.panelView.addElement(new ButtonView(btn)); @@ -593,6 +583,8 @@ public void onButtonClicked(ButtonEvent event) { @Override public void enter() { this.optionsPanel.show(); + this.applyBtn.setVisible(false); + this.keyInput.setDisabled(true); } @@ -602,6 +594,33 @@ public void enter() { @Override public void exit() { this.optionsPanel.destroy(); + + try { + + if(nameTxtBox!=null) { + String name = nameTxtBox.getText(); + String cfgName = app.getConfig().getPlayerName(); + if(name != null && cfgName != null) { + if(!name.equals(cfgName)) { + // change the configuration file + // and if we are connected to a server, + // let the server know we changed our name + app.getConfig().setPlayerName(name); + Cons.getImpl().execute("name", name); + } + } + } + + app.getConfig().setMouseSensitivity(uiManager.getCursor().getMouseSensitivity()); + app.getConfig().save(); + + } + catch (IOException e) { + Cons.println("Unable to save the configuration file:"); + Cons.println(e); + + app.getTerminal().open(); + } } /* (non-Javadoc) diff --git a/src/seventh/client/weapon/ClientSpringfield.java b/src/seventh/client/weapon/ClientSpringfield.java index ca2e138..bf63546 100644 --- a/src/seventh/client/weapon/ClientSpringfield.java +++ b/src/seventh/client/weapon/ClientSpringfield.java @@ -30,7 +30,7 @@ public ClientSpringfield(ClientPlayerEntity owner) { this.weaponWeight = WeaponConstants.SPRINGFIELD_WEIGHT; this.weaponKickTime = 150; - this.endFireKick = 28.7f; + this.endFireKick = 20.7f; this.beginFireKick = 0f; } diff --git a/src/seventh/game/Game.java b/src/seventh/game/Game.java index 52e9142..097f40c 100644 --- a/src/seventh/game/Game.java +++ b/src/seventh/game/Game.java @@ -112,7 +112,7 @@ * */ public class Game implements GameInfo, Debugable, Updatable { - + /** * Null Node Data. @@ -814,17 +814,7 @@ public GameType getGameType() { */ @Override public void update(TimeStep timeStep) { - updateEntity(timeStep); - this.aiSystem.update(timeStep); - this.gameTimers.update(timeStep); - this.gameTriggers.update(timeStep); - this.gameType.update(this, timeStep); - this.time = this.gameType.getRemainingTime(); - } - - - private void updateEntity(TimeStep timeStep) { - for(int i = 0; i < entities.length; i++) { + for(int i = 0; i < entities.length; i++) { Entity ent = entities[i]; if(ent!=null) { if(ent.isAlive()) { @@ -841,8 +831,15 @@ private void updateEntity(TimeStep timeStep) { else { deadFrames[i]++; } - } - } + } + + this.aiSystem.update(timeStep); + this.gameTimers.update(timeStep); + this.gameTriggers.update(timeStep); + + this.gameType.update(this, timeStep); + this.time = this.gameType.getRemainingTime(); + } /** * Invoked after an update, a hack to work @@ -1286,56 +1283,52 @@ public boolean playerSwitchedTeam(int playerId, byte teamId) { if(Team.SPECTATOR_TEAM_ID != teamId) { player.stopSpectating(); } - switchWeaponByTeam(teamId, player); + + /* make sure the player has the teams weaponry */ + switch(player.getWeaponClass()) { + case THOMPSON: + player.setWeaponClass(Type.MP40); + break; + case MP40: + player.setWeaponClass(Type.THOMPSON); + break; + + case KAR98: + player.setWeaponClass(Type.SPRINGFIELD); + break; + case SPRINGFIELD: + player.setWeaponClass(Type.KAR98); + break; + + case MP44: + player.setWeaponClass(Type.M1_GARAND); + break; + case M1_GARAND: + player.setWeaponClass(Type.MP44); + + case SHOTGUN: + case ROCKET_LAUNCHER: + case RISKER: + case FLAME_THROWER: + break; + + /* make the player use the default weapon */ + default: { + switch(teamId) { + case Team.ALLIED_TEAM_ID: + player.setWeaponClass(Type.THOMPSON); + break; + case Team.AXIS_TEAM_ID: + player.setWeaponClass(Type.MP40); + break; + } + } + } } } return playerSwitched; } - - - private void switchWeaponByTeam(byte teamId, Player player) { - /* make sure the player has the teams weaponry */ - switch(player.getWeaponClass()) { - case THOMPSON: - player.setWeaponClass(Type.MP40); - break; - case MP40: - player.setWeaponClass(Type.THOMPSON); - break; - - case KAR98: - player.setWeaponClass(Type.SPRINGFIELD); - break; - case SPRINGFIELD: - player.setWeaponClass(Type.KAR98); - break; - - case MP44: - player.setWeaponClass(Type.M1_GARAND); - break; - case M1_GARAND: - player.setWeaponClass(Type.MP44); - - case SHOTGUN: - case ROCKET_LAUNCHER: - case RISKER: - case FLAME_THROWER: - break; - - /* make the player use the default weapon */ - default: { - switch(teamId) { - case Team.ALLIED_TEAM_ID: - break; - player.setWeaponClass(Type.THOMPSON); - case Team.AXIS_TEAM_ID: - player.setWeaponClass(Type.MP40); - break; - } - } - } - } /** * A player has requested to switch its weapon class diff --git a/src/seventh/game/GameInfo.java b/src/seventh/game/GameInfo.java index 338ab5b..0f79b9a 100644 --- a/src/seventh/game/GameInfo.java +++ b/src/seventh/game/GameInfo.java @@ -182,7 +182,10 @@ public interface GameInfo { * @return true if it does. */ public abstract boolean doesTouchOthers(Entity ent); + public abstract boolean doesTouchOthers(Entity ent, boolean invokeTouch); + public boolean doesTouchEntity(Rectangle bounds); + /** * Determines if the supplied entity touches another * entity. If the {@link Entity#onTouch} listener diff --git a/src/seventh/game/PlayerAwardSystem.java b/src/seventh/game/PlayerAwardSystem.java index d7b9ac1..eac9f37 100644 --- a/src/seventh/game/PlayerAwardSystem.java +++ b/src/seventh/game/PlayerAwardSystem.java @@ -16,15 +16,15 @@ import seventh.game.events.RoundEndedListener; import seventh.game.events.RoundStartedEvent; import seventh.game.events.RoundStartedListener; -import seventh.shared.EventDispatcher; +import seventh.shared.EventDispatcher; import seventh.shared.SeventhConstants; -/** +/** * Keeps track of player stats for kill streaks and bonuses * * @author Tony * - */ + */ public class PlayerAwardSystem { /** @@ -96,12 +96,26 @@ public void roundReset() { } public void roundEnded() { - awardByKill(); - awardByRatio(); - } - - private void awardByRatio() { - float ratio = 1.0f; + if(deaths == 0) { + if(kills == 0) { + // send out coward award + dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Coward)); + } + else if(kills < 5) { + // send out + dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Excellence)); + } + else if(kills < 10) { + // send out + dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.BeastMode)); + } + else { + // send out + dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.FavreMode)); + } + } + + float ratio = 1.0f; if(deaths>0) { ratio = kills / deaths; } @@ -122,40 +136,27 @@ else if(ratio > .60f) { dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Marksman)); } } - } - - private void awardByKill() { - if(deaths == 0) { - if(kills == 0) { - // send out coward award - dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Coward)); - } - else if(kills < 5) { - // send out - dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.Excellence)); - } - else if(kills < 10) { - // send out - dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.BeastMode)); - } - else { - // send out - dispatcher.queueEvent(new PlayerAwardEvent(this, player, Award.FavreMode)); - } - } - } + + } public void addKill() { - awardByKillStreak(); + this.killStreak++; + if(this.killStreak > this.highestKillStreak) { + this.highestKillStreak = this.killStreak; + } - // TODO - use game time, instead of wall time - awardByKillRoll(); + // if the kill streak is worthy, send out an event + switch(this.killStreak) { + case 3: + case 5: + case 10: + case 15: + dispatcher.queueEvent(new KillStreakEvent(this, player, this.killStreak)); + break; + } - this.kills++; - } - - private void awardByKillRoll() { - long killTime = System.currentTimeMillis(); + // TODO - use game time, instead of wall time + long killTime = System.currentTimeMillis(); if(killTime-this.lastKillTime < 3000) { this.killRoll++; @@ -170,24 +171,9 @@ private void awardByKillRoll() { } this.lastKillTime = killTime; - } - - private void awardByKillStreak() { - this.killStreak++; - if(this.killStreak > this.highestKillStreak) { - this.highestKillStreak = this.killStreak; - } - // if the kill streak is worthy, send out an event - switch(this.killStreak) { - case 3: - case 5: - case 10: - case 15: - dispatcher.queueEvent(new KillStreakEvent(this, player, this.killStreak)); - break; - } - } + this.kills++; + } public void addDeath() { this.killStreak = 0; diff --git a/src/seventh/game/entities/BombTarget.java b/src/seventh/game/entities/BombTarget.java index ab9ab76..a850e6c 100644 --- a/src/seventh/game/entities/BombTarget.java +++ b/src/seventh/game/entities/BombTarget.java @@ -5,6 +5,7 @@ package seventh.game.entities; import seventh.game.Game; +import seventh.game.Team; import seventh.game.net.NetBombTarget; import seventh.game.net.NetEntity; import seventh.math.Vector2f; @@ -22,14 +23,17 @@ public class BombTarget extends Entity { private NetBombTarget netBombTarget; private Bomb bomb; + private Team owner; /** * @param position * @param game */ - public BombTarget(Vector2f position, Game game) { + public BombTarget(Team owner, Vector2f position, Game game) { super(game.getNextPersistantId(), position, 0, game, Type.BOMB_TARGET); + this.owner = owner; + this.bounds.width = 64; this.bounds.height = 32; @@ -39,6 +43,13 @@ public BombTarget(Vector2f position, Game game) { setNetEntity(netBombTarget); } + /** + * @return the owner + */ + public Team getOwner() { + return owner; + } + /** * Rotates the bomb target by 90 degrees, this will only * do it once diff --git a/src/seventh/game/entities/Door.java b/src/seventh/game/entities/Door.java index 0a10faa..4325fef 100644 --- a/src/seventh/game/entities/Door.java +++ b/src/seventh/game/entities/Door.java @@ -230,7 +230,7 @@ public Door(Vector2f position, Game game, Vector2f facing) { this.autoCloseTimer = new Timer(false, 5_000); this.autoCloseTimer.stop(); - this.rotation = new SmoothOrientation(0.05); + this.rotation = new SmoothOrientation(0.1); this.rotation.setOrientation(this.hinge.getClosedOrientation()); setOrientation(this.rotation.getOrientation()); @@ -389,11 +389,10 @@ else if(this.isBlocked) { } public void open(Entity ent) { - boolean isNotOpened = this.doorState != DoorState.OPENED; - boolean isNotOpening = this.doorState != DoorState.OPENING; - boolean isNotClosing = this.doorState != DoorState.CLOSING; - - if(isNotOpened || isNotOpening || isNotClosing) { + if(this.doorState != DoorState.OPENED || + this.doorState != DoorState.OPENING || + this.doorState != DoorState.CLOSING) { + if(!canBeHandledBy(ent)) { return; } @@ -408,35 +407,31 @@ public void open(Entity ent) { // figure out what side the entity is // of the door hinge, depending on their // side, we set the destinationOrientation - setDestinationOrientation(entPos, hingePos); + switch(this.hinge) { + + case NORTH_END: + case SOUTH_END: + if(entPos.x < hingePos.x) { + this.targetOrientation = (float)Math.toRadians(0); + } + else if(entPos.x > hingePos.x) { + this.targetOrientation = (float)Math.toRadians(180); + } + break; + case EAST_END: + case WEST_END: + if(entPos.y < hingePos.y) { + this.targetOrientation = (float)Math.toRadians(90); + } + else if(entPos.y > hingePos.y) { + this.targetOrientation = (float)Math.toRadians(270); + } + break; + default: + break; + } } } - - private void setDestinationOrientation(Vector2f entPos, Vector2f hingePos) { - switch(this.hinge) { - - case NORTH_END: - case SOUTH_END: - if(entPos.x < hingePos.x) { - this.targetOrientation = (float)Math.toRadians(0); - } - else if(entPos.x > hingePos.x) { - this.targetOrientation = (float)Math.toRadians(180); - } - break; - case EAST_END: - case WEST_END: - if(entPos.y < hingePos.y) { - this.targetOrientation = (float)Math.toRadians(90); - } - else if(entPos.y > hingePos.y) { - this.targetOrientation = (float)Math.toRadians(270); - } - break; - default: - break; - } - } public void close(Entity ent) { if(this.doorState != DoorState.CLOSED || diff --git a/src/seventh/game/entities/Entity.java b/src/seventh/game/entities/Entity.java index 9939749..6e41915 100644 --- a/src/seventh/game/entities/Entity.java +++ b/src/seventh/game/entities/Entity.java @@ -595,7 +595,7 @@ private int adjustY(Vector2f collisionTilePos, float deltaX, int currentX, int c int xIndex = collisionTile.getXIndex(); int yIndex = collisionTile.getYIndex(); - int offset = 16; + int offset = 32; if(!map.checkTileBounds(xIndex, yIndex - 1) && !map.hasCollidableTile(xIndex, yIndex - 1)) { if(currentY < (collisionTile.getY()-(bounds.height-offset))) { @@ -635,7 +635,7 @@ private int adjustX(Vector2f collisionTilePos, float deltaY, int currentX, int c int xIndex = collisionTile.getXIndex(); int yIndex = collisionTile.getYIndex(); - int offset = 16; + int offset = 32; if(!map.checkTileBounds(xIndex-1, yIndex) && !map.hasCollidableTile(xIndex-1, yIndex)) { if(currentX+bounds.width < (collisionTile.getX()+offset)) { @@ -661,13 +661,10 @@ private int adjustX(Vector2f collisionTilePos, float deltaY, int currentX, int c */ public boolean update(TimeStep timeStep) { boolean isBlocked = false; - boolean isWalking = currentState == State.WALKING; - boolean isSprinting = currentState == State.SPRINTING; - boolean isCrouching = currentState==State.CROUCHING; this.movementDir.zeroOut(); if(this.isAlive && !this.vel.isZero()) { - if(!isWalking && !isSprinting) { + if(currentState != State.WALKING && currentState != State.SPRINTING) { currentState = State.RUNNING; } @@ -757,7 +754,7 @@ else if(deltaX==0 && deltaY!=0) { this.walkingTime = WALK_TIME; } else { - if(this.walkingTime<=0 && !isCrouching) { + if(this.walkingTime<=0 && currentState!=State.CROUCHING) { currentState = State.IDLE; } diff --git a/src/seventh/game/entities/PlayerEntity.java b/src/seventh/game/entities/PlayerEntity.java index 47ef60a..06a9ee9 100644 --- a/src/seventh/game/entities/PlayerEntity.java +++ b/src/seventh/game/entities/PlayerEntity.java @@ -1012,15 +1012,11 @@ public void sprint() { * 6) you are not reloading */ - final boolean isAlive = currentState!=State.DEAD; - final boolean hasStamina = stamina > 0; - final boolean noRecoveryTime = recoveryTime <= 0; - - if(isAlive && - hasStamina && + if(currentState!=State.DEAD && + stamina > 0 && !firing && !wasSprinting && - noRecoveryTime) { + recoveryTime <= 0) { Weapon weapon = this.inventory.currentItem(); boolean isReady = weapon != null ? weapon.isReady() : true; @@ -1376,11 +1372,14 @@ public boolean isThrowingGrenade() { */ protected void handleBombTarget(BombTarget target) { if(target!=null) { - if(target.bombActive()) { - Bomb bomb = target.getBomb(); - bomb.disarm(this); - - game.emitSound(getId(), SoundType.BOMB_DISARM, getPos()); + + if(target.getOwner().equals(getTeam())) { + if(target.bombActive()) { + Bomb bomb = target.getBomb(); + bomb.disarm(this); + + game.emitSound(getId(), SoundType.BOMB_DISARM, getPos()); + } } else { if(!target.isBombAttached()) { @@ -1388,8 +1387,8 @@ protected void handleBombTarget(BombTarget target) { bomb.plant(this, target); target.attachBomb(bomb); game.emitSound(getId(), SoundType.BOMB_PLANT, getPos()); - } - } + } + } } } @@ -1511,6 +1510,7 @@ public boolean isOnTeamWith(PlayerEntity other) { return false; } + /** * If this {@link PlayerEntity} is currently holding a specific * weapon type. @@ -1835,8 +1835,6 @@ public NetPlayer getNetPlayer() { } player.health = (byte)getHealth(); -// player.events = (byte)getEvents(); - player.stamina = getStamina(); player.isOperatingVehicle = isOperatingVehicle(); if(player.isOperatingVehicle) { diff --git a/src/seventh/game/net/NetPlayer.java b/src/seventh/game/net/NetPlayer.java index 6ab5f00..15718fa 100644 --- a/src/seventh/game/net/NetPlayer.java +++ b/src/seventh/game/net/NetPlayer.java @@ -27,7 +27,6 @@ public NetPlayer() { public State state; public byte grenades; public byte health; - public byte stamina; public boolean isOperatingVehicle; public boolean isSmokeGrenades; @@ -68,7 +67,6 @@ public void read(IOBuffer buffer) { state = BufferIO.readState(buffer); grenades = buffer.getByteBits(4); health = buffer.getByteBits(7); - stamina = buffer.getByteBits(7); if((bits & HAS_WEAPON) != 0) { weapon = new NetWeapon(); @@ -100,7 +98,6 @@ public void write(IOBuffer buffer) { BufferIO.writeState(buffer, state); buffer.putByteBits(grenades, 4); buffer.putByteBits(health, 7); - buffer.putByteBits(stamina, 7); if(weapon != null && !isOperatingVehicle) { weapon.write(buffer); diff --git a/src/seventh/game/type/AbstractTeamGameType.java b/src/seventh/game/type/AbstractTeamGameType.java index 9480c9e..63d2d64 100644 --- a/src/seventh/game/type/AbstractTeamGameType.java +++ b/src/seventh/game/type/AbstractTeamGameType.java @@ -581,6 +581,17 @@ else if (alliedScore > axisScore) { return this.highScoreTeams; } + + @Override + public Team getAttacker() { + return getAlliedTeam().isAttacker() ? getAlliedTeam() : getAxisTeam(); + } + + @Override + public Team getDefender() { + return getAlliedTeam().isDefender() ? getAlliedTeam() : getAxisTeam(); + } + /* (non-Javadoc) * @see palisma.game.type.GameType#getTeam(palisma.game.Player) */ diff --git a/src/seventh/game/type/GameType.java b/src/seventh/game/type/GameType.java index 327ab2f..35fb769 100644 --- a/src/seventh/game/type/GameType.java +++ b/src/seventh/game/type/GameType.java @@ -110,6 +110,9 @@ public byte netValue() { public void playerJoin(Player player); public void playerLeft(Player player); + public Team getAttacker(); + public Team getDefender(); + public Team getTeam(Player player); public Team getEnemyTeam(Player player); public boolean switchTeam(Player player, byte teamId); diff --git a/src/seventh/game/type/obj/BombTargetObjective.java b/src/seventh/game/type/obj/BombTargetObjective.java index 9043f8c..d71253a 100644 --- a/src/seventh/game/type/obj/BombTargetObjective.java +++ b/src/seventh/game/type/obj/BombTargetObjective.java @@ -32,7 +32,7 @@ public BombTargetObjective(Vector2f position) { * @param position * @param name */ - public BombTargetObjective(Vector2f position, String name, Boolean rotated) { + public BombTargetObjective(Vector2f position, String name, Boolean rotated) { this.position = position; this.name = name != null ? name : "Bomb Target"; this.rotated = rotated != null && rotated; @@ -68,7 +68,7 @@ public void reset(Game game) { */ @Override public void init(Game game) { - target = game.newBombTarget(position); + target = game.newBombTarget(game.getGameType().getDefender(), position); if(rotated) { target.rotate90(); } diff --git a/src/seventh/game/type/obj/ObjectiveGameType.java b/src/seventh/game/type/obj/ObjectiveGameType.java index 3806be9..e1c0450 100644 --- a/src/seventh/game/type/obj/ObjectiveGameType.java +++ b/src/seventh/game/type/obj/ObjectiveGameType.java @@ -79,6 +79,7 @@ public ObjectiveGameType(Leola runtime, /** * @return the attacker */ + @Override public Team getAttacker() { return attacker; } @@ -86,6 +87,7 @@ public Team getAttacker() { /** * @return the defender */ + @Override public Team getDefender() { return defender; } diff --git a/src/seventh/game/type/obj/ObjectiveScript.java b/src/seventh/game/type/obj/ObjectiveScript.java index 31791f6..3b2ad54 100644 --- a/src/seventh/game/type/obj/ObjectiveScript.java +++ b/src/seventh/game/type/obj/ObjectiveScript.java @@ -45,119 +45,85 @@ public GameType loadGameType(String mapFile, int maxScore, long matchTime) throw List axisSpawnPoints = new ArrayList(); byte defenders = Team.AXIS_TEAM_ID; int minimumObjectivesToComplete = 1; - final long timeBetweenRounds = 10_000L; - - File scriptFile = new File(mapFile + ".obj.leola"); - if (!scriptFile.exists()) { - throw new NotExistScriptFileException(); - }; - - LeoObject config = getRuntime().eval(scriptFile); - if (LeoObject.isTrue(config)) { - - addscriptedObjectives(objectives, config); - defenders = addScriptedDenfenders(defenders, config); - alliedSpawnPoints = loadSpawnPoint(config, "alliedSpawnPoints"); - axisSpawnPoints = loadSpawnPoint(config, "axisSpawnPoints"); - minimumObjectivesToComplete = checkMinumumObjectCompleteSize(objectives, config); - - } - - return new ObjectiveGameType(getRuntime(), objectives, alliedSpawnPoints, axisSpawnPoints, - minimumObjectivesToComplete, maxScore, matchTime, timeBetweenRounds, defenders); - } - - private int checkMinumumObjectCompleteSize(List objectives, LeoObject config) { - int minimumObjectivesToComplete; - if (config.hasObject("minimumObjectivesToComplete")) { - minimumObjectivesToComplete = config.getObject("minimumObjectivesToComplete").asInt(); - } else { - minimumObjectivesToComplete = objectives.size(); - } - return minimumObjectivesToComplete; - } - - private void addscriptedObjectives(List objectives, LeoObject config) throws Exception { - LeoObject scriptedObjectives = config.getObject("objectives"); - if (LeoObject.isTrue(scriptedObjectives)) { - loadscriptObjectCase(objectives, scriptedObjectives); - } - } - private void loadscriptObjectCase(List objectives, LeoObject scriptedObjectives) throws Exception{ - switch (scriptedObjectives.getType()) { - case ARRAY: { - addAllLeoObjectValues(objectives, scriptedObjectives); - break; - } - case NATIVE_CLASS: { - addNativeClassObjectValues(objectives, scriptedObjectives); - break; - } - default: { - throw new NonObjectTypeException(); - } - } - } - - private byte addScriptedDenfenders(byte defenders, LeoObject config) throws Exception { - LeoObject scriptedDefenders = config.getObject("defenders"); - if (LeoObject.isTrue(scriptedDefenders)) { - defenders = loadscriptedDefenderCase(defenders, scriptedDefenders); + File scriptFile = new File(mapFile + ".obj.leola"); + if(!scriptFile.exists()) { + Cons.println("*** ERROR -> No associated script file for objective game type. Looking for: " + scriptFile.getName()); } - return defenders; - } - - private byte loadscriptedDefenderCase(byte defenders, LeoObject scriptedDefenders)throws Exception { - switch (scriptedDefenders.getType()) { - case INTEGER: - case LONG: - case REAL: - defenders = (byte) scriptedDefenders.asInt(); - break; - case STRING: - if (Team.ALLIED_TEAM_NAME.equalsIgnoreCase(scriptedDefenders.toString())) { - defenders = Team.ALLIED_TEAM_ID; + else { + LeoObject config = getRuntime().eval(scriptFile); + if(LeoObject.isTrue(config)) { + LeoObject scriptedObjectives = config.getObject("objectives"); + if(LeoObject.isTrue(scriptedObjectives)) { + switch(scriptedObjectives.getType()) { + case ARRAY: { + LeoArray array = scriptedObjectives.as(); + for(int i = 0; i < array.size(); i++) { + LeoObject o = array.get(i); + if (o instanceof LeoNativeClass) { + if(o.getValue() instanceof Objective) { + Objective objective = (Objective)o.getValue(); + objectives.add(objective); + } + else { + Cons.println(((LeoNativeClass) o).getNativeClass() + " is not of type: " + Objective.class.getName()); + } + + } + } + break; + } + case NATIVE_CLASS: { + LeoObject o = scriptedObjectives; + if(o.getValue() instanceof Objective) { + Objective objective = (Objective)o.getValue(); + objectives.add(objective); + } + else { + Cons.println(((LeoNativeClass) o).getNativeClass() + " is not of type: " + Objective.class.getName()); + } + break; + } + default: { + Cons.println("*** ERROR -> objectives must either be an Array of objectives or a Java class or custom Leola class"); + } + } + } + + LeoObject scriptedDefenders = config.getObject("defenders"); + if(LeoObject.isTrue(scriptedDefenders)) { + switch(scriptedDefenders.getType()) { + case INTEGER: + case LONG: + case REAL: + defenders = (byte)scriptedDefenders.asInt(); + break; + case STRING: + if(Team.ALLIED_TEAM_NAME.equalsIgnoreCase(scriptedDefenders.toString())) { + defenders = Team.ALLIED_TEAM_ID; + } + break; + default:{ + Cons.println("*** ERROR -> defenders must either be a 2(for allies) or 4(for axis) or 'allies' or 'axis' values"); + } + } + } + + alliedSpawnPoints = loadSpawnPoint(config, "alliedSpawnPoints"); + axisSpawnPoints = loadSpawnPoint(config, "axisSpawnPoints"); + if(config.hasObject("minimumObjectivesToComplete")) { + minimumObjectivesToComplete = config.getObject("minimumObjectivesToComplete").asInt(); + } + else { + minimumObjectivesToComplete = objectives.size(); + } } - break; - default: { - throw new NonDefenderTypeException(); - } - } - return defenders; - } - - - private void addAllLeoObjectValues(List objectives, LeoObject scriptedObjectives) throws Exception { - LeoArray array = scriptedObjectives.as(); - for (int i = 0; i < array.size(); i++) { - addLeoObjectValues(objectives, array, i); } - } - - private void addNativeClassObjectValues(List objectives, LeoObject scriptedObjectives)throws Exception { - LeoObject o = scriptedObjectives; - addObjectValue(objectives, o); - } - - - private void addLeoObjectValues(List objectives, LeoArray array, int i) throws Exception { - LeoObject o = array.get(i); - if (o instanceof LeoNativeClass) { - addObjectValue(objectives, o); - } - } - private void addObjectValue(List objectives, LeoObject o) throws NonLeoNativeTypeException { - if (o.getValue() instanceof Objective) { - objectives.add((Objective)o.getValue()); - } else { - printNonNativeClassTypeToConsole(o); - throw new NonLeoNativeTypeException(); - } - } - - - private void printNonNativeClassTypeToConsole(LeoObject o) { - Cons.println(((LeoNativeClass) o).getNativeClass() + " is not of type: "+ Objective.class.getName()); + + final long timeBetweenRounds = 10_000L; + + GameType gameType = new ObjectiveGameType(getRuntime(), objectives, alliedSpawnPoints, axisSpawnPoints, + minimumObjectivesToComplete, maxScore, matchTime, timeBetweenRounds, defenders); + return gameType; } } diff --git a/src/seventh/map/DefaultMapObjectFactory.java b/src/seventh/map/DefaultMapObjectFactory.java index 4823539..b960299 100644 --- a/src/seventh/map/DefaultMapObjectFactory.java +++ b/src/seventh/map/DefaultMapObjectFactory.java @@ -80,7 +80,7 @@ public DefaultMapObject(boolean loadAssets, MapObjectDefinition definition, MapO this.obb = new OBB(rect); this.obb.rotateAround(pos, (float) Math.toRadians(data.rotation)); - int length = (int) this.obb.length(); + int length = (int)this.obb.length(); this.bounds.setSize(length, length); this.bounds.centerAround(this.obb.getCenter()); @@ -198,7 +198,7 @@ public DefaultMapObjectFactory(Leola runtime, String mapFile, boolean loadAssets this.loadAssets = loadAssets; this.objectDefinitions = new HashMap<>(); - File objectsFile = new File(mapFile + ".objects.json"); + File objectsFile = new File(mapFile + ".objects.leola"); if(objectsFile.exists()) { String contents = new String(Files.readAllBytes(objectsFile.toPath())); LeoMap objectData = JSON.parseJson(runtime, contents).as(); diff --git a/src/seventh/map/Layer.java b/src/seventh/map/Layer.java index 35f7231..a1d1269 100644 --- a/src/seventh/map/Layer.java +++ b/src/seventh/map/Layer.java @@ -111,9 +111,9 @@ public int getHeightMask() { public void applyHeightMask() { for(int rowIndex = 0; rowIndex < this.rows.length; rowIndex++) { Tile[] row = this.rows[rowIndex]; - for(int i = 0; i < row.length;i++) { + for(int i = 0; i < row.length; i++) { Tile t = row[i]; - if(t!=null) { + if(t != null) { t.setHeightMask(heightMask); } } @@ -203,9 +203,9 @@ public Tile[] getRow(int i) { */ public void addRow(int index, Tile[] row) { this.rows[index] = row; - for(int i = 0; i < row.length;i++) { + for(int i = 0; i < row.length; i++) { Tile t = row[i]; - if(t!=null) { + if(t != null) { t.setHeightMask(heightMask); } } diff --git a/src/seventh/map/Map.java b/src/seventh/map/Map.java index 6a82081..e5b6283 100644 --- a/src/seventh/map/Map.java +++ b/src/seventh/map/Map.java @@ -269,8 +269,8 @@ public TilesetAtlas getAtlas() { * @param y - y array coordinate * @return */ - public abstract Tile getTile( int layer, int x, int y ); - public abstract Tile getDestructableTile(int x, int y ); + public abstract Tile getTile(int layer, int x, int y); + public abstract Tile getDestructableTile(int x, int y); /** * Retrieve a Tile. @@ -279,7 +279,7 @@ public TilesetAtlas getAtlas() { * @param y - y array coordinate * @return */ - public abstract Tile getCollidableTile(int x, int y ); + public abstract Tile getCollidableTile(int x, int y); @@ -290,7 +290,7 @@ public TilesetAtlas getAtlas() { * @param y - y in world coordinate space * @return */ - public abstract Tile getWorldTile( int layer, int x, int y); + public abstract Tile getWorldTile(int layer, int x, int y); /** @@ -344,7 +344,7 @@ public TilesetAtlas getAtlas() { * @param y - y in world coordinate space * @return true if there is a height mask; false otherwise */ - public abstract boolean hasHeightMask( int worldX, int worldY); + public abstract boolean hasHeightMask(int worldX, int worldY); /** * Check for a collision given a {@link Rectangle} @@ -352,7 +352,7 @@ public TilesetAtlas getAtlas() { * @param rect * @return true if a collision occurs, false otherwise */ - public abstract boolean rectCollides( Rectangle rect ); + public abstract boolean rectCollides(Rectangle rect); /** * Check for a collision given a {@link OBB} @@ -360,7 +360,7 @@ public TilesetAtlas getAtlas() { * @param oob * @return true if a collision occurs, false otherwise */ - public abstract boolean rectCollides( OBB oob ); + public abstract boolean rectCollides(OBB oob); /** * Check for a collision given a {@link Rectangle} @@ -369,7 +369,7 @@ public TilesetAtlas getAtlas() { * @param heightMask * @return true if a collision occurs, false otherwise */ - public abstract boolean rectCollides( Rectangle rect, int heightMask ); + public abstract boolean rectCollides(Rectangle rect, int heightMask); /** * Check for a collision given a {@link Rectangle} @@ -425,7 +425,7 @@ public TilesetAtlas getAtlas() { * @param worldY * @return true if out of bounds */ - public abstract boolean checkBounds( int worldX, int worldY ); + public abstract boolean checkBounds(int worldX, int worldY); /** * Checks the map boundaries based on tile coordinates @@ -476,7 +476,7 @@ public TilesetAtlas getAtlas() { * @param y * @return */ - public abstract Vector2f worldToTile( int x, int y); + public abstract Vector2f worldToTile(int x, int y); public abstract int worldToTileX(int x); public abstract int worldToTileY(int y); @@ -487,7 +487,7 @@ public TilesetAtlas getAtlas() { * @param ty * @return */ - public abstract Vector2f tileToWorld( int tx, int ty ); + public abstract Vector2f tileToWorld(int tx, int ty); /** * Get {@link MapObject}s. diff --git a/src/seventh/map/OrthoMap.java b/src/seventh/map/OrthoMap.java index 617c95e..36dfb56 100644 --- a/src/seventh/map/OrthoMap.java +++ b/src/seventh/map/OrthoMap.java @@ -161,7 +161,7 @@ public List getCollisionTilesAt(List checkAgainst, List result for (int j = 0; j < this.collidableLayers.length; j++) { Tile tile = getTile(this.collidableLayers[j].getIndex(), xIndex, yIndex); - if ( tile != null ) { + if (tile != null) { results.add(tile); break; } @@ -208,15 +208,15 @@ public List getTilesInRect(int layer, Rectangle bounds, List tiles) for(int y = bounds.y; y <= (bounds.y + bounds.height); - y+=tileHeight) { + y += tileHeight) { for(int x = bounds.x; x <= (bounds.x + bounds.width); - x+=tileWidth ) { + x += tileWidth ) { if(!checkBounds(x, y)) { Tile tile = getWorldTile(layer, x, y); - if(tile!=null) { + if(tile != null) { result.add(tile); } } @@ -237,17 +237,17 @@ public List getTilesInCircle(int layer, int centerX, int centerY, int radi int length = (radius * 2) + 1; - for(int y = centerY - (length /2); - y <= (centerY + (length/2)); - y+=tileHeight) { + for(int y = centerY - (length / 2); + y <= (centerY + (length / 2)); + y += tileHeight) { - for(int x = centerX - (length/2); - x <= (centerX + (length/2)); - x+=tileWidth ) { + for(int x = centerX - (length / 2); + x <= (centerX + (length / 2)); + x += tileWidth ) { if(!checkBounds(x, y)) { Tile tile = getWorldTile(layer, x, y); - if(tile!=null) { + if(tile != null) { result.add(tile); } } @@ -278,7 +278,7 @@ public boolean pointCollides(int x, int y) { */ @Override public boolean pointCollides(int x, int y, int heightMask) { - if ( checkBounds(x, y) ) { + if (checkBounds(x, y)) { return true; } @@ -291,9 +291,9 @@ public boolean pointCollides(int x, int y, int heightMask) { for (int i = 0; i < this.collidableLayers.length; i++) { //Tile tile = this.backgroundLayers[this.collidableLayers[i].getIndex()].getRow(wy)[wx]; Tile tile = this.collidableLayers[i].getRow(wy)[wx]; - if ( tile != null ) { + if (tile != null) { int tileHeightMask = tile.getHeightMask(); - if(tileHeightMask>0) { + if(tileHeightMask > 0) { if ((tileHeightMask & heightMask) == tileHeightMask && (tile.pointCollide(x, y))) { return true; } @@ -350,15 +350,15 @@ public boolean rectCollides(Rectangle rect, int heightMask, Vector2f collisionTi int indexX = 0; int indexY = 0; - int toIndex_x=0, toIndex_y=0; + int toIndex_x = 0, toIndex_y = 0; // Current Tile offset (to pixels) - int tileOffset_x = -( rect.x % this.tileWidth ); - toIndex_x = ( tileOffset_x + rect.x) / this.tileWidth; + int tileOffset_x = -(rect.x % this.tileWidth); + toIndex_x = (tileOffset_x + rect.x) / this.tileWidth; // current tile y offset (to pixels) int tileOffset_y = -(rect.y % this.tileHeight); - toIndex_y = (tileOffset_y + rect.y) / this.tileHeight; + toIndex_y = (tileOffset_y + rect.y) / this.tileHeight; indexY = toIndex_y; @@ -376,9 +376,9 @@ public boolean rectCollides(Rectangle rect, int heightMask, Vector2f collisionTi Layer layer = collidableLayers[i]; Tile tile = layer.getRow(indexY)[indexX]; - if ( tile != null ) { + if (tile != null) { int tileHeightMask = tile.getHeightMask(); - if(tileHeightMask>0) { + if(tileHeightMask > 0) { if ( (tileHeightMask & heightMask) == tileHeightMask && (tile.rectCollide(rect)) ) { collisionTilePos.set(tile.getX(), tile.getY()); return true; @@ -432,11 +432,11 @@ public boolean lineCollides(Vector2f a, Vector2f b, int heightMask) { if (x0 < x1) sx = 1; else sx = -1; if (y0 < y1) sy = 1; else sy = -1; - int err = dx-dy; + int err = dx - dy; do { - if(this.pointCollides(x0,y0, heightMask)) { + if(this.pointCollides(x0, y0, heightMask)) { return true; } @@ -452,7 +452,7 @@ public boolean lineCollides(Vector2f a, Vector2f b, int heightMask) { } if(x0 == x1 && y0 == y1) { - if(this.pointCollides(x0,y0, heightMask)) { + if(this.pointCollides(x0, y0, heightMask)) { return true; } break; @@ -463,7 +463,7 @@ public boolean lineCollides(Vector2f a, Vector2f b, int heightMask) { y0 = y0 + sy; } - if( checkBounds(x0, y0) ) { + if(checkBounds(x0, y0)) { return true; } @@ -487,9 +487,6 @@ public void setMask(List tiles, int mask) { } } - - - /* * (non-Javadoc) * @@ -497,10 +494,38 @@ public void setMask(List tiles, int mask) { */ public void destroy() { - - destoryRowLayerisNotNULL(this.backgroundLayers); + if (this.backgroundLayers != null) { + for (int i = 0; i < this.backgroundLayers.length; i++) { + Layer layer = this.backgroundLayers[i]; + if (layer == null) { + continue; + } + + + for(int j = 0; j < this.backgroundLayers[i].numberOfRows(); j++) { + this.backgroundLayers[i].destroy(); + } + this.backgroundLayers[i] = null; + } + + } this.backgroundLayers = null; - destoryRowLayerisNotNULL(this.foregroundLayers); + + + if (this.foregroundLayers != null) { + for (int i = 0; i < this.foregroundLayers.length; i++) { + Layer layer = this.foregroundLayers[i]; + if (layer == null) { + continue; + } + + for(int j = 0; j < this.foregroundLayers[i].numberOfRows(); j++) { + this.foregroundLayers[i].destroy(); + } + + this.foregroundLayers[i] = null; + } + } this.foregroundLayers = null; this.collidableLayers=null; @@ -522,7 +547,7 @@ public void destroy() { this.destroyedTiles.clear(); this.destructableLayer = null; - if(this.backgroundImage!=null) { + if(this.backgroundImage != null) { this.backgroundImage.getTexture().dispose(); } @@ -538,24 +563,6 @@ public void destroy() { this.mapObjects.clear(); } } - - public void destoryRowLayerisNotNULL(Layer[] layers) { - // TODO Auto-generated method stub - if ( layers != null ) { - for (int i = 0; i < layers.length; i++) { - Layer layer = layers[i]; - if ( layer == null ) { - continue; - } - - for( int j = 0; j < layers[i].numberOfRows(); j++ ) { - layers[i].destroy(); - } - layers[i] = null; - } - } - } - /* (non-Javadoc) * @see seventh.map.Map#getTileWorldHeight() @@ -720,7 +727,7 @@ public void init(SceneDef info) throws Exception { int bgSize = info.getBackgroundLayers().length; this.backgroundLayers = new Layer[bgSize]; - for(int i = 0; i < bgSize; i++ ) { + for(int i = 0; i < bgSize; i++) { this.backgroundLayers[i] = info.getBackgroundLayers()[i]; if(this.backgroundLayers[i].collidable()) { collidableLayers.add(this.backgroundLayers[i]); @@ -733,7 +740,7 @@ public void init(SceneDef info) throws Exception { int fgSize = info.getForegroundLayers().length; this.foregroundLayers = new Layer[fgSize]; - for(int i = 0; i < fgSize; i++ ) { + for(int i = 0; i < fgSize; i++) { this.foregroundLayers[i] = info.getForegroundLayers()[i]; // if(this.foregroundLayers[i].collidable()) { // collidableLayers.add(this.foregroundLayers[i]); @@ -759,8 +766,8 @@ public void init(SceneDef info) throws Exception { this.tileHeight = info.getTileHeight(); Vector2f worldCoordinates = tileToWorld(this.maxX, this.maxY); - this.mapWidth = (int) worldCoordinates.x; - this.mapHeight = (int) worldCoordinates.y; + this.mapWidth = (int)worldCoordinates.x; + this.mapHeight = (int)worldCoordinates.y; this.worldBounds = new Rectangle(0, 0, this.mapWidth, this.mapHeight); @@ -790,7 +797,7 @@ public void init(SceneDef info) throws Exception { this.surfaces = info.getSurfaces(); if(this.shadeTilesLookup != null) { - this.shadeTilesLookup = createShadeLookup(45); + this.shadeTilesLookup = createShadeLookup(75); } } @@ -845,7 +852,7 @@ public MapGraph createMapGraph(GraphNodeFactory factory) { for(int x = 0; x < numberOfColumns; x++ ) { boolean isCollidable = false; for(int i = 0; i < collidableLayers.length; i++) { - if ( collidableLayers[i] != null ) { + if (collidableLayers[i] != null) { Tile tile = collidableLayers[i].getRow(y)[x]; isCollidable = tile != null; if(isCollidable) { @@ -869,12 +876,12 @@ public MapGraph createMapGraph(GraphNodeFactory factory) { for(int y = 0; y < numberOfRows; y++) { for(int x = 0; x < numberOfColumns; x++ ) { GraphNode node = nodes[y][x]; - if(node==null) continue; + if(node == null) continue; - addNode(factory, nodes, node, x, y,false); + addNode(factory, nodes, node, x, y, false); } } - return new MapGraph(this,nodes); + return new MapGraph(this, nodes); } @SuppressWarnings("all") @@ -892,59 +899,59 @@ private void addNode(GraphNodeFactory factory, GraphNode[][] nodes, Graph nodes[y][x] = node; GraphNode nw = null; - if(y>0 && x>0) nw = nodes[y - 1][x - 1]; + if(y > 0 && x > 0) nw = nodes[y - 1][x - 1]; GraphNode n = null; - if(y>0) n = nodes[y - 1][x]; + if(y > 0) n = nodes[y - 1][x]; GraphNode ne = null; - if(y>0 && x 0 && x < numberOfColumns - 1) ne = nodes[y - 1][x + 1]; GraphNode e = null; - if(x se = null; - if(y s = null; - if(y sw = null; - if(y0) sw = nodes[y + 1][x - 1]; + if(y < numberOfRows - 1 && x > 0) sw = nodes[y + 1][x - 1]; GraphNode w = null; - if(x>0) w = nodes[y][x - 1]; + if(x > 0) w = nodes[y][x - 1]; if (n != null) { - node.addEdge(Directions.N, new Edge(node, n, factory==null? null:factory.createEdgeData(this, node, n))); - if(addAdjacent) n.addEdge(Directions.N.invertedDirection(), new Edge(n, node, factory==null? null:factory.createEdgeData(this, n, node))); + node.addEdge(Directions.N, new Edge(node, n, factory == null? null:factory.createEdgeData(this, node, n))); + if(addAdjacent) n.addEdge(Directions.N.invertedDirection(), new Edge(n, node, factory == null? null:factory.createEdgeData(this, n, node))); } - if (ne != null && (n!=null||e!=null)) { - node.addEdge(Directions.NE, new Edge(node, ne, factory==null? null:factory.createEdgeData(this, node, ne))); - if(addAdjacent) ne.addEdge(Directions.NE.invertedDirection(), new Edge(ne, node, factory==null? null:factory.createEdgeData(this, ne, node))); + if (ne != null && (n != null || e != null)) { + node.addEdge(Directions.NE, new Edge(node, ne, factory == null? null:factory.createEdgeData(this, node, ne))); + if(addAdjacent) ne.addEdge(Directions.NE.invertedDirection(), new Edge(ne, node, factory == null? null:factory.createEdgeData(this, ne, node))); } if (e != null) { - node.addEdge(Directions.E, new Edge(node, e, factory==null? null:factory.createEdgeData(this, node, e))); - if(addAdjacent) e.addEdge(Directions.E.invertedDirection(), new Edge(e, node, factory==null? null:factory.createEdgeData(this, e, node))); + node.addEdge(Directions.E, new Edge(node, e, factory == null? null:factory.createEdgeData(this, node, e))); + if(addAdjacent) e.addEdge(Directions.E.invertedDirection(), new Edge(e, node, factory == null? null:factory.createEdgeData(this, e, node))); } - if (se != null && (s!=null||e!=null)) { - node.addEdge(Directions.SE, new Edge(node, se, factory==null? null:factory.createEdgeData(this, node, se))); - if(addAdjacent) se.addEdge(Directions.SE.invertedDirection(), new Edge(se, node, factory==null? null:factory.createEdgeData(this, se, node))); + if (se != null && (s != null || e != null)) { + node.addEdge(Directions.SE, new Edge(node, se, factory == null? null:factory.createEdgeData(this, node, se))); + if(addAdjacent) se.addEdge(Directions.SE.invertedDirection(), new Edge(se, node, factory == null? null:factory.createEdgeData(this, se, node))); } if (s != null) { - node.addEdge(Directions.S, new Edge(node, s, factory==null? null:factory.createEdgeData(this, node, s))); - if(addAdjacent) s.addEdge(Directions.S.invertedDirection(), new Edge(s, node, factory==null? null:factory.createEdgeData(this, s, node))); + node.addEdge(Directions.S, new Edge(node, s, factory == null? null:factory.createEdgeData(this, node, s))); + if(addAdjacent) s.addEdge(Directions.S.invertedDirection(), new Edge(s, node, factory == null? null:factory.createEdgeData(this, s, node))); } - if (sw != null && (s!=null||w!=null)) { - node.addEdge(Directions.SW, new Edge(node, sw, factory==null? null:factory.createEdgeData(this, node, sw))); - if(addAdjacent) sw.addEdge(Directions.SW.invertedDirection(), new Edge(sw, node, factory==null? null:factory.createEdgeData(this, sw, node))); + if (sw != null && (s != null || w != null)) { + node.addEdge(Directions.SW, new Edge(node, sw, factory == null? null:factory.createEdgeData(this, node, sw))); + if(addAdjacent) sw.addEdge(Directions.SW.invertedDirection(), new Edge(sw, node, factory == null? null:factory.createEdgeData(this, sw, node))); } if (w != null) { - node.addEdge(Directions.W, new Edge(node, w, factory==null? null:factory.createEdgeData(this, node, w))); - if(addAdjacent) w.addEdge(Directions.W.invertedDirection(), new Edge(w, node, factory==null? null:factory.createEdgeData(this, w, node))); + node.addEdge(Directions.W, new Edge(node, w, factory == null? null:factory.createEdgeData(this, node, w))); + if(addAdjacent) w.addEdge(Directions.W.invertedDirection(), new Edge(w, node, factory == null? null:factory.createEdgeData(this, w, node))); } - if (nw != null && (n!=null||w!=null) ) { - node.addEdge(Directions.NW, new Edge(node, nw, factory==null? null:factory.createEdgeData(this, node, nw))); + if (nw != null && (n != null || w != null) ) { + node.addEdge(Directions.NW, new Edge(node, nw, factory == null? null:factory.createEdgeData(this, node, nw))); if(addAdjacent) nw.addEdge(Directions.NW.invertedDirection(), new Edge(nw, node, factory==null? null:factory.createEdgeData(this, nw, node))); } } @@ -1037,18 +1044,18 @@ public void render(Canvas canvas, Camera camera, float alpha) { int indexX = 0; int indexY = 0; - int toIndex_x=0, toIndex_y=0; + int toIndex_x = 0, toIndex_y = 0; - int camPosX = (int) (camPos.x); - int camPosY = (int) (camPos.y); + int camPosX = (int)(camPos.x); + int camPosY = (int)(camPos.y); // Current Tile offset (to pixels) - int tileOffset_x = -( camPosX % this.tileWidth ); - toIndex_x = ( tileOffset_x + camPosX) / this.tileWidth; + int tileOffset_x = -(camPosX % this.tileWidth); + toIndex_x = (tileOffset_x + camPosX) / this.tileWidth; // current tile y offset (to pixels) int tileOffset_y = -( camPosY % this.tileHeight); - toIndex_y = ( tileOffset_y + camPosY) / this.tileHeight; + toIndex_y = (tileOffset_y + camPosY) / this.tileHeight; // render the background renderBackground(canvas, camera); @@ -1062,22 +1069,22 @@ public void render(Canvas canvas, Camera camera, float alpha) { pixelX < viewport.getWidth() && indexX < this.maxX; pixelX += this.tileWidth, indexX++) { - if ( (indexY >= 0 && indexX >= 0) && (indexY < this.maxY && indexX < this.maxX) ) { + if ((indexY >= 0 && indexX >= 0) && (indexY < this.maxY && indexX < this.maxX)) { //for(int i = this.backgroundLayers.length - 1; i >= 0; i--) for(int i = 0; i < this.backgroundLayers.length; i++) { Layer layer = this.backgroundLayers[i]; - if ( layer == null ) { + if (layer == null) { continue; } - if ( layer.isPropertyLayer()) { + if (layer.isPropertyLayer()) { continue; } Tile tile = layer.getRow(indexY)[indexX]; - if ( tile != null ) { + if (tile != null) { tile.setRenderingPosition(pixelX + vx, pixelY + vy); tile.render(canvas, camera, alpha); @@ -1119,15 +1126,15 @@ public void renderForeground(Canvas canvas, Camera camera, float alpha) { int indexX = 0; int indexY = 0; - int toIndex_x=0, toIndex_y=0; + int toIndex_x = 0, toIndex_y = 0; // Current Tile offset (to pixels) - int tileOffset_x = -( (int)camPos.x % this.tileWidth ); - toIndex_x = ( tileOffset_x + (int)camPos.x) / this.tileWidth; + int tileOffset_x = -((int)camPos.x % this.tileWidth); + toIndex_x = (tileOffset_x + (int)camPos.x) / this.tileWidth; // current tile y offset (to pixels) - int tileOffset_y = -( (int)camPos.y % this.tileHeight); - toIndex_y = (tileOffset_y + (int)camPos.y) / this.tileHeight; + int tileOffset_y = -((int)camPos.y % this.tileHeight); + toIndex_y = (tileOffset_y + (int)camPos.y) / this.tileHeight; indexY = toIndex_y; for (pixelY = tileOffset_y; @@ -1138,21 +1145,20 @@ public void renderForeground(Canvas canvas, Camera camera, float alpha) { pixelX < viewport.getWidth() && indexX < this.maxX; pixelX += this.tileWidth, indexX++) { - if ( (indexY >= 0 && indexX >= 0) && (indexY < this.maxY && indexX < this.maxX) ) { + if ((indexY >= 0 && indexX >= 0) && (indexY < this.maxY && indexX < this.maxX)) { - for(int i = 0; i < this.foregroundLayers.length; i++) - { + for(int i = 0; i < this.foregroundLayers.length; i++) { Layer layer = this.foregroundLayers[i]; - if ( layer == null ) { + if (layer == null) { continue; } - if ( layer.isPropertyLayer()) { + if (layer.isPropertyLayer()) { continue; } Tile tile = layer.getRow(indexY)[indexX]; - if ( tile != null ) { + if (tile != null) { tile.setRenderingPosition(pixelX + vx, pixelY + vy); tile.render(canvas, camera, alpha); } @@ -1186,15 +1192,15 @@ public void renderSolid(Canvas canvas, Camera camera, float alpha) { int indexX = 0; int indexY = 0; - float toIndex_x=0, toIndex_y=0; + float toIndex_x = 0, toIndex_y = 0; // Current Tile offset (to pixels) - float tileOffset_x = -( camPos.x % this.tileWidth ); - toIndex_x = ( tileOffset_x + camPos.x) / this.tileWidth; + float tileOffset_x = -(camPos.x % this.tileWidth); + toIndex_x = (tileOffset_x + camPos.x) / this.tileWidth; // current tile y offset (to pixels) - float tileOffset_y = -( (int)camPos.y % this.tileHeight); - toIndex_y = (tileOffset_y + (int)camPos.y) / this.tileHeight; + float tileOffset_y = -((int)camPos.y % this.tileHeight); + toIndex_y = (tileOffset_y + (int)camPos.y) / this.tileHeight; indexY = (int)toIndex_y; Layer layer = this.backgroundLayers[0]; @@ -1206,11 +1212,11 @@ public void renderSolid(Canvas canvas, Camera camera, float alpha) { pixelX < viewport.getWidth() && indexX < this.maxX; pixelX += this.tileWidth, indexX++) { - if ( (indexY >= 0 && indexX >= 0) && (indexY < this.maxY && indexX < this.maxX) ) { + if ((indexY >= 0 && indexX >= 0) && (indexY < this.maxY && indexX < this.maxX)) { Tile tile = layer.getRow(indexY)[indexX]; - if ( tile != null ) { + if (tile != null) { int mask = tile.getMask(); - if(mask==0) { + if(mask == 0) { canvas.fillRect(pixelX + vx, pixelY + vy, tileWidth, tileHeight, currentColor); } else if (mask > 1) { @@ -1218,8 +1224,8 @@ else if (mask > 1) { float px = pixelX + vx; float py = pixelY + vy; - TextureRegion image = this.shadeTilesLookup.get(mask-1); - if(image!=null) { + TextureRegion image = this.shadeTilesLookup.get(mask - 1); + if(image != null) { canvas.drawImage(image, px, py, null); } } @@ -1236,7 +1242,7 @@ else if (mask > 1) { */ public void update(TimeStep timeStep) { - if ( this.mapOffset==null || this.currentFrameViewport==null ) { + if (this.mapOffset == null || this.currentFrameViewport == null) { return; } boolean doIt = false; @@ -1252,16 +1258,16 @@ public void update(TimeStep timeStep) { int indexX = 0; int indexY = 0; - int toIndex_x=0, toIndex_y=0; + int toIndex_x = 0, toIndex_y = 0; // Current Tile offset (to pixels) - int tileOffset_x = -( (int)camPos.x % this.tileWidth ); + int tileOffset_x = -((int)camPos.x % this.tileWidth); // to next index - toIndex_x = ( tileOffset_x + (int)camPos.x) / this.tileWidth; + toIndex_x = (tileOffset_x + (int)camPos.x) / this.tileWidth; // current tile y offset (to pixels) - int tileOffset_y = -( (int)camPos.y % this.tileHeight); - toIndex_y = (tileOffset_y + (int)camPos.y) / this.tileHeight; + int tileOffset_y = -((int)camPos.y % this.tileHeight); + toIndex_y = (tileOffset_y + (int)camPos.y) / this.tileHeight; indexY = toIndex_y; for (pixelY = tileOffset_x; @@ -1272,33 +1278,33 @@ public void update(TimeStep timeStep) { pixelX < viewport.getWidth() && indexX < this.maxX; pixelX += this.tileWidth, indexX++) { - if ( (indexY >= 0 && indexX >= 0) && (indexY < this.maxY && indexX < this.maxX) ) { + if ((indexY >= 0 && indexX >= 0) && (indexY < this.maxY && indexX < this.maxX)) { for (Layer layer : this.backgroundLayers) { - if ( layer == null ) { + if (layer == null) { continue; } - if ( !layer.hasAnimations() ) { + if (!layer.hasAnimations()) { continue; } Tile tile = layer.getRow(indexY)[indexX]; - if ( tile != null ) { + if (tile != null) { tile.update(timeStep); } } for (Layer layer : this.foregroundLayers) { - if ( layer == null ) { + if (layer == null) { continue; } - if ( !layer.hasAnimations() ) { + if (!layer.hasAnimations()) { continue; } Tile tile = layer.getRow(indexY)[indexX]; - if ( tile != null ) { + if (tile != null) { tile.update(timeStep); } } @@ -1326,7 +1332,7 @@ private void renderMapObjects(Canvas canvas, Camera camera, float alpha) { * @param camera */ private void renderBackground(Canvas canvas, Camera camera) { - if ( this.backgroundImage == null ) { + if (this.backgroundImage == null) { return; } @@ -1380,7 +1386,7 @@ public List getRemovedTiles() { @Override public boolean removeDestructableTilesAt(int[] tilePositions) { if(tilePositions != null) { - for(int i = 0; i < tilePositions.length; i+=2) { + for(int i = 0; i < tilePositions.length; i += 2) { removeDestructableTileAt(tilePositions[i + 0], tilePositions[i + 1]); } } @@ -1418,7 +1424,7 @@ public boolean removeDestructableTileAt(int tileX, int tileY) { for(int i = 0; i < this.destructableLayer.length; i++) { Layer layer = this.destructableLayer[i]; Tile tile = layer.getRow(tileY)[tileX]; - if(tile!=null) { + if(tile != null) { if(!tile.isDestroyed()) { this.destroyedTiles.add(tile); tile.setDestroyed(true); diff --git a/src/seventh/map/Tile.java b/src/seventh/map/Tile.java index f8d7a6f..fa89cf7 100644 --- a/src/seventh/map/Tile.java +++ b/src/seventh/map/Tile.java @@ -65,7 +65,7 @@ public static SurfaceType fromId(int id) { public static SurfaceType fromString(String type) { SurfaceType result = UNKNOWN; try { - if(type!=null) { + if(type != null) { result = SurfaceType.valueOf(type.toUpperCase()); } } @@ -133,21 +133,21 @@ public boolean rectCollide(Rectangle a, Rectangle b) { EAST_HALF_SOLID(3) { @Override public boolean pointCollide(Rectangle a, int x, int y) { - a.x += (a.width/2); + a.x += (a.width / 2); a.width /= 2; return a.contains(x, y); } @Override public boolean rectCollide(Rectangle a, OBB oob) { - a.x += (a.width/2); + a.x += (a.width / 2); a.width /= 2; return oob.intersects(a); } @Override public boolean rectCollide(Rectangle a, Rectangle b) { - a.x += (a.width/2); + a.x += (a.width / 2); a.width /= 2; return a.intersects(b); } @@ -177,7 +177,7 @@ public boolean rectCollide(Rectangle a, Rectangle b) { SOUTH_HALF_SOLID(5) { @Override public boolean pointCollide(Rectangle a, int x, int y) { - a.y += (a.height/2); + a.y += (a.height / 2); a.height /= 2; return a.contains(x, y); } @@ -185,14 +185,14 @@ public boolean pointCollide(Rectangle a, int x, int y) { @Override public boolean rectCollide(Rectangle a, OBB oob) { - a.y += (a.height/2); + a.y += (a.height / 2); a.height /= 2; return oob.intersects(a); } @Override public boolean rectCollide(Rectangle a, Rectangle b) { - a.y += (a.height/2); + a.y += (a.height / 2); a.height /= 2; return a.intersects(b); } @@ -210,7 +210,7 @@ public boolean pointCollide(Rectangle a, int x, int y) { a.height = height; a.width /= 2; - return a.contains(x,y); + return a.contains(x, y); } return true; } @@ -258,10 +258,10 @@ public boolean pointCollide(Rectangle a, int x, int y) { if(!north) { a.height = height; - a.x += (width/2); + a.x += (width / 2); a.width /= 2; - return a.contains(x,y); + return a.contains(x, y); } return true; } @@ -276,7 +276,7 @@ public boolean rectCollide(Rectangle a, OBB oob) { if(!north) { a.height = height; - a.x += (width/2); + a.x += (width / 2); a.width /= 2; return oob.intersects(a); @@ -294,7 +294,7 @@ public boolean rectCollide(Rectangle a, Rectangle b) { if(!north) { a.height = height; - a.x += (width/2); + a.x += (width / 2); a.width /= 2; return a.intersects(b); @@ -316,7 +316,7 @@ public boolean pointCollide(Rectangle a, int x, int y) { a.height = height; a.width /= 2; - return a.contains(x,y); + return a.contains(x, y); } return true; } @@ -880,8 +880,8 @@ public boolean pointCollide(Rectangle a, int x, int y) { int width = a.width; int height = a.height; - a.set(ax+width/2, ay+height/2, width/2, height/2); - return a.contains(x,y); + a.set(ax + width / 2, ay + height / 2, width / 2, height / 2); + return a.contains(x, y); } @Override @@ -891,7 +891,7 @@ public boolean rectCollide(Rectangle a, OBB oob) { int width = a.width; int height = a.height; - a.set(ax+width/2, ay+height/2, width/2, height/2); + a.set(ax + width / 2, ay + height / 2, width / 2, height / 2); return oob.intersects(a); } @@ -902,7 +902,7 @@ public boolean rectCollide(Rectangle a, Rectangle b) { int width = a.width; int height = a.height; - a.set(ax+width/2, ay+height/2, width/2, height/2); + a.set(ax + width / 2, ay + height / 2, width / 2, height / 2); return a.intersects(b); } @@ -916,8 +916,8 @@ public boolean pointCollide(Rectangle a, int x, int y) { int width = a.width; int height = a.height; - a.set(ax, ay, width/2, height/2); - return a.contains(x,y); + a.set(ax, ay, width / 2, height / 2); + return a.contains(x, y); } @Override @@ -927,7 +927,7 @@ public boolean rectCollide(Rectangle a, OBB oob) { int width = a.width; int height = a.height; - a.set(ax, ay, width/2, height/2); + a.set(ax, ay, width / 2, height / 2); return oob.intersects(a); } @@ -938,7 +938,7 @@ public boolean rectCollide(Rectangle a, Rectangle b) { int width = a.width; int height = a.height; - a.set(ax, ay, width/2, height/2); + a.set(ax, ay, width / 2, height / 2); return a.intersects(b); } @@ -952,8 +952,8 @@ public boolean pointCollide(Rectangle a, int x, int y) { int width = a.width; int height = a.height; - a.set(ax+width/2, ay, width/2, height/2); - return a.contains(x,y); + a.set(ax + width / 2, ay, width / 2, height / 2); + return a.contains(x, y); } @Override @@ -963,7 +963,7 @@ public boolean rectCollide(Rectangle a, OBB oob) { int width = a.width; int height = a.height; - a.set(ax+width/2, ay, width/2, height/2); + a.set(ax + width / 2, ay, width / 2, height / 2); return oob.intersects(a); } @@ -974,7 +974,7 @@ public boolean rectCollide(Rectangle a, Rectangle b) { int width = a.width; int height = a.height; - a.set(ax+width/2, ay, width/2, height/2); + a.set(ax + width / 2, ay, width / 2, height / 2); return a.intersects(b); } @@ -988,8 +988,8 @@ public boolean pointCollide(Rectangle a, int x, int y) { int width = a.width; int height = a.height; - a.set(ax, ay+height/2, width/2, height/2); - return a.contains(x,y); + a.set(ax, ay + height / 2, width / 2, height / 2); + return a.contains(x, y); } @Override @@ -999,7 +999,7 @@ public boolean rectCollide(Rectangle a, OBB oob) { int width = a.width; int height = a.height; - a.set(ax, ay+height/2, width/2, height/2); + a.set(ax, ay + height / 2, width / 2, height / 2); return oob.intersects(a); } @@ -1010,7 +1010,7 @@ public boolean rectCollide(Rectangle a, Rectangle b) { int width = a.width; int height = a.height; - a.set(ax, ay+height/2, width/2, height/2); + a.set(ax, ay + height / 2, width / 2, height / 2); return a.intersects(b); } @@ -1019,14 +1019,14 @@ public boolean rectCollide(Rectangle a, Rectangle b) { MIDDLE_VERTICAL_SLICE_SOLID(24) { @Override public boolean pointCollide(Rectangle a, int x, int y) { - a.x += a.width/2; + a.x += a.width / 2; a.width = 5; return a.contains(x, y); } @Override public boolean rectCollide(Rectangle a, OBB oob) { - a.x += a.width/2; + a.x += a.width / 2; a.width = 5; return oob.intersects(a); @@ -1034,7 +1034,7 @@ public boolean rectCollide(Rectangle a, OBB oob) { @Override public boolean rectCollide(Rectangle a, Rectangle b) { - a.x += a.width/2; + a.x += a.width / 2; a.width = 5; return a.intersects(b); @@ -1044,21 +1044,21 @@ public boolean rectCollide(Rectangle a, Rectangle b) { MIDDLE_HORIZONTAL_SLICE_SOLID(25) { @Override public boolean pointCollide(Rectangle a, int x, int y) { - a.y += a.height/2; + a.y += a.height / 2; a.height = 5; return a.contains(x, y); } @Override public boolean rectCollide(Rectangle a, OBB oob) { - a.y += a.height/2; + a.y += a.height / 2; a.height = 5; return oob.intersects(a); } @Override public boolean rectCollide(Rectangle a, Rectangle b) { - a.y += a.height/2; + a.y += a.height / 2; a.height = 5; return a.intersects(b); @@ -1197,8 +1197,8 @@ public boolean rectCollide(Rectangle a, Rectangle b) { @Override public boolean pointCollide(Rectangle a, int x, int y) { - float circleX = a.x + a.width/2; - float circleY = a.y + a.height/2; + float circleX = a.x + a.width / 2; + float circleY = a.y + a.height / 2; float radius = 16f; return Circle.circleContainsPoint(circleX, circleY, radius, x, y); @@ -1211,12 +1211,61 @@ public boolean rectCollide(Rectangle a, OBB oob) { @Override public boolean rectCollide(Rectangle a, Rectangle b) { - float circleX = a.x + a.width/2; - float circleY = a.y + a.height/2; + float circleX = a.x + a.width / 2; + float circleY = a.y + a.height / 2; float radius = 16f; return Circle.circleIntersectsRect(circleX, circleY, radius, b); } + }, + + CENTER_VERTICAL_SOLID(31) { + + @Override + public boolean pointCollide(Rectangle a, int x, int y) { + a.x += 8; + a.width /= 2; + return a.contains(x, y); + } + + + @Override + public boolean rectCollide(Rectangle a, OBB oob) { + a.x += 8; + a.width /= 2; + return oob.intersects(a); + } + + @Override + public boolean rectCollide(Rectangle a, Rectangle b) { + a.x += 8; + a.width /= 2; + return a.intersects(b); + } + }, + + CENTER_HORIZONTAL_SOLID(32) { + @Override + public boolean pointCollide(Rectangle a, int x, int y) { + a.y += 8; + a.height /= 2; + return a.contains(x, y); + } + + @Override + public boolean rectCollide(Rectangle a, OBB oob) { + a.y += 8; + a.height /= 2; + return oob.intersects(a); + } + + @Override + public boolean rectCollide(Rectangle a, Rectangle b) { + a.y += 8; + a.height /= 2; + return a.intersects(b); + + } } ; @@ -1247,7 +1296,7 @@ public static CollisionMask fromId(int id) { /** * Flip masks */ - private static final int isFlippedHorizontal=(1<<0), isFlippedVert=(1<<1), isFlippedDiagnally=(1<<2); + private static final int isFlippedHorizontal=(1 << 0), isFlippedVert=(1 << 1), isFlippedDiagnally=(1 << 2); private int x,y; private int width, height; @@ -1293,7 +1342,7 @@ public Tile(TextureRegion image, int layer, int width, int height) { * code to the render() method for quick * responsive feedback */ - if(image!=null) { + if(image != null) { this.sprite = new Sprite(image); this.u = image.getU(); this.u2 = image.getU2(); @@ -1306,11 +1355,11 @@ public Tile(TextureRegion image, int layer, int width, int height) { float adjustX = 0.0125f / width; float adjustY = 0.0125f / height; - sprite.setU(u+adjustX); - sprite.setU2(u2-adjustX); + sprite.setU(u + adjustX); + sprite.setU2(u2 - adjustX); - sprite.setV(v-adjustY); - sprite.setV2(v2+adjustY); + sprite.setV(v - adjustY); + sprite.setV2(v2 + adjustY); } } @@ -1397,8 +1446,8 @@ public int getY() { * @return the centerPos */ public Vector2f getCenterPos() { - this.centerPos.set(this.x + this.width/2, - this.y + this.height/2); + this.centerPos.set(this.x + this.width / 2, + this.y + this.height / 2); return centerPos; } @@ -1496,7 +1545,7 @@ public void setFlips(boolean isFlippedHorizontal, boolean isFlippedVert, boolean if(isFlippedDiagnally) this.flipMask |= Tile.isFlippedDiagnally; if(isFlippedHorizontal) this.flipMask |= Tile.isFlippedHorizontal; if(isFlippedVert) this.flipMask |= Tile.isFlippedVert; - if(this.sprite==null) return; + if(this.sprite == null) return; TextureUtil.setFlips(this.sprite, isFlippedHorizontal, isFlippedVert, isFlippedDiagnally); } diff --git a/src/seventh/map/TiledMapLoader.java b/src/seventh/map/TiledMapLoader.java index 2f68457..70682ca 100644 --- a/src/seventh/map/TiledMapLoader.java +++ b/src/seventh/map/TiledMapLoader.java @@ -104,7 +104,7 @@ private void parseSurfaces(SurfaceType[][] surfaces, TilesetAtlas atlas, LeoArra } int tileId = data.get(x).asInt(); - int surfaceId = atlas.getTileId(tileId)-1; /* minus one to get back to zero based */ + int surfaceId = atlas.getTileId(tileId) - 1; /* minus one to get back to zero based */ surfaces[y][x % width] = SurfaceType.fromId(surfaceId); } } @@ -170,7 +170,7 @@ private Layer parseLayer(LeoMap layer, int index, TilesetAtlas atlas, boolean lo boolean isVisible = layer.getBoolean("visible"); int heightMask = 0; - if ( layer.has(LeoString.valueOf("properties"))) { + if (layer.has(LeoString.valueOf("properties"))) { LeoMap properties = layer.getByString("properties").as(); isCollidable = properties.getString("collidable").equals("true"); isForeground = properties.getString("foreground").equals("true"); @@ -233,7 +233,7 @@ private Layer parseLayer(LeoMap layer, int index, TilesetAtlas atlas, boolean lo TextureRegion image = atlas.getTile(tileId); if(image != null) { Tile tile = null; - if( atlas.isAnimatedTile(tileId) ) { + if(atlas.isAnimatedTile(tileId)) { tile = new AnimatedTile(atlas.getAnimatedTile(tileId), index, tileWidth, tileHeight); mapLayer.setContainsAnimations(true); } @@ -241,7 +241,7 @@ private Layer parseLayer(LeoMap layer, int index, TilesetAtlas atlas, boolean lo tile = new Tile(image, index, tileWidth, tileHeight); } - tile.setPosition( (x%width) * tileWidth, y); + tile.setPosition((x % width) * tileWidth, y); // tile.setSurfaceType(atlas.getTileSurfaceType(tileId)); tile.setFlips(flippedHorizontally, flippedVertically, flippedDiagonally); @@ -249,27 +249,27 @@ private Layer parseLayer(LeoMap layer, int index, TilesetAtlas atlas, boolean lo int collisionId = atlas.getTileId(tileId); tile.setCollisionMaskById(collisionId); } - row[x%width] = tile; + row[x % width] = tile; } else { - row[x%width] = null; + row[x % width] = null; } } // if we are headless... else { if(tileId != 0) { - Tile tile = new Tile(null, index, tileWidth,tileHeight); - tile.setPosition( (x%width) * tileWidth, y); + Tile tile = new Tile(null, index, tileWidth, tileHeight); + tile.setPosition( (x % width) * tileWidth, y); // tile.setSurfaceType(atlas.getTileSurfaceType(tileId)); if(isCollidable) { int collisionId = atlas.getTileId(tileId); tile.setCollisionMaskById(collisionId); } - row[x%width] = tile; + row[x % width] = tile; } else { - row[x%width] = null; + row[x % width] = null; } } } diff --git a/src/seventh/map/Tileset.java b/src/seventh/map/Tileset.java index bad7e6f..5476dbd 100644 --- a/src/seventh/map/Tileset.java +++ b/src/seventh/map/Tileset.java @@ -33,9 +33,9 @@ public Tileset(int startId, TextureRegion[] image, LeoMap props) { * Frees the texture memory */ public void destroy() { - if(this.image!=null&&this.image.length > 0) { + if(this.image != null && this.image.length > 0) { TextureRegion tex = this.image[0]; - if(tex!=null) { + if(tex != null) { tex.getTexture().dispose(); } } diff --git a/src/seventh/map/TilesetAtlas.java b/src/seventh/map/TilesetAtlas.java index e8bbb48..2024218 100644 --- a/src/seventh/map/TilesetAtlas.java +++ b/src/seventh/map/TilesetAtlas.java @@ -34,7 +34,7 @@ public void addTileset(Tileset t) { public TextureRegion getTile(int id) { for(Tileset t : tilesets) { TextureRegion img = t.getTile(id); - if(img!=null) { + if(img != null) { return img; } } @@ -49,7 +49,7 @@ public TextureRegion getTile(int id) { public boolean isAnimatedTile(int id) { for(Tileset t : tilesets) { TextureRegion img = t.getTile(id); - if(img!=null) { + if(img != null) { return t.isAnimatedImage(id); } } @@ -60,7 +60,7 @@ public boolean isAnimatedTile(int id) { public AnimatedImage getAnimatedTile(int id) { for(Tileset t : tilesets) { TextureRegion img = t.getTile(id); - if(img!=null) { + if(img != null) { return t.getAnimatedImage(id); } } diff --git a/src/seventh/math/Circle.java b/src/seventh/math/Circle.java index 35bfbce..5ff26f1 100644 --- a/src/seventh/math/Circle.java +++ b/src/seventh/math/Circle.java @@ -43,7 +43,7 @@ public static boolean circleContainsPoint(Circle circle, Vector2f a) { */ public static boolean circleContainsPoint(float cx, float cy, float radius, float x, float y) { float distSq = (cx - x) * 2 + (cy - y) * 2; - return distSq <= radius*radius; + return distSq <= radius * radius; } /** @@ -71,8 +71,8 @@ public static boolean circleContainsRect(float cx, float cy, float radius, Recta int height = rect.getHeight(); // check if it is inside - return (cx > x && cx < x+width && - cy < y+height && cy > y ); + return (cx > x && cx < x + width && + cy < y + height && cy > y ); } @@ -98,14 +98,14 @@ public static boolean circleIntersectsRect(float cx, float cy, float radius, Rec float circleDistanceX = Math.abs(cx - rect.x); float circleDistanceY = Math.abs(cy - rect.y); - if (circleDistanceX > (rect.width/2 + radius)) { return false; } - if (circleDistanceY > (rect.height/2 + radius)) { return false; } + if (circleDistanceX > (rect.width / 2 + radius)) { return false; } + if (circleDistanceY > (rect.height / 2 + radius)) { return false; } - if (circleDistanceX <= (rect.width/2)) { return true; } - if (circleDistanceY <= (rect.height/2)) { return true; } + if (circleDistanceX <= (rect.width / 2)) { return true; } + if (circleDistanceY <= (rect.height / 2)) { return true; } - float cornerDistanceSq = (circleDistanceX - rect.width/2) * (circleDistanceX - rect.width/2) + - (circleDistanceY - rect.height/2) * (circleDistanceY - rect.height/2); + float cornerDistanceSq = (circleDistanceX - rect.width / 2) * (circleDistanceX - rect.width / 2) + + (circleDistanceY - rect.height / 2) * (circleDistanceY - rect.height / 2); return (cornerDistanceSq <= (radius * radius)); } @@ -143,7 +143,7 @@ public static boolean circleIntersectsLine(Circle circle, Vector2f a, Vector2f b float det = Vector2fDet(ca, cb); // only the discriminant matters: - float delta = circle.radius * circle.radius * dr - (det*det); + float delta = circle.radius * circle.radius * dr - (det * det); /* * Delta<0 no intersection diff --git a/src/seventh/math/FastMath.java b/src/seventh/math/FastMath.java index 3f09d4f..2fc0e17 100644 --- a/src/seventh/math/FastMath.java +++ b/src/seventh/math/FastMath.java @@ -9,13 +9,13 @@ /** * Utility and fast math functions. * - * Thanks to:
+ * Thanks to:
* Riven on JavaGaming.org for sin/cos/atan2 tables.
* Roquen on JavaGaming.org for random numbers.
* pjt33 on JavaGaming.org for fixed point.
- * Jim Shima for atan2_fast.
+ * Jim Shima for atan2_fast.
* - *

+ *

* Taken from JavaGaming.org from Nate * * @author Nate @@ -39,39 +39,39 @@ public class FastMath { static { for (int i = 0; i < SIN_COUNT; i++) { float a = (i + 0.5f) / SIN_COUNT * radFull; - sin[i] = (float) Math.sin(a); - cos[i] = (float) Math.cos(a); + sin[i] = (float)Math.sin(a); + cos[i] = (float)Math.cos(a); } } static public final float sin(float rad) { - return sin[(int) (rad * radToIndex) & SIN_MASK]; + return sin[(int)(rad * radToIndex) & SIN_MASK]; } static public final float cos(float rad) { - return cos[(int) (rad * radToIndex) & SIN_MASK]; + return cos[(int)(rad * radToIndex) & SIN_MASK]; } static public final float sin(int deg) { - return sin[(int) (deg * degToIndex) & SIN_MASK]; + return sin[(int)(deg * degToIndex) & SIN_MASK]; } static public final float cos(int deg) { - return cos[(int) (deg * degToIndex) & SIN_MASK]; + return cos[(int)(deg * degToIndex) & SIN_MASK]; } private static final int ATAN2_BITS = 7; // Adjust for accuracy. private static final int ATAN2_BITS2 = ATAN2_BITS << 1; private static final int ATAN2_MASK = ~(-1 << ATAN2_BITS2); private static final int ATAN2_COUNT = ATAN2_MASK + 1; - private static final int ATAN2_DIM = (int) Math.sqrt(ATAN2_COUNT); + private static final int ATAN2_DIM = (int)Math.sqrt(ATAN2_COUNT); private static final float INV_ATAN2_DIM_MINUS_1 = 1.0f / (ATAN2_DIM - 1); private static final float [] atan2 = new float[ATAN2_COUNT]; static { for (int i = 0; i < ATAN2_DIM; i++) { for (int j = 0; j < ATAN2_DIM; j++) { - float x0 = (float) i / ATAN2_DIM; - float y0 = (float) j / ATAN2_DIM; + float x0 = (float)i / ATAN2_DIM; + float y0 = (float)j / ATAN2_DIM; atan2[j * ATAN2_DIM + i] = (float) Math.atan2(y0, x0); } } @@ -152,7 +152,7 @@ static public final float sqrt(float value) { * @return */ public static float a_isqrt(float x) { - + float hx = x * 0.5f; int ix; float r; @@ -164,7 +164,7 @@ public static float a_isqrt(float x) { // do some number of newton-ralphson steps, // each doubles the number of accurate // binary digits. - r = r * (1.5f - hx(x) * r * r); + r = r * (1.5f - hx * r * r); // r = r*(1.5f-hx*r*r); // r = r*(1.5f-hx*r*r); // r = r*(1.5f-hx*r*r); @@ -180,6 +180,7 @@ public static float a_isqrt(float x) { * @return */ public static float a_sqrt(float x) { + float hx = x * 0.5f; int ix; float r; @@ -191,34 +192,29 @@ public static float a_sqrt(float x) { // do some number of newton-ralphson steps, // each doubles the number of accurate // binary digits. - r = r * (1.5f - hx(x) * r * r); + r = r * (1.5f - hx * r * r); // r = r*(1.5f-hx*r*r); // r = r*(1.5f-hx*r*r); // r = r*(1.5f-hx*r*r); - return r*x; // sqrt(x) + return r * x; // sqrt(x) } - private static float hx(float x) { - float hx = x * 0.5f; - return hx; - } - /** * Fixed point multiply. */ static public int multiply(int x, int y) { - return (int) ((long) x * (long) y >> 16); + return (int)((long) x * (long) y >> 16); } /** * Fixed point divide. */ static public int divide(int x, int y) { - return (int) ((((long) x) << 16) / y); + return (int)((((long) x) << 16) / y); } - static private int randomSeed = (int) System.currentTimeMillis(); + static private int randomSeed = (int)System.currentTimeMillis(); /** * Returns a random number between 0 (inclusive) and the specified value @@ -227,25 +223,28 @@ static public int divide(int x, int y) { * @param range * Must be >= 0. */ - private static int seed() { - int seed = randomSeed * 1103515245 + 12345; - randomSeed = seed; - return seed; - } static public final int random(int range) { - return ((seed() >>> 15) * (range + 1)) >>> 17; + int seed = randomSeed * 1103515245 + 12345; + randomSeed = seed; + return ((seed >>> 15) * (range + 1)) >>> 17; } - + static public final int random(int start, int end) { - return (((seed() >>> 15) * ((end - start) + 1)) >>> 17) + start; + int seed = randomSeed * 1103515245 + 12345; + randomSeed = seed; + return (((seed >>> 15) * ((end - start) + 1)) >>> 17) + start; } static public final boolean randomBoolean() { - return seed() > 0; + int seed = randomSeed * 1103515245 + 12345; + randomSeed = seed; + return seed > 0; } static public final float random() { - return (seed() >>> 8) * (1f / (1 << 24)); + int seed = randomSeed * 1103515245 + 12345; + randomSeed = seed; + return (seed >>> 8) * (1f / (1 << 24)); } static public int nextPowerOfTwo(int value) { diff --git a/src/seventh/math/FloatUtil.java b/src/seventh/math/FloatUtil.java index 244eaa5..cea0882 100644 --- a/src/seventh/math/FloatUtil.java +++ b/src/seventh/math/FloatUtil.java @@ -30,7 +30,7 @@ private FloatUtil() { * @return */ public static boolean eq(float f1, float f2) { - return Math.abs(f1-f2) < epsilon; + return Math.abs(f1 - f2) < epsilon; } /** @@ -42,7 +42,7 @@ public static boolean eq(float f1, float f2) { * @return true if equal */ public static boolean eq(float f1, float f2, float epsilon) { - return Math.abs(f1-f2) < epsilon; + return Math.abs(f1 - f2) < epsilon; } /** @@ -169,7 +169,7 @@ public static float Vector2fLengthSq(float[] a) { public static void Vector2fNormalize(float[] a, float[] dest) { float fLen = (float)Math.sqrt( (a[X] * a[X] + a[Y] * a[Y]) ); - if ( fLen==0 ) return; + if ( fLen == 0 ) return; fLen = 1.0f / fLen; dest[X] = a[X] * fLen; diff --git a/src/seventh/math/Line.java b/src/seventh/math/Line.java index 4661a01..0790384 100644 --- a/src/seventh/math/Line.java +++ b/src/seventh/math/Line.java @@ -200,14 +200,14 @@ private static int outcode(Rectangle r, float x, float y) { out |= OUT_LEFT | OUT_RIGHT; } else if (x < r.x) { out |= OUT_LEFT; - } else if (x > r.x + (float) r.width) { + } else if (x > r.x + (float)r.width) { out |= OUT_RIGHT; } if (r.height <= 0) { out |= OUT_TOP | OUT_BOTTOM; } else if (y < r.y) { out |= OUT_TOP; - } else if (y > r.y + (float) r.height) { + } else if (y > r.y + (float)r.height) { out |= OUT_BOTTOM; } return out; @@ -294,7 +294,7 @@ public static boolean lineIntersectsRectangle(Vector2f v1, Vector2f v2, Rectangl C.x = rect.getX() + E.x; C.y = rect.getY() + E.y; - float t[] = {0,0}; /* parametric values corresponding to the points where the line intersects the AABB. */ + float t[] = {0, 0}; /* parametric values corresponding to the points where the line intersects the AABB. */ boolean result = intersectLineAABB(O, D, C, E, t, FloatUtil.epsilon); Vector2f tmp = new Vector2f(); @@ -308,7 +308,7 @@ public static boolean lineIntersectsRectangle(Vector2f v1, Vector2f v2, Rectangl Vector2f.Vector2fAdd(O, tmp, far); return result && (rect.contains(far) - || rect.contains(near)); + || rect.contains(near)); } /** @@ -373,7 +373,7 @@ private static boolean intersectLineAABB( int parallel = 0; boolean found = false; Vector2f d = new Vector2f(); - Vector2f.Vector2fSubtract(C,O, d); + Vector2f.Vector2fSubtract(C, O, d); for (int i = 0; i < 2; ++i) { @@ -418,11 +418,11 @@ private static boolean intersectLineAABB( } public static void main(String [] args) { - Line l = new Line(new Vector2f(-1,-1), new Vector2f(1,1)); + Line l = new Line(new Vector2f(-1, -1), new Vector2f(1, 1)); // Vector2f Pnear = new Vector2f(); // Vector2f Pfar = new Vector2f(); - Vector2f C = new Vector2f(2,2); - Vector2f E = new Vector2f(2,2); + Vector2f C = new Vector2f(2, 2); + Vector2f E = new Vector2f(2, 2); // Vector2f [] D = new Vector2f[2]; // //for(int i = 0 ; i < 2; i++) { // D[0] = new Vector2f(0,0); @@ -430,7 +430,7 @@ public static void main(String [] args) { // //} // l.SegmentIntersectBox(l, C, R, D, Pnear, Pfar); - float [] t = {0,0}; + float [] t = {0, 0}; intersectLineAABB(l.a, l.b, C, E, t, FloatUtil.epsilon); Vector2f tmp = new Vector2f(); diff --git a/src/seventh/math/MathLeolaLibrary.java b/src/seventh/math/MathLeolaLibrary.java index 2dbd86d..7aa6688 100644 --- a/src/seventh/math/MathLeolaLibrary.java +++ b/src/seventh/math/MathLeolaLibrary.java @@ -34,10 +34,10 @@ public void init(Leola leola, LeoNamespace namespace) throws LeolaRuntimeExcepti } public Vector2f newVec2(Double x, Double y) { - if(x!=null&&y!=null) - return new Vector2f(x.floatValue(),y.floatValue()); - if(x!=null) - return new Vector2f(x.floatValue(),0.0f); + if(x != null && y != null) + return new Vector2f(x.floatValue(), y.floatValue()); + if(x != null) + return new Vector2f(x.floatValue(), 0.0f); return new Vector2f(); } diff --git a/src/seventh/math/Matrix2f.java b/src/seventh/math/Matrix2f.java index ce37db5..961bbd2 100644 --- a/src/seventh/math/Matrix2f.java +++ b/src/seventh/math/Matrix2f.java @@ -25,8 +25,7 @@ public class Matrix2f { /** * Identity matrix */ - public static final Matrix2f IDENTITY = new Matrix2f(1,0 - ,0,1); + public static final Matrix2f IDENTITY = new Matrix2f(1, 0, 0, 1); /** * @param m diff --git a/src/seventh/math/OBB.java b/src/seventh/math/OBB.java index 1053af2..480c55f 100644 --- a/src/seventh/math/OBB.java +++ b/src/seventh/math/OBB.java @@ -33,7 +33,7 @@ public OBB() { * @param r */ public OBB(Rectangle r) { - this(0, new Vector2f(r.x + r.width/2, r.y + r.height/2), r.width, r.height); + this(0, new Vector2f(r.x + r.width / 2, r.y + r.height / 2), r.width, r.height); } /** @@ -43,7 +43,7 @@ public OBB(Rectangle r) { * @param r */ public OBB(float orientation, Rectangle r) { - this(orientation, new Vector2f(r.x + r.width/2, r.y + r.height/2), r.width, r.height); + this(orientation, new Vector2f(r.x + r.width / 2, r.y + r.height / 2), r.width, r.height); } /** @@ -106,11 +106,11 @@ public void update(float newOrientation, Vector2f center) { public void update(float newOrientation, float px, float py) { // first translate to center coordinate space - this.center.set(0,0); - this.topLeft.set(center.x-width/2f, center.y+height/2f); - this.topRight.set(center.x+width/2f, center.y+height/2f); - this.bottomLeft.set(center.x-width/2f, center.y-height/2f); - this.bottomRight.set(center.x+width/2f, center.y-height/2f); + this.center.set(0, 0); + this.topLeft.set(center.x - width / 2f, center.y + height / 2f); + this.topRight.set(center.x + width / 2f, center.y + height / 2f); + this.bottomLeft.set(center.x - width / 2f, center.y - height / 2f); + this.bottomRight.set(center.x + width / 2f, center.y - height / 2f); // rotate the rectangle this.orientation = newOrientation; @@ -191,7 +191,7 @@ public void translate(Vector2f p) { * @param py */ public void translate(float px, float py) { - setLocation(center.x+px, center.y+py); + setLocation(center.x + px, center.y + py); } /** @@ -280,7 +280,7 @@ private boolean pointInTriangle(float px, float py, Vector2f a, Vector2f b, Vect boolean b1 = sign(px, py, a, b) < 0f; boolean b2 = sign(px, py, b, c) < 0f; boolean b3 = sign(px, py, c, a) < 0f; - return ((b1==b2) && (b2==b3)); + return ((b1 == b2) && (b2 == b3)); } /** @@ -425,10 +425,10 @@ private boolean checkLineAgainstOOB(Vector2f a, Vector2f b, OBB other) { } private boolean checkLineAgainstOOB(Vector2f a, Vector2f b, Rectangle other) { - return Line.lineIntersectLine(a.x, a.y, b.x, b.y, other.x , other.y , other.x+other.width, other.y) || - Line.lineIntersectLine(a.x, a.y, b.x, b.y, other.x+other.width, other.y , other.x+other.width, other.y+other.height) || - Line.lineIntersectLine(a.x, a.y, b.x, b.y, other.x+other.width, other.y+other.height, other.x , other.y+other.height) || - Line.lineIntersectLine(a.x, a.y, b.x, b.y, other.x , other.y+other.height, other.x , other.y); + return Line.lineIntersectLine(a.x, a.y, b.x, b.y, other.x , other.y , other.x + other.width, other.y) || + Line.lineIntersectLine(a.x, a.y, b.x, b.y, other.x+other.width, other.y , other.x + other.width, other.y + other.height) || + Line.lineIntersectLine(a.x, a.y, b.x, b.y, other.x+other.width, other.y + other.height, other.x , other.y + other.height) || + Line.lineIntersectLine(a.x, a.y, b.x, b.y, other.x , other.y + other.height, other.x , other.y); } @@ -449,7 +449,7 @@ public String toString() { } public static void main(String[] args) { - OBB a = new OBB( (float)Math.PI/4f, new Vector2f(0,0), 50, 50); + OBB a = new OBB( (float)Math.PI / 4f, new Vector2f(0, 0), 50, 50); System.out.println(a.contains(1, 1)); @@ -467,7 +467,7 @@ public static void main(String[] args) { System.out.println(a.contains(-d, 0)); Vector2f v = new Vector2f(25, 0); - Vector2f.Vector2fRotate(v, 3*Math.PI/4, v); + Vector2f.Vector2fRotate(v, 3 * Math.PI / 4, v); System.out.println("Point is in a: " + a.contains(v)); // a.setLocation(76, 76); @@ -475,7 +475,7 @@ public static void main(String[] args) { printOOB(a); - OBB b = new OBB( a.orientation, new Vector2f(35.355f,35.355f), 50, 50); + OBB b = new OBB( a.orientation, new Vector2f(35.355f, 35.355f), 50, 50 ); b.translate(1, 1); b.translate(-1, -1); printOOB(b); @@ -502,10 +502,10 @@ public static void main(String[] args) { } private static void printOOB(OBB a) { - System.out.printf("C : (%3.1f, %3.1f) D: %3.1f \n",a.center.x,a.center.y,Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.center)); - System.out.printf("TL: (%3.1f, %3.1f) D: %3.1f \n",a.topLeft.x,a.topLeft.y,Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.topLeft)); - System.out.printf("TR: (%3.1f, %3.1f) D: %3.1f \n",a.topRight.x,a.topRight.y,Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.topRight)); - System.out.printf("BL: (%3.1f, %3.1f) D: %3.1f \n",a.bottomLeft.x,a.bottomLeft.y,Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.bottomLeft)); - System.out.printf("BR: (%3.1f, %3.1f) D: %3.1f \n",a.bottomRight.x,a.bottomRight.y,Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.bottomRight)); + System.out.printf("C : (%3.1f, %3.1f) D: %3.1f \n", a.center.x, a.center.y, Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.center)); + System.out.printf("TL: (%3.1f, %3.1f) D: %3.1f \n", a.topLeft.x, a.topLeft.y, Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.topLeft)); + System.out.printf("TR: (%3.1f, %3.1f) D: %3.1f \n", a.topRight.x, a.topRight.y, Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.topRight)); + System.out.printf("BL: (%3.1f, %3.1f) D: %3.1f \n", a.bottomLeft.x, a.bottomLeft.y, Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.bottomLeft)); + System.out.printf("BR: (%3.1f, %3.1f) D: %3.1f \n", a.bottomRight.x, a.bottomRight.y, Vector2f.Vector2fDistance(Vector2f.ZERO_VECTOR, a.bottomRight)); } } diff --git a/src/seventh/math/Pair.java b/src/seventh/math/Pair.java index 2539044..36ed6d7 100644 --- a/src/seventh/math/Pair.java +++ b/src/seventh/math/Pair.java @@ -26,8 +26,8 @@ public class Pair { * @param second */ public Pair(X first, Y second) { - this.first=first; - this.second=second; + this.first = first; + this.second = second; } /** diff --git a/src/seventh/math/Rectangle.java b/src/seventh/math/Rectangle.java index 249529b..4f112fe 100644 --- a/src/seventh/math/Rectangle.java +++ b/src/seventh/math/Rectangle.java @@ -68,7 +68,7 @@ public Rectangle(int x, int y, int width, int height) { * @param height */ public Rectangle(int width, int height) { - this(0,0,width, height); + this(0, 0, width, height); } /** @@ -81,7 +81,7 @@ public Rectangle(Rectangle rect) { /** */ public Rectangle() { - this(0,0,0,0); + this(0, 0, 0, 0); } /** @@ -284,8 +284,8 @@ public void setSize(Rectangle r) { * @param pos */ public void centerAround(Vector2f pos) { - this.x = (int)pos.x - (this.width/2); - this.y = (int)pos.y - (this.height/2); + this.x = (int)pos.x - (this.width / 2); + this.y = (int)pos.y - (this.height / 2); } /** @@ -294,8 +294,8 @@ public void centerAround(Vector2f pos) { * @param y */ public void centerAround(int x, int y) { - this.x = x - (this.width/2); - this.y = y - (this.height/2); + this.x = x - (this.width / 2); + this.y = y - (this.height / 2); } /** @@ -499,7 +499,7 @@ public static void RectangleIntersection(Rectangle a, Rectangle b, Rectangle des if (ty2 < Integer.MIN_VALUE) ty2 = Integer.MIN_VALUE; - dest.set(tx1, ty1, (int) tx2, (int) ty2); + dest.set(tx1, ty1, (int)tx2, (int)ty2); } /** diff --git a/src/seventh/math/Tri.java b/src/seventh/math/Tri.java index 6858c24..f158f0c 100644 --- a/src/seventh/math/Tri.java +++ b/src/seventh/math/Tri.java @@ -6,64 +6,24 @@ /** * @author Tony - * + * */ -public class Tri { +public class Tri extends Pair { /** - * Get the first item - */ - private X first; - - /** - * Get the second item - */ - private Y second; - - /** - * Get the third item + * Thrid Var */ private Z third; - + /** * @param first * @param second - * @param third */ public Tri(X first, Y second, Z third) { - this.first = first; - this.second = second; - this.third = third; - } - - /** - * @param first the first to set - */ - public void setFirst(X first) { - this.first = first; - } - - /** - * @return the first - */ - public X getFirst() { - return first; - } - - /** - * @param second the second to set - */ - public void setSecond(Y second) { - this.second = second; + super(first, second); + this.third = third; } - /** - * @return the second - */ - public Y getSecond() { - return second; - } - /** * @param third the third to set */ diff --git a/src/seventh/math/Triangle.java b/src/seventh/math/Triangle.java index 8dc06cb..3ce1adc 100644 --- a/src/seventh/math/Triangle.java +++ b/src/seventh/math/Triangle.java @@ -219,33 +219,33 @@ public static boolean rectangleIntersectsTriangle(Rectangle rectangle, float x0, int b0 = 0; - if ( x0 > l ) b0=1; - if ( y0 > t ) b0 |= (b0<<1); - if ( x0 > r ) b0 |= (b0<<2); - if ( y0 > b ) b0 |= (b0<<3); + if ( x0 > l ) b0 = 1; + if ( y0 > t ) b0 |= (b0 << 1); + if ( x0 > r ) b0 |= (b0 << 2); + if ( y0 > b ) b0 |= (b0 << 3); if ( b0 == 3 ) return true; int b1 = 0; - if ( x1 > l ) b1=1; - if ( y1 > t ) b1 |= (b1<<1); - if ( x1 > r ) b1 |= (b1<<2); - if ( y1 > b ) b1 |= (b1<<3); + if ( x1 > l ) b1 = 1; + if ( y1 > t ) b1 |= (b1 << 1); + if ( x1 > r ) b1 |= (b1 << 2); + if ( y1 > b ) b1 |= (b1 << 3); if ( b1 == 3 ) return true; int b2 = 0; - if ( x2 > l ) b2=1; - if ( y2 > t ) b2 |= (b2<<1); - if ( x2 > r ) b2 |= (b2<<2); - if ( y2 > b ) b2 |= (b2<<3); + if ( x2 > l ) b2 = 1; + if ( y2 > t ) b2 |= (b2 << 1); + if ( x2 > r ) b2 |= (b2 << 2); + if ( y2 > b ) b2 |= (b2 << 3); if ( b2 == 3 ) return true; int i0 = b0 ^ b1; if (i0 != 0) { - float m = (y1-y0) / (x1-x0); + float m = (y1 - y0) / (x1 - x0); float c = y0 -(m * x0); if ( (i0 & 1) > 0 ) { float s = m * l + c; if ( s > t && s < b) return true; } if ( (i0 & 2) > 0 ) { float s = (t - c) / m; if ( s > l && s < r) return true; } @@ -256,7 +256,7 @@ public static boolean rectangleIntersectsTriangle(Rectangle rectangle, float x0, int i1 = b1 ^ b2; if (i1 != 0) { - float m = (y2-y1) / (x2-x1); + float m = (y2 - y1) / (x2 - x1); float c = y1 -(m * x1); if ( (i1 & 1) > 0 ) { float s = m * l + c; if ( s > t && s < b) return true; } if ( (i1 & 2) > 0 ) { float s = (t - c) / m; if ( s > l && s < r) return true; } @@ -267,8 +267,8 @@ public static boolean rectangleIntersectsTriangle(Rectangle rectangle, float x0, int i2 = b0 ^ b2; if (i2 != 0) { - float m = (y2-y0) / (x2-x0); - float c = y0 -(m * x0); + float m = (y2 - y0) / (x2 - x0); + float c = y0 - (m * x0); if ( (i2 & 1) > 0 ) { float s = m * l + c; if ( s > t && s < b) return true; } if ( (i2 & 2) > 0 ) { float s = (t - c) / m; if ( s > l && s < r) return true; } if ( (i2 & 4) > 0 ) { float s = m * r + c; if ( s > t && s < b) return true; } diff --git a/src/seventh/math/Vector2f.java b/src/seventh/math/Vector2f.java index 09b8c5e..105f8f7 100644 --- a/src/seventh/math/Vector2f.java +++ b/src/seventh/math/Vector2f.java @@ -19,7 +19,7 @@ /** * The zero vector */ - public static final Vector2f ZERO_VECTOR = new Vector2f(0,0); + public static final Vector2f ZERO_VECTOR = new Vector2f(0, 0); /** * The Right vector @@ -29,7 +29,7 @@ /** * X and Y components. */ - public float x,y; + public float x, y; /** * Constructs a new Vector2f @@ -71,7 +71,7 @@ public Vector2f(Vector2f v) { * @return */ public float get(int i) { - return (i==0) ? this.x : this.y; + return (i == 0) ? this.x : this.y; } /** @@ -115,7 +115,7 @@ public void zeroOut() { * @return */ public boolean isZero() { - return this.x==0 && this.y==0; + return this.x == 0 && this.y == 0; } /** @@ -195,7 +195,7 @@ public Vector2f div(float scalar) { */ public void normalize() { float flLen = (float)Math.sqrt( (this.x * this.x + this.y * this.y) ); - if ( flLen==0 ) return; + if ( flLen == 0 ) return; flLen = 1.0f / flLen; this.x = this.x * flLen; @@ -250,7 +250,7 @@ public Vector2f rotate(double radians) { public boolean equals(Object o) { if ( o instanceof Vector2f ) { Vector2f v = (Vector2f)o; - return v.x==this.x&&this.y==v.y; + return v.x == this.x && this.y == v.y; } return false; } @@ -572,7 +572,7 @@ public float[] toArray() { */ public static /*strictfp*/ void Vector2fNormalize(Vector2f a, Vector2f dest) { float fLen = (float)Math.sqrt( (a.x * a.x + a.y * a.y) ); - if ( fLen==0 ) return; + if ( fLen == 0 ) return; //fLen = 1.0f / fLen; dest.x = a.x / fLen; @@ -686,13 +686,13 @@ public float[] toArray() { public static /*strictfp*/ void Vector2fWholeNumber(Vector2f a, Vector2f dest) { int t = (int)a.x; float delta = a.x - (float)t; - if ( ! FloatUtil.eq(delta, 0) ) { + if ( !FloatUtil.eq(delta, 0) ) { dest.x = (a.x < 0) ? t - 1 : t + 1; } t = (int)a.y; delta = a.y - (float)t; - if ( ! FloatUtil.eq(delta, 0) ) { + if ( !FloatUtil.eq(delta, 0) ) { dest.y = (a.y < 0 ) ? t - 1 : t + 1; } diff --git a/src/seventh/math/Vector3f.java b/src/seventh/math/Vector3f.java index 15771e6..a0c6b3d 100644 --- a/src/seventh/math/Vector3f.java +++ b/src/seventh/math/Vector3f.java @@ -41,13 +41,13 @@ public Vector3f(float x, float y, float z) { * @param v */ public Vector3f(Vector3f v) { - this(v.x,v.y,v.z); + this(v.x, v.y, v.z); } /** */ public Vector3f() { - this(0,0,0); + this(0, 0, 0); } /** diff --git a/src/seventh/network/messages/BombExplodedMessage.java b/src/seventh/network/messages/BombExplodedMessage.java index 7e0e25e..99a55e3 100644 --- a/src/seventh/network/messages/BombExplodedMessage.java +++ b/src/seventh/network/messages/BombExplodedMessage.java @@ -3,9 +3,6 @@ */ package seventh.network.messages; - - - /** * @author Tony * diff --git a/src/seventh/network/messages/BufferIO.java b/src/seventh/network/messages/BufferIO.java index 269de5d..310e93d 100644 --- a/src/seventh/network/messages/BufferIO.java +++ b/src/seventh/network/messages/BufferIO.java @@ -246,7 +246,7 @@ public static byte readTeamId(IOBuffer buffer) { } public static void writeAngle(IOBuffer buffer, int degrees) { - int bangle = ( degrees * 256) / 360; + int bangle = (degrees * 256) / 360; buffer.putUnsignedByte(bangle); } @@ -290,7 +290,7 @@ public static void writeString(IOBuffer buffer, String str) { byte[] chars = str.getBytes(); int len = chars.length; buffer.putUnsignedByte(len); - for(byte i = 0; i < len; i++) { + for(int i = 0; i < len; i++) { buffer.putByte(chars[i]); } } @@ -298,7 +298,7 @@ public static void writeString(IOBuffer buffer, String str) { public static String readString(IOBuffer buffer) { int len = buffer.getUnsignedByte(); byte[] chars = new byte[len]; - for(byte i = 0; i < len; i++) { + for(int i = 0; i < len; i++) { chars[i] = buffer.getByte(); } @@ -309,8 +309,8 @@ public static void writeBigString(IOBuffer buffer, String str) { byte[] chars = str.getBytes(); int len = chars.length; - buffer.putShort( (short)len); - for(byte i = 0; i < len; i++) { + buffer.putShort((short)len); + for(int i = 0; i < len; i++) { buffer.putByte(chars[i]); } } @@ -318,7 +318,7 @@ public static void writeBigString(IOBuffer buffer, String str) { public static String readBigString(IOBuffer buffer) { int len = buffer.getShort(); byte[] chars = new byte[len]; - for(byte i = 0; i < len; i++) { + for(int i = 0; i < len; i++) { chars[i] = buffer.getByte(); } diff --git a/src/seventh/server/GameServer.java b/src/seventh/server/GameServer.java index 1b915c2..37c899c 100644 --- a/src/seventh/server/GameServer.java +++ b/src/seventh/server/GameServer.java @@ -202,7 +202,21 @@ private void init(final ServerSeventhConfig config, /* if this is a dedicated server, we'll contact the * master server so that users know about this server */ - contactDedicatedServer(settings.isDedicatedServer,settings.isLAN); + this.console.print("Initializing MasterServerRegistration..."); + this.registration = new MasterServerRegistration(this.serverContext); + if(settings.isDedicatedServer) { + this.registration.start(); + this.console.println("done!"); + } + else this.console.println(""); + + this.console.print("Initializing LANServerRegistration..."); + this.lanRegistration = new LANServerRegistration(this.serverContext); + if(settings.isLAN) { + this.lanRegistration.start(); + this.console.println("done!"); + } + else this.console.println(""); /* attempt to attach a debugger */ if(config.isDebuggerEnabled()) { @@ -280,28 +294,6 @@ public void onExitState(State state) { console.println("Done initialzing the game server, ready to launch network..."); } - - - /** - * @param settings - */ - private void contactDedicatedServer(boolean isDedicatedServer,boolean isLAN) { - this.console.print("Initializing MasterServerRegistration..."); - this.registration = new MasterServerRegistration(this.serverContext); - if(isDedicatedServer) { - this.registration.start(); - this.console.println("done!"); - } - else this.console.println(""); - - this.console.print("Initializing LANServerRegistration..."); - this.lanRegistration = new LANServerRegistration(this.serverContext); - if(isLAN) { - this.lanRegistration.start(); - this.console.println("done!"); - } - else this.console.println(""); - } /** @@ -310,7 +302,7 @@ private void contactDedicatedServer(boolean isDedicatedServer,boolean isLAN) { * @param config * @return the {@link DebugableListener} if one is available, or null */ - private DebugableListener createDebugListener(ServerSeventhConfig config) { + private DebugableListener createDebugListener(ServerSeventhConfig config) { try { String className = config.getDebuggerClassName(); if(className != null && !"".equals(className)) { @@ -395,7 +387,7 @@ public void execute(Console console, String... args) { @Override public void execute(Console console, String... args) { ServerSeventhConfig config = serverContext.getConfig(); - if(args==null||args.length < 1) { + if(args == null || args.length < 1) { console.println("sv_privatePassword: " + config.getPrivatePassword()); } else { @@ -404,12 +396,12 @@ public void execute(Console console, String... args) { } }); - console.addCommand(new Command("add_bot"){ + console.addCommand(new Command("add_bot") { @Override public void execute(Console console, String... args) { Game game = serverContext.getGameSession().getGame(); if(game != null) { - if( args.length < 1) { + if(args.length < 1) { console.println(" add_bot [bot name] [optional team]"); } else { @@ -446,7 +438,7 @@ else if(teamName.startsWith(Team.AXIS_TEAM_NAME.toLowerCase())) { }); - console.addCommand(new Command("add_dummy_bot"){ + console.addCommand(new Command("add_dummy_bot") { @Override public void execute(Console console, String... args) { Game game = serverContext.getGameSession().getGame(); @@ -461,7 +453,7 @@ public void execute(Console console, String... args) { } }); - console.addCommand(new Command("kick"){ + console.addCommand(new Command("kick") { @Override public void execute(Console console, String... args) { Game game = serverContext.getGameSession().getGame(); @@ -480,7 +472,7 @@ public void execute(Console console, String... args) { } }); - console.addCommand(new Command("kill"){ + console.addCommand(new Command("kill") { @Override public void execute(Console console, String... args) { GameInfo game = serverContext.getGameSession().getGame(); @@ -491,7 +483,7 @@ public void execute(Console console, String... args) { default: { int id = Integer.parseInt(args[0]); PlayerInfo player = game.getPlayerById(id); - if(player!=null&&!player.isDead()) { + if(player != null && !player.isDead()) { player.getEntity().kill(player.getEntity()); } } @@ -501,7 +493,7 @@ public void execute(Console console, String... args) { } }); - console.addCommand(new Command("players"){ + console.addCommand(new Command("players") { @Override public void execute(final Console console, String... args) { GameInfo game = serverContext.getGameSession().getGame(); @@ -522,7 +514,7 @@ public void onPlayerInfo(PlayerInfo p) { } }); - console.addCommand(new Command("stats"){ + console.addCommand(new Command("stats") { @Override public void execute(final Console console, String... args) { Game game = serverContext.getGameSession().getGame(); @@ -564,7 +556,7 @@ public void onPlayerInfo(PlayerInfo p) { } }); - console.addCommand(new Command("sv_exit"){ + console.addCommand(new Command("sv_exit") { @Override public void execute(Console console, String... args) { console.println("Shutting down the system..."); @@ -579,7 +571,7 @@ public void execute(Console console, String... args) { console.addCommand("quit", console.getCommand("sv_exit")); } - console.addCommand(new Command("get"){ + console.addCommand(new Command("get") { @Override public void execute(Console console, String... args) { switch(args.length) { @@ -592,7 +584,7 @@ public void execute(Console console, String... args) { } }); - console.addCommand(new Command("set"){ + console.addCommand(new Command("set") { @Override public void execute(Console console, String... args) { switch(args.length) { @@ -608,7 +600,7 @@ public void execute(Console console, String... args) { } }); - console.addCommand(new Command("seti"){ + console.addCommand(new Command("seti") { @Override public void execute(Console console, String... args) { switch(args.length) { @@ -784,7 +776,7 @@ public void start(int port) throws Exception { final int maxIterations = 5; final long maxDelta = 250; final long frameRate = Math.abs(serverContext.getConfig().getServerFrameRate()); - final long dt = 1000 / frameRate==0 ? 20 : frameRate; + final long dt = 1000 / frameRate == 0 ? 20 : frameRate; final TimeStep timeStep = new TimeStep(); timeStep.setDeltaTime(dt); diff --git a/src/seventh/server/InGameState.java b/src/seventh/server/InGameState.java index 28db79b..4e89ee5 100644 --- a/src/seventh/server/InGameState.java +++ b/src/seventh/server/InGameState.java @@ -138,7 +138,7 @@ public InGameState(final ServerContext serverContext, this.netPartialStatDelay = config.getServerNetPartialStatDelay(); final long netRate = Math.abs(config.getServerNetUpdateRate()); - this.netUpdateRate = 1000 / netRate==0 ? 20 : netRate; + this.netUpdateRate = 1000 / netRate == 0 ? 20 : netRate; this.nextGameStatUpdate = 2_000; // first big update, wait only 2 seconds this.nextGamePartialStatUpdate = this.netPartialStatDelay; @@ -218,7 +218,7 @@ public void onRoundEnded(RoundEndedEvent event) { msg.stats = game.getNetGameStats();//event.getStats(); Team winner = event.getWinner(); - if(winner!=null) { + if(winner != null) { msg.winnerTeamId = winner.getId(); } @@ -371,7 +371,7 @@ public void enter() { @Override public void execute(Console console, String... args) { - if(args.length>0) { + if(args.length > 0) { int enabled = Integer.parseInt(args[0]); game.enableFOW(enabled != 0); } @@ -432,7 +432,7 @@ public void update(TimeStep timeStep) { // check for game end if(gameEnded) { - if(gameEndTime>GAME_END_DELAY) { + if(gameEndTime > GAME_END_DELAY) { /* load up the next level */ serverContext.spawnGameSession(); } diff --git a/src/seventh/server/ServerNetworkProtocol.java b/src/seventh/server/ServerNetworkProtocol.java index ed11d13..acc7cf9 100644 --- a/src/seventh/server/ServerNetworkProtocol.java +++ b/src/seventh/server/ServerNetworkProtocol.java @@ -467,7 +467,9 @@ else if(cmd.startsWith("password")) { Logger logger = this.rconLoggers.put(client.getId(), new RconLogger(client.getId(), this)); console.removeLogger(logger); - console.addLogger(this.rconLoggers.get(client.getId())); + if(!serverContext.getGameServer().isLocal()) { + console.addLogger(this.rconLoggers.get(client.getId())); + } } else { client.setRconAuthenticated(false); diff --git a/src/seventh/server/SeventhScriptingCommonLibrary.java b/src/seventh/server/SeventhScriptingCommonLibrary.java index ad03cfe..18e5333 100644 --- a/src/seventh/server/SeventhScriptingCommonLibrary.java +++ b/src/seventh/server/SeventhScriptingCommonLibrary.java @@ -34,10 +34,10 @@ public class SeventhScriptingCommonLibrary { * @return the {@link Vector2f} */ public static Vector2f newVec2(Double x, Double y) { - if(x!=null&&y!=null) - return new Vector2f(x.floatValue(),y.floatValue()); - if(x!=null) - return new Vector2f(x.floatValue(),0.0f); + if(x != null && y != null) + return new Vector2f(x.floatValue(), y.floatValue()); + if(x != null) + return new Vector2f(x.floatValue(), 0.0f); return new Vector2f(); } @@ -189,7 +189,7 @@ public boolean checkCondition(Game game) { @Override public void execute(Game game) { - if(triggeredEntity!=null) { + if(triggeredEntity != null) { game.newBigExplosion(new Vector2f(tile.getX(),tile.getY()), triggeredEntity, 15, 25, 1); } diff --git a/src/seventh/shared/Arrays.java b/src/seventh/shared/Arrays.java index bbd55d1..4dc8d35 100644 --- a/src/seventh/shared/Arrays.java +++ b/src/seventh/shared/Arrays.java @@ -19,7 +19,7 @@ public class Arrays { * * @param newSortStrategy */ - public void setStrategy(SortStrategy newSortStrategy) { + public void setSortStrategy(SortStrategy newSortStrategy) { this.sortStrategy = newSortStrategy; } diff --git a/src/seventh/ui/Button.java b/src/seventh/ui/Button.java index b161bdb..5d10217 100644 --- a/src/seventh/ui/Button.java +++ b/src/seventh/ui/Button.java @@ -88,8 +88,8 @@ public Button(EventDispatcher eventDispatcher) { @Override public boolean mouseMoved(int x, int y) { super.mouseMoved(x, y); - if ( ! isDisabled() ) { - if ( getScreenBounds().contains(x,y)) { + if ( !isDisabled() ) { + if ( getScreenBounds().contains(x, y) ) { setHovering(true); return false; } @@ -100,8 +100,8 @@ public boolean mouseMoved(int x, int y) { @Override public boolean touchDown(int x, int y, int pointer, int button) { - if ( ! isDisabled() ) { - if ( getScreenBounds().contains(x,y)) { + if ( !isDisabled() ) { + if ( getScreenBounds().contains(x, y) ) { setPressed(true); click(); return true; @@ -118,8 +118,8 @@ public boolean touchDown(int x, int y, int pointer, int button) { @Override public boolean touchUp(int x, int y, int pointer, int button) { setPressed(false); - if ( ! isDisabled() ) { - if ( getScreenBounds().contains(x,y)) { + if ( !isDisabled() ) { + if ( getScreenBounds().contains(x, y) ) { return true; } } @@ -183,7 +183,7 @@ public void setBounds(Rectangle bounds) { @Override public void setTheme(Theme theme) { super.setTheme(theme); - if(theme!=null) { + if(theme != null) { label.setFont(theme.getPrimaryFontName()); } } @@ -252,7 +252,7 @@ public void setHovering(boolean isHovering) { if(isHovering) { this.label.setTextSize(this.hoverTextSize); Theme theme = getTheme(); - if(theme!=null) { + if(theme != null) { this.label.setForegroundColor(theme.getHoverColor()); } @@ -264,7 +264,7 @@ public void setHovering(boolean isHovering) { else { this.label.setTextSize(this.normalTextSize); Theme theme = getTheme(); - if(theme!=null) { + if(theme != null) { this.label.setForegroundColor(theme.getForegroundColor()); } } diff --git a/src/seventh/ui/Checkbox.java b/src/seventh/ui/Checkbox.java index ebc7828..2499ea9 100644 --- a/src/seventh/ui/Checkbox.java +++ b/src/seventh/ui/Checkbox.java @@ -41,8 +41,8 @@ public Checkbox(boolean isChecked, EventDispatcher eventDispatcher) { @Override public boolean mouseMoved(int x, int y) { super.mouseMoved(x, y); - if ( ! isDisabled() ) { - if ( getScreenBounds().contains(x,y)) { + if ( !isDisabled() ) { + if ( getScreenBounds().contains(x, y)) { setHovering(true); return false; } @@ -55,7 +55,7 @@ public boolean mouseMoved(int x, int y) { @Override public boolean touchUp(int x, int y, int pointer, int button) { if(getScreenBounds().contains(x, y)) { - setChecked(! isChecked() ); + setChecked(!isChecked() ); return true; } diff --git a/src/seventh/ui/DefaultStyling.java b/src/seventh/ui/DefaultStyling.java index 0a711e7..cb94fe9 100644 --- a/src/seventh/ui/DefaultStyling.java +++ b/src/seventh/ui/DefaultStyling.java @@ -58,7 +58,7 @@ public void styleDialog(Dialog dialog) { dialog.setForegroundColor(WHITE); for( Widget widget: dialog.getWidgets()) { - if ( widget instanceof Button) { + if ( widget instanceof Button ) { styleButton((Button)widget); } } diff --git a/src/seventh/ui/LevelButton.java b/src/seventh/ui/LevelButton.java index bf38be1..40f3c65 100644 --- a/src/seventh/ui/LevelButton.java +++ b/src/seventh/ui/LevelButton.java @@ -139,6 +139,4 @@ public void setLevelName(String levelName) { this.levelName = levelName; } - - } diff --git a/src/seventh/ui/ListBox.java b/src/seventh/ui/ListBox.java index bd9b315..9d4642b 100644 --- a/src/seventh/ui/ListBox.java +++ b/src/seventh/ui/ListBox.java @@ -152,7 +152,7 @@ public ListBox addColumnHeader(String header, int width) { addWidget(button); - if(this.headerListener!=null) { + if(this.headerListener != null) { this.headerListener.onHeaderAdded(button); } @@ -176,7 +176,7 @@ public ListBox addItem(Button button) { this.items.add(button); addWidget(button); - if(this.itemListener!=null) { + if(this.itemListener != null) { this.itemListener.onItemAdded(button); } return this; diff --git a/src/seventh/ui/MessageBoard.java b/src/seventh/ui/MessageBoard.java index 3a31e23..9098c51 100644 --- a/src/seventh/ui/MessageBoard.java +++ b/src/seventh/ui/MessageBoard.java @@ -118,7 +118,7 @@ public MessageBoard(int messageBoardSize) { * @param timeStep */ public void update(TimeStep timeStep) { - if ( ! this.messages.isEmpty() ) { + if ( !this.messages.isEmpty() ) { // determine if the message has expired. Message msg = this.messages.peek(); diff --git a/src/seventh/ui/Slider.java b/src/seventh/ui/Slider.java index 9bce467..ef03550 100644 --- a/src/seventh/ui/Slider.java +++ b/src/seventh/ui/Slider.java @@ -73,7 +73,7 @@ public boolean touchDown(int x, int y, int pointer, int button) { sliderHitbox.height *= 4; sliderHitbox.y -= (getScreenBounds().height * 2); - if(sliderHitbox.contains(x,y)) { + if(sliderHitbox.contains(x, y)) { moveHandleTo(x); return true; } @@ -84,8 +84,8 @@ public boolean touchDown(int x, int y, int pointer, int button) { @Override public boolean mouseMoved(int x, int y) { super.mouseMoved(x, y); - if ( ! isDisabled() ) { - if ( getScreenBounds().contains(x,y)) { + if ( !isDisabled() ) { + if ( getScreenBounds().contains(x, y) ) { setHovering(true); return false; } @@ -189,7 +189,7 @@ else if(index < 0) { // int width = getBounds().width - handle.getBounds().width; float percentage = (float)index / (float)MAX_INDEX; float x = getBounds().width * percentage; - moveHandleTo( getBounds().x + (int)x); + moveHandleTo( getBounds().x + (int)x ); } } diff --git a/src/seventh/ui/TextBox.java b/src/seventh/ui/TextBox.java index 2936add..e222f05 100644 --- a/src/seventh/ui/TextBox.java +++ b/src/seventh/ui/TextBox.java @@ -66,8 +66,8 @@ public TextBox(EventDispatcher eventDispatcher) { @Override public boolean mouseMoved(int x, int y) { super.mouseMoved(x, y); - if ( ! isDisabled() ) { - if ( getScreenBounds().contains(x,y)) { + if ( !isDisabled() ) { + if ( getScreenBounds().contains(x, y) ) { if(!hasFocus()) { setHovering(true); } @@ -80,8 +80,8 @@ public boolean mouseMoved(int x, int y) { @Override public boolean touchDown(int x, int y, int pointer, int button) { - if ( ! isDisabled() ) { - if ( getScreenBounds().contains(x,y)) { + if ( !isDisabled() ) { + if ( getScreenBounds().contains(x, y) ) { setFocus(true); return false; } @@ -100,7 +100,7 @@ public boolean touchUp(int x, int y, int pointer, int button) { } public boolean keyDown(int key) { - if(isDisabled()|| !hasFocus()) { + if(isDisabled() || !hasFocus()) { return false; } @@ -150,7 +150,7 @@ public boolean keyDown(int key) { @Override public boolean keyUp(int key) { - if(isDisabled()|| !hasFocus()) { + if(isDisabled() || !hasFocus()) { return false; } @@ -173,7 +173,7 @@ public boolean keyTyped(char key) { switch(key) { case /*Keys.BACKSPACE*/8: { - if(cursorIndex>0) { + if(cursorIndex > 0) { inputBuffer.deleteCharAt(--cursorIndex); if(cursorIndex < 0) { cursorIndex = 0; @@ -195,8 +195,8 @@ public boolean keyTyped(char key) { break; } default: { - char c =key; - if(c>31&&c<127 && c != 96 && inputBuffer.length() < maxSize) { + char c = key; + if(c > 31 && c < 127 && c != 96 && inputBuffer.length() < maxSize) { inputBuffer.insert(cursorIndex, key); cursorIndex++; Sounds.playGlobalSound(Sounds.uiKeyType); diff --git a/src/seventh/ui/UserInterfaceManager.java b/src/seventh/ui/UserInterfaceManager.java index 173ef42..5b14115 100644 --- a/src/seventh/ui/UserInterfaceManager.java +++ b/src/seventh/ui/UserInterfaceManager.java @@ -147,7 +147,7 @@ public boolean keyUp(int key) { */ @Override public boolean mouseMoved(int x, int y) { - cursor.moveTo(x,y); + cursor.moveTo(x, y); return Widget.globalInputListener.mouseMoved(cursor.getX(), cursor.getY()); } @@ -188,7 +188,7 @@ public boolean scrolled(int amount) { */ @Override public boolean touchDragged(int x, int y, int pointer) { - cursor.moveTo(x,y); + cursor.moveTo(x, y); return Widget.globalInputListener.touchDragged(cursor.getX(), cursor.getY(), pointer); } diff --git a/src/seventh/ui/Widget.java b/src/seventh/ui/Widget.java index a1482c9..fe5ee3e 100644 --- a/src/seventh/ui/Widget.java +++ b/src/seventh/ui/Widget.java @@ -183,7 +183,7 @@ public Widget(EventDispatcher eventDispatcher) { } public void setTheme(Theme theme) { - if(theme!=null) { + if(theme != null) { setForegroundColor(theme.getForegroundColor()); setBackgroundColor(theme.getBackgroundColor()); this.theme = theme; @@ -730,7 +730,7 @@ public void removeWidget(Widget w) { // don't remove from this list if // we are destroying all Widgets - avoids // concurrent modification exception - if ( ! this.isDestroying ) { + if ( !this.isDestroying ) { this.globalWidgets.remove(w); } } @@ -744,7 +744,7 @@ public boolean keyTyped(char key) { int size = globalWidgets.size(); for(int i = 0; i < size; i++) { Widget widget = this.globalWidgets.get(i); - if ( widget.hasFocus() && ! widget.isDisabled() ) { + if ( widget.hasFocus() && !widget.isDisabled() ) { if ( widget.fireKeyTypedEvent(key) ) { return true; } @@ -762,7 +762,7 @@ public boolean keyDown(int event) { int size = globalWidgets.size(); for(int i = 0; i < size; i++) { Widget widget = this.globalWidgets.get(i); - if ( widget.hasFocus() && ! widget.isDisabled() ) { + if ( widget.hasFocus() && !widget.isDisabled() ) { if ( widget.fireKeyEvent(event, true) ) { return true; } @@ -779,7 +779,7 @@ public boolean keyUp(int event) { int size = globalWidgets.size(); for(int i = 0; i < size; i++) { Widget widget = this.globalWidgets.get(i); - if ( widget.hasFocus() && ! widget.isDisabled() ) { + if ( widget.hasFocus() && !widget.isDisabled() ) { if ( widget.fireKeyEvent(event, false) ) { return true; } @@ -796,7 +796,7 @@ public boolean touchDown(int x, int y, int pointer, int button) { int size = globalWidgets.size(); for(int i = 0; i < size; i++) { Widget widget = this.globalWidgets.get(i); - if ( /*widget.hasFocus() &&*/ ! widget.isDisabled() ) { + if ( /*widget.hasFocus() &&*/ !widget.isDisabled() ) { if ( widget.fireMouseEvent(x, y, pointer, button, true) ) { return true; } @@ -812,7 +812,7 @@ public boolean touchUp(int x, int y, int pointer, int button) { int size = globalWidgets.size(); for(int i = 0; i < size; i++) { Widget widget = this.globalWidgets.get(i); - if ( /*widget.hasFocus() &&*/ ! widget.isDisabled() ) { + if ( /*widget.hasFocus() &&*/ !widget.isDisabled() ) { if ( widget.fireMouseEvent(x, y, pointer, button, false) ) { return true; } @@ -846,8 +846,8 @@ public boolean mouseMoved(int x, int y) { int size = globalWidgets.size(); for(int i = 0; i < size; i++) { Widget widget = this.globalWidgets.get(i); - if ( /*widget.hasFocus() &&*/ ! widget.isDisabled() ) { - if ( widget.fireMouseMotionEvent(x,y) ) { + if ( /*widget.hasFocus() &&*/ !widget.isDisabled() ) { + if ( widget.fireMouseMotionEvent(x, y) ) { return true; } } @@ -863,7 +863,7 @@ public boolean scrolled(int amount) { int size = globalWidgets.size(); for(int i = 0; i < size; i++) { Widget widget = this.globalWidgets.get(i); - if ( /*widget.hasFocus() &&*/ ! widget.isDisabled() ) { + if ( /*widget.hasFocus() &&*/ !widget.isDisabled() ) { if ( widget.fireMouseScrolledEvent(amount) ) { return true; } diff --git a/src/seventh/ui/view/ButtonView.java b/src/seventh/ui/view/ButtonView.java index 3738b94..60d9c25 100644 --- a/src/seventh/ui/view/ButtonView.java +++ b/src/seventh/ui/view/ButtonView.java @@ -67,7 +67,7 @@ public ButtonView(Button button) { this.labelView = new LabelView(this.button.getTextLabel()) { @Override protected void setColor(Canvas renderer, Label label) { - renderer.setColor(Color.argb8888(currentColor), (int) (currentColor.a * 255) ); + renderer.setColor(Color.argb8888(currentColor), (int)(currentColor.a * 255) ); //super.setColor(renderer, label); } }; @@ -115,7 +115,7 @@ public void update(TimeStep timeStep) { if(button.isHovering()) { Theme theme = button.getTheme(); Color.argb8888ToColor(this.srcColor, button.getForegroundColor()); - Color.argb8888ToColor(this.dstColor, (theme!=null) ? theme.getHoverColor() : button.getForegroundColor()); + Color.argb8888ToColor(this.dstColor, (theme != null) ? theme.getHoverColor() : button.getForegroundColor()); time += timeStep.asFraction() * 0.79; float t = (float)Math.cos(time); diff --git a/src/seventh/ui/view/ImageButtonView.java b/src/seventh/ui/view/ImageButtonView.java index c1926ad..e09ee85 100644 --- a/src/seventh/ui/view/ImageButtonView.java +++ b/src/seventh/ui/view/ImageButtonView.java @@ -171,8 +171,8 @@ public void render(Canvas renderer, Camera camera, float alpha) { int uw = this.buttonUpImage.getRegionWidth(); int uh = this.buttonUpImage.getRegionHeight(); - int w = uw / 2 - this.buttonImage.getRegionWidth()/2; - int h = uh / 2 - this.buttonImage.getRegionHeight()/2 + 5; + int w = uw / 2 - this.buttonImage.getRegionWidth() / 2; + int h = uh / 2 - this.buttonImage.getRegionHeight() / 2 + 5; if ( button.isPressed() ) { if ( this.buttonDownImage != null) { @@ -200,7 +200,7 @@ public void render(Canvas renderer, Camera camera, float alpha) { } else { if(makeBig) { - renderer.drawScaledImage(this.buttonUpImage, (int)position.x, (int)position.y, r.width+5, r.height+5, color); + renderer.drawScaledImage(this.buttonUpImage, (int)position.x, (int)position.y, r.width + 5, r.height + 5, color); } else { renderer.drawScaledImage(this.buttonUpImage, (int)position.x, (int)position.y, r.width, r.height, color); diff --git a/src/seventh/ui/view/ImagePanelView.java b/src/seventh/ui/view/ImagePanelView.java index 00ec2e9..1f0a6ae 100644 --- a/src/seventh/ui/view/ImagePanelView.java +++ b/src/seventh/ui/view/ImagePanelView.java @@ -55,7 +55,7 @@ public void render(Canvas renderer, Camera camera, float alpha) { renderer.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, panel.getForegroundColor()); TextureRegion tex = panel.getImage(); - if(tex!=null) { + if(tex != null) { renderer.drawScaledImage(tex, bounds.x, bounds.y, bounds.width, bounds.height, null); } super.render(renderer, camera, alpha); diff --git a/src/seventh/ui/view/LabelView.java b/src/seventh/ui/view/LabelView.java index 3f33f64..137d866 100644 --- a/src/seventh/ui/view/LabelView.java +++ b/src/seventh/ui/view/LabelView.java @@ -82,7 +82,7 @@ public void render(Canvas renderer, Camera camera, float alpha) { int width = renderer.getWidth(buttonTxt); int height = renderer.getHeight("W"); - int vertical = bounds.y + (bounds.height/2); + int vertical = bounds.y + (bounds.height / 2); switch(this.label.getVerticalTextAlignment()) { case BOTTOM: vertical = bounds.y + (bounds.height - 5); @@ -91,7 +91,7 @@ public void render(Canvas renderer, Camera camera, float alpha) { vertical = bounds.y + height; break; default: - vertical = bounds.y + (bounds.height/2); + vertical = bounds.y + (bounds.height / 2); } switch(this.label.getHorizontalTextAlignment()) { @@ -113,7 +113,7 @@ public void render(Canvas renderer, Camera camera, float alpha) { RenderFont.drawShadedString(renderer // renderer.drawString( , buttonTxt - , bounds.x + (bounds.width/2) - (width/2) + , bounds.x + (bounds.width / 2) - (width / 2) , vertical, null, label.isShadowed() ); break; } diff --git a/src/seventh/ui/view/ListBoxView.java b/src/seventh/ui/view/ListBoxView.java index df7bcc8..a8ab28b 100644 --- a/src/seventh/ui/view/ListBoxView.java +++ b/src/seventh/ui/view/ListBoxView.java @@ -63,7 +63,7 @@ public void onItemRemove(Button button) { int removeIndex = -1; int i = 0; for(ButtonView view : buttonViews) { - if(view.getButton()==button) { + if(view.getButton() == button) { removeIndex = i; break; } @@ -119,15 +119,15 @@ public void render(Canvas renderer, Camera camera, float alpha) { Rectangle bounds = box.getBounds(); - renderer.fillRect(bounds.x-1, bounds.y, bounds.width, bounds.height+1, box.getBackgroundColor()); - renderer.drawRect(bounds.x-1, bounds.y, bounds.width+1, bounds.height+1, 0xff000000); + renderer.fillRect(bounds.x - 1, bounds.y, bounds.width, bounds.height + 1, box.getBackgroundColor()); + renderer.drawRect(bounds.x - 1, bounds.y, bounds.width + 1, bounds.height + 1, 0xff000000); bounds = box.getScreenBounds(); int y = 40; - renderer.fillRect(bounds.x-1, bounds.y, bounds.width+1, 31, 0xff282c0c); - renderer.drawRect(bounds.x-1, bounds.y, bounds.width+1, 30+1, 0xff000000); + renderer.fillRect(bounds.x - 1, bounds.y, bounds.width + 1, 31, 0xff282c0c); + renderer.drawRect(bounds.x - 1, bounds.y, bounds.width + 1, 30 + 1, 0xff000000); int hsize = hderButtonViews.size(); for(int i = 0; i < hsize; i++) { @@ -142,10 +142,9 @@ public void render(Canvas renderer, Camera camera, float alpha) { btn.getBounds().y = y; Rectangle rect = btn.getScreenBounds(); //rect.y = y; - if(bounds.contains(rect)) - { + if(bounds.contains(rect)) { if(btn.isHovering()) { - renderer.fillRect(rect.x-10, rect.y-5, rect.width+40, rect.height, 0x0fffffff); + renderer.fillRect(rect.x - 10, rect.y - 5, rect.width + 40, rect.height, 0x0fffffff); } view.render(renderer, camera, alpha); } diff --git a/src/seventh/ui/view/ProgressBarView.java b/src/seventh/ui/view/ProgressBarView.java index e5e9dc1..392bd34 100644 --- a/src/seventh/ui/view/ProgressBarView.java +++ b/src/seventh/ui/view/ProgressBarView.java @@ -47,33 +47,25 @@ public void render(Canvas canvas, Camera camera, float alpha) { canvas.fillRect(bounds.x, bounds.y, percentOfWidth, bounds.height, progressBar.getForegroundColor()); canvas.drawRect(bounds.x, bounds.y, bounds.width, bounds.height, 0xff000000); - addAShadowEffect(canvas, bounds); + int x = bounds.x; + int y = bounds.y; + + // add a shadow effect + canvas.drawLine( x, y + 1, x + bounds.width, y + 1, 0x8f000000 ); + canvas.drawLine( x, y + 2, x + bounds.width, y + 2, 0x5f000000 ); + canvas.drawLine( x, y + 3, x + bounds.width, y + 3, 0x2f000000 ); + canvas.drawLine( x, y + 4, x + bounds.width, y + 4, 0x0f000000 ); + canvas.drawLine( x, y + 5, x + bounds.width, y + 5, 0x0b000000 ); + canvas.drawLine( x, y + 6, x + bounds.width, y + 6, 0x0a000000 ); + + y = y + 15; + canvas.drawLine( x, y - 6, x + bounds.width, y - 6, 0x0a000000 ); + canvas.drawLine( x, y - 5, x + bounds.width, y - 5, 0x0b000000 ); + canvas.drawLine( x, y - 4, x + bounds.width, y - 4, 0x0f000000 ); + canvas.drawLine( x, y - 3, x + bounds.width, y - 3, 0x2f000000 ); + canvas.drawLine( x, y - 2, x + bounds.width, y - 2, 0x5f000000 ); + canvas.drawLine( x, y - 1, x + bounds.width, y - 1, 0x8f000000 ); } } - - /** - * add a shadow effect on canvas with a rectangle bounds - * - * @param canvas - * @param bounds - */ - private static void addAShadowEffect(Canvas canvas, Rectangle bounds) { - int x = bounds.x; - int y = bounds.y; - - canvas.drawLine( x, y+1, x+bounds.width, y+1, 0x8f000000 ); - canvas.drawLine( x, y+2, x+bounds.width, y+2, 0x5f000000 ); - canvas.drawLine( x, y+3, x+bounds.width, y+3, 0x2f000000 ); - canvas.drawLine( x, y+4, x+bounds.width, y+4, 0x0f000000 ); - canvas.drawLine( x, y+5, x+bounds.width, y+5, 0x0b000000 ); - canvas.drawLine( x, y+6, x+bounds.width, y+6, 0x0a000000 ); - - y = y+15; - canvas.drawLine( x, y-6, x+bounds.width, y-6, 0x0a000000 ); - canvas.drawLine( x, y-5, x+bounds.width, y-5, 0x0b000000 ); - canvas.drawLine( x, y-4, x+bounds.width, y-4, 0x0f000000 ); - canvas.drawLine( x, y-3, x+bounds.width, y-3, 0x2f000000 ); - canvas.drawLine( x, y-2, x+bounds.width, y-2, 0x5f000000 ); - canvas.drawLine( x, y-1, x+bounds.width, y-1, 0x8f000000 ); - } + } diff --git a/src/seventh/ui/view/TextBoxView.java b/src/seventh/ui/view/TextBoxView.java index cbfea13..5516446 100644 --- a/src/seventh/ui/view/TextBoxView.java +++ b/src/seventh/ui/view/TextBoxView.java @@ -83,7 +83,7 @@ public void render(Canvas renderer, Camera camera, float alpha) { renderGradiantBackground(textBox, renderer, camera, alpha); if(textBox.hasFocus() || textBox.isHovering()) { - renderer.drawRect(bounds.x-1, bounds.y-1, bounds.width+2, bounds.height+2, //textBox.getForegroundColor()); + renderer.drawRect(bounds.x - 1, bounds.y - 1, bounds.width + 2, bounds.height + 2, //textBox.getForegroundColor()); 0x5ff1f401); // 0xff393939); } @@ -93,11 +93,10 @@ public void render(Canvas renderer, Camera camera, float alpha) { Rectangle lbounds = this.textBox.getTextLabel().getBounds();//update the text lbounds.set(bounds); lbounds.x += xTextOffset; - lbounds.y += (lbounds.height / 2) - textHeight/3; + lbounds.y += (lbounds.height / 2) - textHeight / 3; this.textView.render(renderer, camera, alpha); - if(showCursor && textBox.hasFocus()) - { + if(showCursor && textBox.hasFocus()) { String text = textBox.getText(); int textWidth = renderer.getWidth(text.substring(0, textBox.getCursorIndex())) + 5; renderer.setFont(textBox.getTextLabel().getFont(), (int)textBox.getTextLabel().getTextSize()); diff --git a/src/test/harenet/ByteBufferIOBufferTest.java b/src/test/harenet/ByteBufferIOBufferTest.java index a4335ee..41755d2 100644 --- a/src/test/harenet/ByteBufferIOBufferTest.java +++ b/src/test/harenet/ByteBufferIOBufferTest.java @@ -97,5 +97,30 @@ public void testShort() { int value = writeBuffer.getIntBits(13);// & (short)0b111111111111; assertEquals(8189, value); } + + + @Test + public void testLong() { + IOBuffer writeBuffer = IOBuffer.Factory.allocate(1500); + + long value = 0xf123a4234ac5af21L; + writeBuffer.putLong(value); + writeBuffer.flip(); + long outputValue = writeBuffer.getLong(); + assertEquals(value, outputValue); + } + + @Test + public void testDouble() { + IOBuffer writeBuffer = IOBuffer.Factory.allocate(1500); + + double value = 0xf123a4234ac5af21L; + writeBuffer.putDouble(value); + writeBuffer.flip(); + double outputValue = writeBuffer.getDouble(); + System.out.println("output: " + Double.toHexString(outputValue)); + System.out.println("given: " + Double.toHexString(value)); + assertEquals(value, outputValue, 0.001D); + } } From f701c0b8e18ddcaaebabeccc67d9601888bbe614 Mon Sep 17 00:00:00 2001 From: aikaran Date: Tue, 5 Jun 2018 20:50:20 +0900 Subject: [PATCH 36/47] Factory Method Pattern Target : seventh.shared.Arrays class Reason : Factory Method pattern can create objects with common ancestor --- src/seventh/shared/Arrays.java | 14 +++----------- src/seventh/shared/SortStrategyFactory.java | 11 +++++++++++ 2 files changed, 14 insertions(+), 11 deletions(-) create mode 100644 src/seventh/shared/SortStrategyFactory.java diff --git a/src/seventh/shared/Arrays.java b/src/seventh/shared/Arrays.java index 4dc8d35..644074e 100644 --- a/src/seventh/shared/Arrays.java +++ b/src/seventh/shared/Arrays.java @@ -12,16 +12,6 @@ * */ public class Arrays { - private SortStrategy sortStrategy; - - /** - * Set the strategy. - * - * @param newSortStrategy - */ - public void setSortStrategy(SortStrategy newSortStrategy) { - this.sortStrategy = newSortStrategy; - } /** * Counts the amount of used elements in the array @@ -63,7 +53,9 @@ public static void clear(T[] array) { * @return the supplied array */ public T[] sort(T[] array, Comparator comp) { - sortStrategy.sort(array, comp); + SortStrategyFactory = new SortStrategyFactory(); + SortStrategy sortStrategy = SortStrategyFactory.getSortStrategy(array); + sortStrategy.sort(array, comp); return array; } } diff --git a/src/seventh/shared/SortStrategyFactory.java b/src/seventh/shared/SortStrategyFactory.java new file mode 100644 index 0000000..a895b61 --- /dev/null +++ b/src/seventh/shared/SortStrategyFactory.java @@ -0,0 +1,11 @@ +import java.util.Comparator; + +public class SortStrategyFactory { + + public SortStrategy getSortStrategy(T[] array) { + if (array == null || array.length == 0) + return new NoSortStrategy; + else + return new QuickSortStrategy; + } +} From 94bd18984b7211871022b25a61715526c63d3f22 Mon Sep 17 00:00:00 2001 From: aikaran Date: Tue, 5 Jun 2018 21:02:56 +0900 Subject: [PATCH 37/47] fix syntax error --- src/seventh/shared/Arrays.java | 4 ++-- src/seventh/shared/NoSortStrategy.java | 1 + src/seventh/shared/QuickSortStrategy.java | 1 + src/seventh/shared/SortStrategy.java | 1 + src/seventh/shared/SortStrategyFactory.java | 6 +++--- 5 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/seventh/shared/Arrays.java b/src/seventh/shared/Arrays.java index 644074e..0081708 100644 --- a/src/seventh/shared/Arrays.java +++ b/src/seventh/shared/Arrays.java @@ -53,8 +53,8 @@ public static void clear(T[] array) { * @return the supplied array */ public T[] sort(T[] array, Comparator comp) { - SortStrategyFactory = new SortStrategyFactory(); - SortStrategy sortStrategy = SortStrategyFactory.getSortStrategy(array); + SortStrategyFactory sortStrategyFactory = new SortStrategyFactory(); + SortStrategy sortStrategy = sortStrategyFactory.getSortStrategy(array); sortStrategy.sort(array, comp); return array; } diff --git a/src/seventh/shared/NoSortStrategy.java b/src/seventh/shared/NoSortStrategy.java index 20fea9a..dc8f71e 100644 --- a/src/seventh/shared/NoSortStrategy.java +++ b/src/seventh/shared/NoSortStrategy.java @@ -3,6 +3,7 @@ import java.util.Comparator; public class NoSortStrategy implements SortStrategy { + public void sort(T[] array, Comparator comp) { return ; } diff --git a/src/seventh/shared/QuickSortStrategy.java b/src/seventh/shared/QuickSortStrategy.java index 8d76187..861d721 100644 --- a/src/seventh/shared/QuickSortStrategy.java +++ b/src/seventh/shared/QuickSortStrategy.java @@ -3,6 +3,7 @@ import java.util.Comparator; public class QuickSortStrategy implements SortStrategy { + public void sort(T[] array, Comparator comp) { quickSort(array, comp, 0, array.length-1); } diff --git a/src/seventh/shared/SortStrategy.java b/src/seventh/shared/SortStrategy.java index c54f504..553a855 100644 --- a/src/seventh/shared/SortStrategy.java +++ b/src/seventh/shared/SortStrategy.java @@ -3,5 +3,6 @@ import java.util.Comparator; public interface SortStrategy { + public void sort(T[] array, Comparator comp); } \ No newline at end of file diff --git a/src/seventh/shared/SortStrategyFactory.java b/src/seventh/shared/SortStrategyFactory.java index a895b61..06dffe3 100644 --- a/src/seventh/shared/SortStrategyFactory.java +++ b/src/seventh/shared/SortStrategyFactory.java @@ -1,11 +1,11 @@ -import java.util.Comparator; +package seventh.shared; public class SortStrategyFactory { public SortStrategy getSortStrategy(T[] array) { if (array == null || array.length == 0) - return new NoSortStrategy; + return new NoSortStrategy(); else - return new QuickSortStrategy; + return new QuickSortStrategy(); } } From 1eeefd65af51f2d8410136dae86d2b4d62477933 Mon Sep 17 00:00:00 2001 From: aikaran Date: Thu, 7 Jun 2018 13:37:25 +0900 Subject: [PATCH 38/47] Singleton Pattern Target : seventh.shared.Arrays and, seventh.shared.SortStrategyFactory Reason : Two more factories are not necessary. Only one factory is sufficient. --- src/seventh/shared/Arrays.java | 3 +-- src/seventh/shared/NoSortStrategy.java | 6 ++++++ src/seventh/shared/QuickSortStrategy.java | 20 ++++++++++++++++++++ src/seventh/shared/SortStrategy.java | 7 +++++++ src/seventh/shared/SortStrategyFactory.java | 10 ++++++++-- 5 files changed, 42 insertions(+), 4 deletions(-) diff --git a/src/seventh/shared/Arrays.java b/src/seventh/shared/Arrays.java index 0081708..53e52f0 100644 --- a/src/seventh/shared/Arrays.java +++ b/src/seventh/shared/Arrays.java @@ -53,8 +53,7 @@ public static void clear(T[] array) { * @return the supplied array */ public T[] sort(T[] array, Comparator comp) { - SortStrategyFactory sortStrategyFactory = new SortStrategyFactory(); - SortStrategy sortStrategy = sortStrategyFactory.getSortStrategy(array); + SortStrategy sortStrategy = SortStrategyFactory.getSortStrategy(array); sortStrategy.sort(array, comp); return array; } diff --git a/src/seventh/shared/NoSortStrategy.java b/src/seventh/shared/NoSortStrategy.java index dc8f71e..9d77b3d 100644 --- a/src/seventh/shared/NoSortStrategy.java +++ b/src/seventh/shared/NoSortStrategy.java @@ -4,6 +4,12 @@ public class NoSortStrategy implements SortStrategy { + /** + * do not sorting for null array + * + * @param array + * @param comp + */ public void sort(T[] array, Comparator comp) { return ; } diff --git a/src/seventh/shared/QuickSortStrategy.java b/src/seventh/shared/QuickSortStrategy.java index 861d721..ca80bcc 100644 --- a/src/seventh/shared/QuickSortStrategy.java +++ b/src/seventh/shared/QuickSortStrategy.java @@ -4,10 +4,23 @@ public class QuickSortStrategy implements SortStrategy { + /** + * Sorts the supplied array by the quickSort method + * + * @param array + * @param comp + */ public void sort(T[] array, Comparator comp) { quickSort(array, comp, 0, array.length-1); } + /** + * Sorts the supplied array by the {@link Comparator} + * + * @param array + * @param comp + * @return the supplied array + */ private static void quickSort(T[] array, Comparator comp, int low, int high) { int i = low; int j = high; @@ -37,6 +50,13 @@ private static void quickSort(T[] array, Comparator comp, int low, int hi } } + /** + * Swap the elements in array + * + * @param array + * @param i + * @param j + */ private static void swap(T[] array, int i, int j) { T temp = array[i]; array[i] = array[j]; diff --git a/src/seventh/shared/SortStrategy.java b/src/seventh/shared/SortStrategy.java index 553a855..e271ec6 100644 --- a/src/seventh/shared/SortStrategy.java +++ b/src/seventh/shared/SortStrategy.java @@ -4,5 +4,12 @@ public interface SortStrategy { + /** + * Sorts the supplied array by the {@link Comparator} + * + * @param array + * @param comp + * @return the supplied array + */ public void sort(T[] array, Comparator comp); } \ No newline at end of file diff --git a/src/seventh/shared/SortStrategyFactory.java b/src/seventh/shared/SortStrategyFactory.java index 06dffe3..8857067 100644 --- a/src/seventh/shared/SortStrategyFactory.java +++ b/src/seventh/shared/SortStrategyFactory.java @@ -1,8 +1,14 @@ package seventh.shared; -public class SortStrategyFactory { +public final class SortStrategyFactory { - public SortStrategy getSortStrategy(T[] array) { + /** + * Return SortStrategy for the supplied array + * + * @param array + * @return SortStrategy + */ + public static SortStrategy getSortStrategy(T[] array) { if (array == null || array.length == 0) return new NoSortStrategy(); else From 2479d4c7c8bc9454c50f895f7d3ff5798df160f9 Mon Sep 17 00:00:00 2001 From: aikaran Date: Thu, 7 Jun 2018 13:42:27 +0900 Subject: [PATCH 39/47] replace all tabs to 4 spaces --- src/seventh/shared/Arrays.java | 6 ++--- src/seventh/shared/NoSortStrategy.java | 10 +++---- src/seventh/shared/QuickSortStrategy.java | 30 ++++++++++----------- src/seventh/shared/SortStrategy.java | 4 +-- src/seventh/shared/SortStrategyFactory.java | 14 +++++----- 5 files changed, 32 insertions(+), 32 deletions(-) diff --git a/src/seventh/shared/Arrays.java b/src/seventh/shared/Arrays.java index 53e52f0..ddb68e8 100644 --- a/src/seventh/shared/Arrays.java +++ b/src/seventh/shared/Arrays.java @@ -12,7 +12,7 @@ * */ public class Arrays { - + /** * Counts the amount of used elements in the array * @@ -53,8 +53,8 @@ public static void clear(T[] array) { * @return the supplied array */ public T[] sort(T[] array, Comparator comp) { - SortStrategy sortStrategy = SortStrategyFactory.getSortStrategy(array); - sortStrategy.sort(array, comp); + SortStrategy sortStrategy = SortStrategyFactory.getSortStrategy(array); + sortStrategy.sort(array, comp); return array; } } diff --git a/src/seventh/shared/NoSortStrategy.java b/src/seventh/shared/NoSortStrategy.java index 9d77b3d..ca30bda 100644 --- a/src/seventh/shared/NoSortStrategy.java +++ b/src/seventh/shared/NoSortStrategy.java @@ -3,14 +3,14 @@ import java.util.Comparator; public class NoSortStrategy implements SortStrategy { - - /** + + /** * do not sorting for null array * * @param array * @param comp */ - public void sort(T[] array, Comparator comp) { - return ; - } + public void sort(T[] array, Comparator comp) { + return ; + } } diff --git a/src/seventh/shared/QuickSortStrategy.java b/src/seventh/shared/QuickSortStrategy.java index ca80bcc..96ec188 100644 --- a/src/seventh/shared/QuickSortStrategy.java +++ b/src/seventh/shared/QuickSortStrategy.java @@ -3,26 +3,26 @@ import java.util.Comparator; public class QuickSortStrategy implements SortStrategy { - - /** + + /** * Sorts the supplied array by the quickSort method * * @param array * @param comp */ - public void sort(T[] array, Comparator comp) { - quickSort(array, comp, 0, array.length-1); - } - - /** + public void sort(T[] array, Comparator comp) { + quickSort(array, comp, 0, array.length-1); + } + + /** * Sorts the supplied array by the {@link Comparator} * * @param array * @param comp * @return the supplied array */ - private static void quickSort(T[] array, Comparator comp, int low, int high) { - int i = low; + private static void quickSort(T[] array, Comparator comp, int low, int high) { + int i = low; int j = high; T pivot = array[low + (high - low) / 2]; @@ -42,22 +42,22 @@ private static void quickSort(T[] array, Comparator comp, int low, int hi } if (low < j) { - quickSort(array, comp, low, j); + quickSort(array, comp, low, j); } if (i < high) { - quickSort(array, comp, i, high); + quickSort(array, comp, i, high); } - } - - /** + } + + /** * Swap the elements in array * * @param array * @param i * @param j */ - private static void swap(T[] array, int i, int j) { + private static void swap(T[] array, int i, int j) { T temp = array[i]; array[i] = array[j]; array[j] = temp; diff --git a/src/seventh/shared/SortStrategy.java b/src/seventh/shared/SortStrategy.java index e271ec6..a91a639 100644 --- a/src/seventh/shared/SortStrategy.java +++ b/src/seventh/shared/SortStrategy.java @@ -3,8 +3,8 @@ import java.util.Comparator; public interface SortStrategy { - - /** + + /** * Sorts the supplied array by the {@link Comparator} * * @param array diff --git a/src/seventh/shared/SortStrategyFactory.java b/src/seventh/shared/SortStrategyFactory.java index 8857067..56c4ce9 100644 --- a/src/seventh/shared/SortStrategyFactory.java +++ b/src/seventh/shared/SortStrategyFactory.java @@ -1,17 +1,17 @@ package seventh.shared; public final class SortStrategyFactory { - - /** + + /** * Return SortStrategy for the supplied array * * @param array * @return SortStrategy */ - public static SortStrategy getSortStrategy(T[] array) { - if (array == null || array.length == 0) + public static SortStrategy getSortStrategy(T[] array) { + if (array == null || array.length == 0) return new NoSortStrategy(); - else - return new QuickSortStrategy(); - } + else + return new QuickSortStrategy(); + } } From ce9f243382475571d3b525d1ec57524215e5a01f Mon Sep 17 00:00:00 2001 From: junhyeong Date: Fri, 8 Jun 2018 00:24:32 +0900 Subject: [PATCH 40/47] Strategy Pattern Target : seventh/ai/basic/group/AIGroupAction seventh/ai/basic/group/AIGroupAction seventh/ai/basic/group/AIGroupAction seventh/ai/basic/group/AIGroupAction seventh/ai/basic/group/AIGroupAction seventh/ai/basic/group/AIGroupAction Reason : Separate implementation of start and getAction method from AIGroupAction Class for avoiding duplication --- src/seventh/ai/basic/group/AIGroupAction.java | 13 ++++- .../ai/basic/group/AIGroupAttackAction.java | 37 +------------- .../ai/basic/group/AIGroupDefendAction.java | 48 +------------------ 3 files changed, 15 insertions(+), 83 deletions(-) diff --git a/src/seventh/ai/basic/group/AIGroupAction.java b/src/seventh/ai/basic/group/AIGroupAction.java index 129b6bc..35e467e 100644 --- a/src/seventh/ai/basic/group/AIGroupAction.java +++ b/src/seventh/ai/basic/group/AIGroupAction.java @@ -12,10 +12,19 @@ */ public abstract class AIGroupAction implements Updatable { - public abstract void start(AIGroup aIGroup); + protected Start start; + protected GetAction action; + + public abstract void end(AIGroup aIGroup); public abstract void cancel(AIGroup aIGroup); public abstract boolean isFinished(AIGroup aIGroup); - public abstract Action getAction(AIGroup aIGroup); + + public void start(AIGroup aIGroup) { + start.start(aIGroup); + } + public Action getAction(AIGroup aIGroup) { + return action.getAction(aIGroup); + } } diff --git a/src/seventh/ai/basic/group/AIGroupAttackAction.java b/src/seventh/ai/basic/group/AIGroupAttackAction.java index 07add40..d6d3941 100644 --- a/src/seventh/ai/basic/group/AIGroupAttackAction.java +++ b/src/seventh/ai/basic/group/AIGroupAttackAction.java @@ -32,43 +32,10 @@ public class AIGroupAttackAction extends AIGroupAction { public AIGroupAttackAction(Vector2f position) { this.attackPosition = position; this.attackDirections = new ArrayList<>(); + start = new AttackStart(position); + action = new AttackGetAction(position); } - @Override - public void start(AIGroup aIGroup) { - World world = aIGroup.getWorld(); - - this.attackDirections.addAll(world.getAttackDirections(attackPosition, 150f, aIGroup.groupSize())); - if(attackDirections.isEmpty()) { - attackDirections.add(new AttackDirection(attackPosition)); - } - } - - /* (non-Javadoc) - * @see seventh.ai.basic.group.AIGroupAction#getAction(seventh.ai.basic.group.AIGroup) - */ - @Override - public Action getAction(AIGroup aIGroup) { - if(aIGroup.groupSize()>0) { - World world = aIGroup.getWorld(); - Brain[] members = aIGroup.getMembers(); - Roles roles = aIGroup.getRoles(); - - int j = 0; - for(int i = 0; i < members.length; i++) { - Brain member = members[i]; - if(member!=null) { - if(roles.getAssignedRole(member.getPlayer()) != Role.None) { - AttackDirection dir = attackDirections.get( (j+=1) % attackDirections.size()); - return new SequencedAction("squadAttack") - .addNext(world.getGoals().moveToAction(dir.getDirection())); - } - } - } - } - - return new WaitAction(500); - } /* (non-Javadoc) * @see seventh.ai.basic.group.AIGroupAction#end(seventh.ai.basic.group.AIGroup) diff --git a/src/seventh/ai/basic/group/AIGroupDefendAction.java b/src/seventh/ai/basic/group/AIGroupDefendAction.java index 5bda7cb..a3de547 100644 --- a/src/seventh/ai/basic/group/AIGroupDefendAction.java +++ b/src/seventh/ai/basic/group/AIGroupDefendAction.java @@ -29,54 +29,10 @@ public class AIGroupDefendAction extends AIGroupAction { public AIGroupDefendAction(Vector2f position) { this.defendPosition = position; this.directionsToDefend = new ArrayList<>(); + start = new DefendStart(position); + action = new DefendGetAction(position); } - @Override - public void start(AIGroup aIGroup) { - World world = aIGroup.getWorld(); - float radius = (float)world.getRandom().getRandomRange(100f, 150f); - directionsToDefend.addAll(world.getAttackDirections(this.defendPosition, radius, 12)); - - } - - /* (non-Javadoc) - * @see seventh.ai.basic.group.AIGroupAction#getAction(seventh.ai.basic.group.AIGroup) - */ - @Override - public Action getAction(AIGroup aIGroup) { - if(aIGroup.groupSize() > 0 ) { - World world = aIGroup.getWorld(); - Brain[] members = aIGroup.getMembers(); -// Roles roles = aIGroup.getRoles(); - - int squadSize = aIGroup.groupSize(); - - if(!directionsToDefend.isEmpty() && squadSize>0) { - int increment = 1; - if(directionsToDefend.size()> squadSize) { - increment = directionsToDefend.size() / squadSize; - } - - int i = 0; - for(int j = 0; j < members.length; j++) { - Brain member = members[j]; - if(member!=null) { - //if(roles.getAssignedRole(member.getPlayer()) != Role.None) - { - AttackDirection dir = directionsToDefend.get( (i += increment) % directionsToDefend.size()); - Vector2f position = new Vector2f(dir.getDirection()); - //Vector2f.Vector2fMA(defendPosition, dir.getDirection(), 10f + world.getRandom().nextInt(100), position); - - return (world.getGoals().guard(position)); - } - } - - } - } - } - - return new WaitAction(500); - } /* (non-Javadoc) * @see seventh.ai.basic.group.AIGroupAction#end(seventh.ai.basic.group.AIGroup) From b27aca5059da4fc8211a2f4dec119fdd97b1fcbe Mon Sep 17 00:00:00 2001 From: terry2511 Date: Fri, 8 Jun 2018 00:29:50 +0900 Subject: [PATCH 41/47] Strategy Pattern Target : seventh/ai/basic/group/AIGroupAction seventh/ai/basic/group/AIGroupAttackAction seventh/ai/basic/group/AIGroupDefendAction seventh/ai/basic/group/AttackGetAction seventh/ai/basic/group/AttackStart seventh/ai/basic/group/DefendGetAction seventh/ai/basic/group/DefendStart seventh/ai/basic/group/GetAction seventh/ai/basic/group/Start Reason : Separate implementation of start and getAction method from AIGroupAction Class for avoiding duplication --- src/seventh/ai/basic/group/AIGroupAction.java | 10 +++++----- src/seventh/ai/basic/group/AIGroupAttackAction.java | 3 ++- src/seventh/ai/basic/group/AIGroupDefendAction.java | 3 ++- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/src/seventh/ai/basic/group/AIGroupAction.java b/src/seventh/ai/basic/group/AIGroupAction.java index 35e467e..e2a0867 100644 --- a/src/seventh/ai/basic/group/AIGroupAction.java +++ b/src/seventh/ai/basic/group/AIGroupAction.java @@ -12,19 +12,19 @@ */ public abstract class AIGroupAction implements Updatable { - protected Start start; - protected GetAction action; - + protected Start start; + protected GetAction action; + public abstract void end(AIGroup aIGroup); public abstract void cancel(AIGroup aIGroup); public abstract boolean isFinished(AIGroup aIGroup); public void start(AIGroup aIGroup) { - start.start(aIGroup); + start.start(aIGroup); } public Action getAction(AIGroup aIGroup) { - return action.getAction(aIGroup); + return action.getAction(aIGroup); } } diff --git a/src/seventh/ai/basic/group/AIGroupAttackAction.java b/src/seventh/ai/basic/group/AIGroupAttackAction.java index d6d3941..181baa5 100644 --- a/src/seventh/ai/basic/group/AIGroupAttackAction.java +++ b/src/seventh/ai/basic/group/AIGroupAttackAction.java @@ -32,8 +32,9 @@ public class AIGroupAttackAction extends AIGroupAction { public AIGroupAttackAction(Vector2f position) { this.attackPosition = position; this.attackDirections = new ArrayList<>(); - start = new AttackStart(position); action = new AttackGetAction(position); + start = new AttackStart(position); + } diff --git a/src/seventh/ai/basic/group/AIGroupDefendAction.java b/src/seventh/ai/basic/group/AIGroupDefendAction.java index a3de547..a4f9385 100644 --- a/src/seventh/ai/basic/group/AIGroupDefendAction.java +++ b/src/seventh/ai/basic/group/AIGroupDefendAction.java @@ -29,8 +29,9 @@ public class AIGroupDefendAction extends AIGroupAction { public AIGroupDefendAction(Vector2f position) { this.defendPosition = position; this.directionsToDefend = new ArrayList<>(); - start = new DefendStart(position); action = new DefendGetAction(position); + start = new DefendStart(position); + } From d5031ced07417111d2f15717701b065787f74a58 Mon Sep 17 00:00:00 2001 From: terry2511 Date: Fri, 8 Jun 2018 00:35:40 +0900 Subject: [PATCH 42/47] Strategy Pattern Target : seventh/ai/basic/group/AIGroupAction seventh/ai/basic/group/AIGroupAttackAction seventh/ai/basic/group/AIGroupDefendAction seventh/ai/basic/group/AttackGetAction seventh/ai/basic/group/AttackStart seventh/ai/basic/group/DefendGetAction seventh/ai/basic/group/DefendStart seventh/ai/basic/group/GetAction seventh/ai/basic/group/Start Reason : Separate implementation of start and getAction method from AIGroupAction Class for avoiding duplication --- src/seventh/ai/basic/group/AIGroupAction.java | 1 - .../ai/basic/group/AIGroupAttackAction.java | 1 - .../ai/basic/group/AIGroupDefendAction.java | 1 - .../ai/basic/group/AttackGetAction.java | 51 ++++++++++++++++ src/seventh/ai/basic/group/AttackStart.java | 28 +++++++++ .../ai/basic/group/DefendGetAction.java | 58 +++++++++++++++++++ src/seventh/ai/basic/group/DefendStart.java | 27 +++++++++ src/seventh/ai/basic/group/GetAction.java | 7 +++ src/seventh/ai/basic/group/Start.java | 5 ++ 9 files changed, 176 insertions(+), 3 deletions(-) create mode 100644 src/seventh/ai/basic/group/AttackGetAction.java create mode 100644 src/seventh/ai/basic/group/AttackStart.java create mode 100644 src/seventh/ai/basic/group/DefendGetAction.java create mode 100644 src/seventh/ai/basic/group/DefendStart.java create mode 100644 src/seventh/ai/basic/group/GetAction.java create mode 100644 src/seventh/ai/basic/group/Start.java diff --git a/src/seventh/ai/basic/group/AIGroupAction.java b/src/seventh/ai/basic/group/AIGroupAction.java index e2a0867..3146315 100644 --- a/src/seventh/ai/basic/group/AIGroupAction.java +++ b/src/seventh/ai/basic/group/AIGroupAction.java @@ -15,7 +15,6 @@ public abstract class AIGroupAction implements Updatable { protected Start start; protected GetAction action; - public abstract void end(AIGroup aIGroup); public abstract void cancel(AIGroup aIGroup); public abstract boolean isFinished(AIGroup aIGroup); diff --git a/src/seventh/ai/basic/group/AIGroupAttackAction.java b/src/seventh/ai/basic/group/AIGroupAttackAction.java index 181baa5..b57a8a4 100644 --- a/src/seventh/ai/basic/group/AIGroupAttackAction.java +++ b/src/seventh/ai/basic/group/AIGroupAttackAction.java @@ -34,7 +34,6 @@ public AIGroupAttackAction(Vector2f position) { this.attackDirections = new ArrayList<>(); action = new AttackGetAction(position); start = new AttackStart(position); - } diff --git a/src/seventh/ai/basic/group/AIGroupDefendAction.java b/src/seventh/ai/basic/group/AIGroupDefendAction.java index a4f9385..22a7a96 100644 --- a/src/seventh/ai/basic/group/AIGroupDefendAction.java +++ b/src/seventh/ai/basic/group/AIGroupDefendAction.java @@ -31,7 +31,6 @@ public AIGroupDefendAction(Vector2f position) { this.directionsToDefend = new ArrayList<>(); action = new DefendGetAction(position); start = new DefendStart(position); - } diff --git a/src/seventh/ai/basic/group/AttackGetAction.java b/src/seventh/ai/basic/group/AttackGetAction.java new file mode 100644 index 0000000..bc2f939 --- /dev/null +++ b/src/seventh/ai/basic/group/AttackGetAction.java @@ -0,0 +1,51 @@ +package seventh.ai.basic.group; + +import java.util.ArrayList; +import java.util.List; + +import seventh.ai.basic.AttackDirection; +import seventh.ai.basic.Brain; +import seventh.ai.basic.World; +import seventh.ai.basic.actions.Action; +import seventh.ai.basic.actions.SequencedAction; +import seventh.ai.basic.actions.WaitAction; +import seventh.ai.basic.teamstrategy.Roles; +import seventh.ai.basic.teamstrategy.Roles.Role; +import seventh.math.Vector2f; + +public class AttackGetAction implements GetAction { + private Vector2f attackPosition; + private List attackDirections; + + + public AttackGetAction(Vector2f Position) { + this.attackPosition = Position; + this.attackDirections = new ArrayList<>(); + } + /* (non-Javadoc) + * @see seventh.ai.basic.group.AIGroupAction#getAction(seventh.ai.basic.group.AIGroup) + */ + @Override + public Action getAction(AIGroup aIGroup) { + if(aIGroup.groupSize()>0) { + World world = aIGroup.getWorld(); + Brain[] members = aIGroup.getMembers(); + Roles roles = aIGroup.getRoles(); + + int j = 0; + for(int i = 0; i < members.length; i++) { + Brain member = members[i]; + if(member!=null) { + if(roles.getAssignedRole(member.getPlayer()) != Role.None) { + AttackDirection dir = attackDirections.get( (j+=1) % attackDirections.size()); + return new SequencedAction("squadAttack") + .addNext(world.getGoals().moveToAction(dir.getDirection())); + } + } + } + } + + return new WaitAction(500); + } + +} diff --git a/src/seventh/ai/basic/group/AttackStart.java b/src/seventh/ai/basic/group/AttackStart.java new file mode 100644 index 0000000..c75fc05 --- /dev/null +++ b/src/seventh/ai/basic/group/AttackStart.java @@ -0,0 +1,28 @@ +package seventh.ai.basic.group; + +import java.util.ArrayList; +import java.util.List; + +import seventh.ai.basic.AttackDirection; +import seventh.ai.basic.World; +import seventh.math.Vector2f; + +public class AttackStart implements Start { + + private Vector2f attackPosition; + private List attackDirections; + + public AttackStart(Vector2f Position) { + this.attackPosition = Position; + this.attackDirections = new ArrayList<>(); + } + + public void start(AIGroup aIGroup) { + World world = aIGroup.getWorld(); + + this.attackDirections.addAll(world.getAttackDirections(attackPosition, 150f, aIGroup.groupSize())); + if(attackDirections.isEmpty()) { + attackDirections.add(new AttackDirection(attackPosition)); + } + } +} diff --git a/src/seventh/ai/basic/group/DefendGetAction.java b/src/seventh/ai/basic/group/DefendGetAction.java new file mode 100644 index 0000000..63592ff --- /dev/null +++ b/src/seventh/ai/basic/group/DefendGetAction.java @@ -0,0 +1,58 @@ +package seventh.ai.basic.group; + +import java.util.ArrayList; +import java.util.List; + +import seventh.ai.basic.AttackDirection; +import seventh.ai.basic.Brain; +import seventh.ai.basic.World; +import seventh.ai.basic.actions.Action; +import seventh.ai.basic.actions.WaitAction; +import seventh.math.Vector2f; + +public class DefendGetAction implements GetAction { + + private Vector2f defendPosition; + private List directionsToDefend; + + public DefendGetAction(Vector2f Position) { + this.defendPosition = Position; + this.directionsToDefend = new ArrayList<>(); + } + + public Action getAction(AIGroup aIGroup) { + if(aIGroup.groupSize() > 0 ) { + World world = aIGroup.getWorld(); + Brain[] members = aIGroup.getMembers(); +// Roles roles = aIGroup.getRoles(); + + int squadSize = aIGroup.groupSize(); + + if(!directionsToDefend.isEmpty() && squadSize>0) { + int increment = 1; + if(directionsToDefend.size()> squadSize) { + increment = directionsToDefend.size() / squadSize; + } + + int i = 0; + for(int j = 0; j < members.length; j++) { + Brain member = members[j]; + if(member!=null) { + //if(roles.getAssignedRole(member.getPlayer()) != Role.None) + { + AttackDirection dir = directionsToDefend.get( (i += increment) % directionsToDefend.size()); + Vector2f position = new Vector2f(dir.getDirection()); + //Vector2f.Vector2fMA(defendPosition, dir.getDirection(), 10f + world.getRandom().nextInt(100), position); + + return (world.getGoals().guard(position)); + } + } + + } + } + } + + return new WaitAction(500); + } + +} diff --git a/src/seventh/ai/basic/group/DefendStart.java b/src/seventh/ai/basic/group/DefendStart.java new file mode 100644 index 0000000..918d0b9 --- /dev/null +++ b/src/seventh/ai/basic/group/DefendStart.java @@ -0,0 +1,27 @@ +package seventh.ai.basic.group; + +import java.util.ArrayList; +import java.util.List; + +import seventh.ai.basic.AttackDirection; +import seventh.ai.basic.World; +import seventh.math.Vector2f; + +public class DefendStart implements Start { + + + private Vector2f defendPosition; + private List directionsToDefend; + + public DefendStart(Vector2f Position) { + this.defendPosition = Position; + this.directionsToDefend = new ArrayList<>(); + } + + public void start(AIGroup aIGroup) { + World world = aIGroup.getWorld(); + float radius = (float)world.getRandom().getRandomRange(100f, 150f); + directionsToDefend.addAll(world.getAttackDirections(this.defendPosition, radius, 12)); + + } +} diff --git a/src/seventh/ai/basic/group/GetAction.java b/src/seventh/ai/basic/group/GetAction.java new file mode 100644 index 0000000..3e15c3f --- /dev/null +++ b/src/seventh/ai/basic/group/GetAction.java @@ -0,0 +1,7 @@ +package seventh.ai.basic.group; + +import seventh.ai.basic.actions.Action; + +public interface GetAction { + public Action getAction(AIGroup aIGroup); +} diff --git a/src/seventh/ai/basic/group/Start.java b/src/seventh/ai/basic/group/Start.java new file mode 100644 index 0000000..ff166a5 --- /dev/null +++ b/src/seventh/ai/basic/group/Start.java @@ -0,0 +1,5 @@ +package seventh.ai.basic.group; + +public interface Start { + public void start(AIGroup aIGroup); +} From 08b730f26bac10006d78fc7e8d3c5402938957b0 Mon Sep 17 00:00:00 2001 From: GardenHee Date: Fri, 8 Jun 2018 00:42:44 +0900 Subject: [PATCH 43/47] Design Pattern: Factory Method Pattern Target : seventh/ai/basic/FeelSensor seventh/ai/basic/Sensors seventh/ai/basic/SightSensor seventh/ai/basic/SoundSensor seventh/ai/basic/SensorFactory Reason : For useful skill to prepare for changes in objects --- src/seventh/ai/basic/FeelSensor.java | 2 +- src/seventh/ai/basic/SensorFactory.java | 42 +++++++++++++++++++++++++ src/seventh/ai/basic/Sensors.java | 22 +++++-------- src/seventh/ai/basic/SightSensor.java | 2 +- src/seventh/ai/basic/SoundSensor.java | 3 +- 5 files changed, 52 insertions(+), 19 deletions(-) create mode 100644 src/seventh/ai/basic/SensorFactory.java diff --git a/src/seventh/ai/basic/FeelSensor.java b/src/seventh/ai/basic/FeelSensor.java index a346ada..c803003 100644 --- a/src/seventh/ai/basic/FeelSensor.java +++ b/src/seventh/ai/basic/FeelSensor.java @@ -21,7 +21,7 @@ public class FeelSensor implements Sensor, OnDamageListener { private FeelMemory memory; private TimeStep timeStep; private Brain brain; - + /** * @param brain */ diff --git a/src/seventh/ai/basic/SensorFactory.java b/src/seventh/ai/basic/SensorFactory.java new file mode 100644 index 0000000..2586f59 --- /dev/null +++ b/src/seventh/ai/basic/SensorFactory.java @@ -0,0 +1,42 @@ +package seventh.ai.basic; + +import seventh.shared.TimeStep; + +public class SensorFactory { + + protected SightSensor sightSensor; + protected SoundSensor soundSensor; + protected FeelSensor feelSensor; + + public SensorFactory(Brain brain){ + this.sightSensor = new SightSensor(brain); + this.soundSensor = new SoundSensor(brain); + this.feelSensor = new FeelSensor(brain); + } + + public FeelSensor getFeelSensor() { + return feelSensor; + } + + public SightSensor getSightSensor() { + return sightSensor; + } + + public SoundSensor getSoundSensor() { + return soundSensor; + } + + public void reset(Brain brain) { + this.sightSensor.reset(brain); + this.soundSensor.reset(brain); + this.feelSensor.reset(brain); + } + + public void update(TimeStep timeStep) { + this.sightSensor.update(timeStep); + this.soundSensor.update(timeStep); + this.feelSensor.update(timeStep); + } + + +} diff --git a/src/seventh/ai/basic/Sensors.java b/src/seventh/ai/basic/Sensors.java index 035b3e1..d3fe866 100644 --- a/src/seventh/ai/basic/Sensors.java +++ b/src/seventh/ai/basic/Sensors.java @@ -13,16 +13,12 @@ */ public class Sensors { - private SightSensor sightSensor; - private SoundSensor soundSensor; - private FeelSensor feelSensor; + private SensorFactory sensorfactory; public Sensors(Brain brain) { - this.sightSensor = new SightSensor(brain); - this.soundSensor = new SoundSensor(brain); - this.feelSensor = new FeelSensor(brain); + this.sensorfactory = new SensorFactory(brain); } @@ -32,30 +28,28 @@ public Sensors(Brain brain) { * @param brain */ public void reset(Brain brain) { - this.sightSensor.reset(brain); - this.soundSensor.reset(brain); - this.feelSensor.reset(brain); + this.sensorfactory.reset(brain); } /** * @return the feelSensor */ public FeelSensor getFeelSensor() { - return feelSensor; + return this.sensorfactory.getFeelSensor(); } /** * @return the sightSensor */ public SightSensor getSightSensor() { - return sightSensor; + return this.sensorfactory.getSightSensor(); } /** * @return the soundSensor */ public SoundSensor getSoundSensor() { - return soundSensor; + return this.sensorfactory.getSoundSensor(); } /** @@ -63,9 +57,7 @@ public SoundSensor getSoundSensor() { * @param timeStep */ public void update(TimeStep timeStep) { - this.sightSensor.update(timeStep); - this.soundSensor.update(timeStep); - this.feelSensor.update(timeStep); + this.sensorfactory.update(timeStep); } } diff --git a/src/seventh/ai/basic/SightSensor.java b/src/seventh/ai/basic/SightSensor.java index 478433b..f7e3e10 100644 --- a/src/seventh/ai/basic/SightSensor.java +++ b/src/seventh/ai/basic/SightSensor.java @@ -30,7 +30,7 @@ public class SightSensor implements Sensor { private Timer updateSight; private List entitiesInView; - + /** * @param width * @param height diff --git a/src/seventh/ai/basic/SoundSensor.java b/src/seventh/ai/basic/SoundSensor.java index 00bd07b..8221d00 100644 --- a/src/seventh/ai/basic/SoundSensor.java +++ b/src/seventh/ai/basic/SoundSensor.java @@ -24,8 +24,7 @@ * @author Tony * */ -public class SoundSensor implements Sensor { - +public class SoundSensor implements Sensor{ /** * Less important sounds */ From c01c2761697900c048b2c8db13f8da9bbadf9202 Mon Sep 17 00:00:00 2001 From: virginbabylon Date: Sat, 9 Jun 2018 13:26:34 +0900 Subject: [PATCH 44/47] ai/basic/memory template method pattern strategy pattern --- .../ai/basic/memory/ExpireStrategy.java | 5 ++++ .../ai/basic/memory/FeelExpireStrategy.java | 16 +++++++++++++ src/seventh/ai/basic/memory/FeelMemory.java | 17 ++++--------- src/seventh/ai/basic/memory/MemoryRecord.java | 24 +++++++++++++++++++ .../ai/basic/memory/SightExpireStrategy.java | 22 +++++++++++++++++ src/seventh/ai/basic/memory/SightMemory.java | 24 +++++-------------- .../ai/basic/memory/SoundExpireStrategy.java | 16 +++++++++++++ src/seventh/ai/basic/memory/SoundMemory.java | 23 +++++------------- 8 files changed, 100 insertions(+), 47 deletions(-) create mode 100644 src/seventh/ai/basic/memory/ExpireStrategy.java create mode 100644 src/seventh/ai/basic/memory/FeelExpireStrategy.java create mode 100644 src/seventh/ai/basic/memory/MemoryRecord.java create mode 100644 src/seventh/ai/basic/memory/SightExpireStrategy.java create mode 100644 src/seventh/ai/basic/memory/SoundExpireStrategy.java diff --git a/src/seventh/ai/basic/memory/ExpireStrategy.java b/src/seventh/ai/basic/memory/ExpireStrategy.java new file mode 100644 index 0000000..8736988 --- /dev/null +++ b/src/seventh/ai/basic/memory/ExpireStrategy.java @@ -0,0 +1,5 @@ +package seventh.ai.basic.memory; + +public interface ExpireStrategy { + public void expire(); +} diff --git a/src/seventh/ai/basic/memory/FeelExpireStrategy.java b/src/seventh/ai/basic/memory/FeelExpireStrategy.java new file mode 100644 index 0000000..ba4dec2 --- /dev/null +++ b/src/seventh/ai/basic/memory/FeelExpireStrategy.java @@ -0,0 +1,16 @@ +package seventh.ai.basic.memory; + +import seventh.game.entities.Entity; + +public class FeelExpireStrategy implements ExpireStrategy{ + + protected Entity damager; + protected boolean isValid; + @Override + public void expire() { + this.damager = null; + this.isValid = false; + } + + +} \ No newline at end of file diff --git a/src/seventh/ai/basic/memory/FeelMemory.java b/src/seventh/ai/basic/memory/FeelMemory.java index d686aa9..6953fd8 100644 --- a/src/seventh/ai/basic/memory/FeelMemory.java +++ b/src/seventh/ai/basic/memory/FeelMemory.java @@ -7,7 +7,6 @@ import seventh.shared.SeventhConstants; import seventh.shared.TimeStep; import seventh.shared.Updatable; - /** * @author Tony * @@ -20,21 +19,18 @@ public class FeelMemory implements Updatable { * @author Tony * */ - public static class FeelMemoryRecord { - private final long expireTime; + public static class FeelMemoryRecord extends MemoryRecord{ private Entity damager; private long timeFelt; private long timeFeltAgo; - private boolean isValid; /** * @param expireTime */ public FeelMemoryRecord(long expireTime) { - this.expireTime = expireTime; - this.isValid = false; + super(expireTime); } @@ -66,17 +62,14 @@ public boolean isValid() { public void checkExpired(TimeStep timeStep) { this.timeFeltAgo = timeStep.getGameClock() - this.timeFelt; if(isExpired(timeStep)) { - expire(); + expireStrategy = new FeelExpireStrategy(); } } /** * Expire this record */ - public void expire() { - this.damager = null; - this.isValid = false; - } + /** * If this entity is expired @@ -141,7 +134,7 @@ public void update(TimeStep timeStep) { */ public void clear() { for(int i = 0; i < this.feelingRecords.length; i++) { - this.feelingRecords[i].expire(); + this.feelingRecords[i].expireStrategy = new FeelExpireStrategy(); } } diff --git a/src/seventh/ai/basic/memory/MemoryRecord.java b/src/seventh/ai/basic/memory/MemoryRecord.java new file mode 100644 index 0000000..133628b --- /dev/null +++ b/src/seventh/ai/basic/memory/MemoryRecord.java @@ -0,0 +1,24 @@ +package seventh.ai.basic.memory; + +import seventh.ai.basic.memory.ExpireStrategy; + +public abstract class MemoryRecord { + protected final long expireTime; + protected boolean isValid; + ExpireStrategy expireStrategy; + public MemoryRecord(long expireTime) + { + this.expireTime = expireTime; + this.setValid(false); + } + public long getExpireTime() { + return expireTime; + } + public boolean isValid() { + return isValid; + } + public void setValid(boolean isValid) { + this.isValid = isValid; + } + +} \ No newline at end of file diff --git a/src/seventh/ai/basic/memory/SightExpireStrategy.java b/src/seventh/ai/basic/memory/SightExpireStrategy.java new file mode 100644 index 0000000..3f3f64f --- /dev/null +++ b/src/seventh/ai/basic/memory/SightExpireStrategy.java @@ -0,0 +1,22 @@ +package seventh.ai.basic.memory; + +import seventh.game.entities.PlayerEntity; +import seventh.game.weapons.Weapon; +import seventh.math.Vector2f; + +public class SightExpireStrategy implements ExpireStrategy { + + protected PlayerEntity entity; + protected Weapon lastSeenWithWeapon; + protected Vector2f lastSeenAt; + protected boolean isValid; + @Override + public void expire() { + this.entity = null; + this.lastSeenWithWeapon = null; + + this.lastSeenAt.zeroOut(); + this.isValid = false; + } + +} \ No newline at end of file diff --git a/src/seventh/ai/basic/memory/SightMemory.java b/src/seventh/ai/basic/memory/SightMemory.java index 3992ff8..4a96dfe 100644 --- a/src/seventh/ai/basic/memory/SightMemory.java +++ b/src/seventh/ai/basic/memory/SightMemory.java @@ -15,7 +15,7 @@ /** * Visual sight memory -- what this bot has seen, we store in a small cache so that he doesn't immediately forget the * world around him - * + * * * @author Tony * @@ -29,8 +29,7 @@ public class SightMemory implements Updatable { * @author Tony * */ - public static class SightMemoryRecord { - private final long expireTime; + public static class SightMemoryRecord extends MemoryRecord { private PlayerEntity entity; private Weapon lastSeenWithWeapon; @@ -38,15 +37,13 @@ public static class SightMemoryRecord { private long timeSeen; private long seenDelta; - private boolean isValid; /** * @param expireTime */ public SightMemoryRecord(long expireTime) { - this.expireTime = expireTime; + super(expireTime); this.lastSeenAt = new Vector2f(); - this.isValid = false; } @@ -82,20 +79,11 @@ public boolean isValid() { public void checkExpired(TimeStep timeStep) { this.seenDelta = timeStep.getGameClock() - this.timeSeen; if(isExpired(timeStep)) { - expire(); + expireStrategy = new SightExpireStrategy(); } } - /** - * Expire this record - */ - public void expire() { - this.entity = null; - this.lastSeenWithWeapon = null; - - this.lastSeenAt.zeroOut(); - this.isValid = false; - } + /** * If this entity is expired @@ -183,7 +171,7 @@ public void update(TimeStep timeStep) { */ public void clear() { for(int i = 0; i < this.entityRecords.length; i++) { - this.entityRecords[i].expire(); + this.entityRecords[i].expireStrategy = new SightExpireStrategy(); } } diff --git a/src/seventh/ai/basic/memory/SoundExpireStrategy.java b/src/seventh/ai/basic/memory/SoundExpireStrategy.java new file mode 100644 index 0000000..eabc8df --- /dev/null +++ b/src/seventh/ai/basic/memory/SoundExpireStrategy.java @@ -0,0 +1,16 @@ +package seventh.ai.basic.memory; + +import seventh.game.events.SoundEmittedEvent; +import seventh.shared.SoundType; + +public class SoundExpireStrategy implements ExpireStrategy{ + protected SoundEmittedEvent sound; + protected boolean isValid; + @Override + public void expire() { + this.sound.setId(-1); + this.sound.setSoundType(SoundType.MUTE); + this.isValid = false; + } + +} \ No newline at end of file diff --git a/src/seventh/ai/basic/memory/SoundMemory.java b/src/seventh/ai/basic/memory/SoundMemory.java index 9bd264e..6db0a37 100644 --- a/src/seventh/ai/basic/memory/SoundMemory.java +++ b/src/seventh/ai/basic/memory/SoundMemory.java @@ -17,7 +17,7 @@ /** * Sound memory -- what this bot has heard, we store in a small cache so that he doesn't immediately forget the * world around him - * + * * * @author Tony * @@ -31,20 +31,17 @@ public class SoundMemory implements Updatable { * @author Tony * */ - public static class SoundMemoryRecord { - private final long expireTime; + public static class SoundMemoryRecord extends MemoryRecord{ private long timeHeard; private long timeHeardAgo; private SoundEmittedEvent sound; - private boolean isValid; /** * @param expireTime */ public SoundMemoryRecord(long expireTime) { - this.expireTime = expireTime; - this.isValid = false; + super(expireTime); this.sound = new SoundEmittedEvent(this, 0, SoundType.MUTE, new Vector2f()); } @@ -79,19 +76,11 @@ public boolean isValid() { public void checkExpired(TimeStep timeStep) { this.timeHeardAgo = timeStep.getGameClock() - this.timeHeard; if(isExpired(timeStep)) { - expire(); + expireStrategy = new SoundExpireStrategy(); } } - /** - * Expire this record - */ - public void expire() { - this.sound.setId(-1); - this.sound.setSoundType(SoundType.MUTE); - this.isValid = false; - } - + /** * If this sound is expired * @@ -153,7 +142,7 @@ public void update(TimeStep timeStep) { */ public void clear() { for(int i = 0; i < this.soundRecords.length; i++) { - this.soundRecords[i].expire(); + this.soundRecords[i].expireStrategy = new SoundExpireStrategy(); } } From fd81bf8d2c3b4feb71d3347939fe86b0e42ce1c0 Mon Sep 17 00:00:00 2001 From: bananapizza Date: Sat, 9 Jun 2018 15:54:44 +0900 Subject: [PATCH 45/47] Apply design patterns - Observer, Template Method, Factory Method --- src/harenet/BitPacker.java | 55 ++----------------- src/harenet/BitStatement.java | 28 ++++++++++ src/harenet/ByteStatement.java | 28 ++++++++++ src/harenet/Statement.java | 48 ++++++++++++++++ src/harenet/StatementFactory.java | 10 ++++ .../ai/basic/actions/ActionSubject.java | 16 ++++++ 6 files changed, 136 insertions(+), 49 deletions(-) create mode 100644 src/harenet/BitStatement.java create mode 100644 src/harenet/ByteStatement.java create mode 100644 src/harenet/Statement.java create mode 100644 src/harenet/StatementFactory.java create mode 100644 src/seventh/ai/basic/actions/ActionSubject.java diff --git a/src/harenet/BitPacker.java b/src/harenet/BitPacker.java index 6e41085..2daab9b 100644 --- a/src/harenet/BitPacker.java +++ b/src/harenet/BitPacker.java @@ -533,58 +533,15 @@ public BitPacker pad() { public static void dumpBytes(byte[] value) { - System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); - System.out.println("| Dumping bytes, length: " + (value.length * 8) + " (" + value.length + " byte(s))"); - System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); - - int count = 0; - for (int j = 0; j < value.length; j++) { - - byte v = value[j]; - - for (int i = 0; i < Byte.SIZE; i++) { - if (((v >> i) & 1) == 1) { - System.out.print("1"); - } - else { - System.out.print("0"); - } - } - - System.out.print(" "); - count++; - if (count == 12) { - System.out.println(); - count = 0; - } - - } - System.out.println(); - System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); + StatementFactory statementFactory = new StatementFactory(); + Statement statement = statementFactory.getInstance(value); + statement.print(); } public void dump() { - System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); - System.out.println("| Dumping bitset, length: " + numBits); - System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); - - int count = 0; - - for (int i = 0; i < numBits; i++) { - System.out.print(data.getBit(i) ? "1" : "0"); - if ((i != 0) && (i % 8 == 7)) { - System.out.print(" "); - count++; - if (count == 12) { - System.out.println(); - count = 0; - } - - } - - } - System.out.println(); - System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); + StatementFactory statementFactory = new StatementFactory(); + Statement statement = statementFactory.getInstance(numBits,data); + statement.print(); } } \ No newline at end of file diff --git a/src/harenet/BitStatement.java b/src/harenet/BitStatement.java new file mode 100644 index 0000000..8a74ea6 --- /dev/null +++ b/src/harenet/BitStatement.java @@ -0,0 +1,28 @@ +package harenet; + +public class BitStatement extends Statement { + private int numBits; + private BitArray data; + + public BitStatement(int number,BitArray bitData) { + numBits = number; + data = bitData; + } + + protected void printHeaderContents() { + System.out.println("| Dumping bitset, length: " + numBits); + } + + public void printBody() { + int count = 0; + + for (int i = 0; i < numBits; i++) { + printBit(data.getBit(i)); + if ((i != 0) && (i % 8 == 7)) { + count = countProcess(count); + } + + } + } + +} diff --git a/src/harenet/ByteStatement.java b/src/harenet/ByteStatement.java new file mode 100644 index 0000000..e43ddc4 --- /dev/null +++ b/src/harenet/ByteStatement.java @@ -0,0 +1,28 @@ +package harenet; + +public class ByteStatement extends Statement { + private byte[] value; + + public ByteStatement(byte[] byteValue) { + value = byteValue; + } + + protected void printHeaderContents() { + System.out.println("| Dumping bytes, length: " + (value.length * 8) + " (" + value.length + " byte(s))"); + } + + public void printBody() { + int count = 0; + for (int j = 0; j < value.length; j++) { + + byte v = value[j]; + + for (int i = 0; i < Byte.SIZE; i++) { + printBit(((v >> i) & 1) == 1); + } + + count = countProcess(count); + + } + } +} diff --git a/src/harenet/Statement.java b/src/harenet/Statement.java new file mode 100644 index 0000000..3cc6c1b --- /dev/null +++ b/src/harenet/Statement.java @@ -0,0 +1,48 @@ +package harenet; + +public abstract class Statement { + public void print() { + printHeader(); + printBody(); + printFooter(); + } + + public void printHeader() { + printLine(); + printHeaderContents(); + printLine(); + } + + public abstract void printBody(); + + public void printFooter() { + System.out.println(); + printLine(); + } + + private void printLine() { + System.out.println("+--------------- ------------- ------- ------ --- -- -- - -- -- --"); + } + + protected abstract void printHeaderContents(); + + protected void printBit(boolean isOne) { + if (isOne) { + System.out.print("1"); + } + else { + System.out.print("0"); + } + } + + protected int countProcess(int count) { + int tempCount = count; + System.out.print(" "); + tempCount++; + if (tempCount == 12) { + System.out.println(); + tempCount = 0; + } + return tempCount; + } +} diff --git a/src/harenet/StatementFactory.java b/src/harenet/StatementFactory.java new file mode 100644 index 0000000..00a2940 --- /dev/null +++ b/src/harenet/StatementFactory.java @@ -0,0 +1,10 @@ +package harenet; + +public class StatementFactory { + public Statement getInstance(byte[] value) { + return new ByteStatement(value); + } + public Statement getInstance(int numBits, BitArray data) { + return new BitStatement(numBits,data); + } +} diff --git a/src/seventh/ai/basic/actions/ActionSubject.java b/src/seventh/ai/basic/actions/ActionSubject.java new file mode 100644 index 0000000..2e8cef1 --- /dev/null +++ b/src/seventh/ai/basic/actions/ActionSubject.java @@ -0,0 +1,16 @@ +package seventh.ai.basic.actions; + +import java.util.List; +import java.util.ArrayList; +import seventh.ai.basic.Brain; +import seventh.shared.TimeStep; + +public abstract class ActionSubject { + private List actions = new ArrayList(); + public void attach(Action action) { actions.add(action); } + public void detach(Action action) { actions.remove(action); } + public void notifyActions(Brain brain, TimeStep timeStep) { + for(Action action : actions) + action.update(brain, timeStep); + } +} From adb6954049893b1773efb3baf558488b574ad1b3 Mon Sep 17 00:00:00 2001 From: virginbabylon Date: Tue, 12 Jun 2018 08:22:04 +0900 Subject: [PATCH 46/47] tab -> 4 spaces --- .../ai/basic/memory/FeelExpireStrategy.java | 11 ++++----- src/seventh/ai/basic/memory/MemoryRecord.java | 23 +++++++++---------- .../ai/basic/memory/SightExpireStrategy.java | 20 ++++++++-------- .../ai/basic/memory/SoundExpireStrategy.java | 9 ++++---- 4 files changed, 28 insertions(+), 35 deletions(-) diff --git a/src/seventh/ai/basic/memory/FeelExpireStrategy.java b/src/seventh/ai/basic/memory/FeelExpireStrategy.java index ba4dec2..2a06c7b 100644 --- a/src/seventh/ai/basic/memory/FeelExpireStrategy.java +++ b/src/seventh/ai/basic/memory/FeelExpireStrategy.java @@ -3,14 +3,11 @@ import seventh.game.entities.Entity; public class FeelExpireStrategy implements ExpireStrategy{ - protected Entity damager; protected boolean isValid; - @Override - public void expire() { - this.damager = null; + @Override + public void expire() { + this.damager = null; this.isValid = false; - } - - + } } \ No newline at end of file diff --git a/src/seventh/ai/basic/memory/MemoryRecord.java b/src/seventh/ai/basic/memory/MemoryRecord.java index 133628b..fd19478 100644 --- a/src/seventh/ai/basic/memory/MemoryRecord.java +++ b/src/seventh/ai/basic/memory/MemoryRecord.java @@ -8,17 +8,16 @@ public abstract class MemoryRecord { ExpireStrategy expireStrategy; public MemoryRecord(long expireTime) { - this.expireTime = expireTime; - this.setValid(false); + this.expireTime = expireTime; + this.setValid(false); + } + public long getExpireTime() { + return expireTime; + } + public boolean isValid() { + return isValid; + } + public void setValid(boolean isValid) { + this.isValid = isValid; } - public long getExpireTime() { - return expireTime; - } - public boolean isValid() { - return isValid; - } - public void setValid(boolean isValid) { - this.isValid = isValid; - } - } \ No newline at end of file diff --git a/src/seventh/ai/basic/memory/SightExpireStrategy.java b/src/seventh/ai/basic/memory/SightExpireStrategy.java index 3f3f64f..b615b81 100644 --- a/src/seventh/ai/basic/memory/SightExpireStrategy.java +++ b/src/seventh/ai/basic/memory/SightExpireStrategy.java @@ -6,17 +6,15 @@ public class SightExpireStrategy implements ExpireStrategy { - protected PlayerEntity entity; - protected Weapon lastSeenWithWeapon; + protected PlayerEntity entity; + protected Weapon lastSeenWithWeapon; protected Vector2f lastSeenAt; protected boolean isValid; - @Override - public void expire() { - this.entity = null; - this.lastSeenWithWeapon = null; - - this.lastSeenAt.zeroOut(); - this.isValid = false; - } - + @Override + public void expire() { + this.entity = null; + this.lastSeenWithWeapon = null; + this.lastSeenAt.zeroOut(); + this.isValid = false; + } } \ No newline at end of file diff --git a/src/seventh/ai/basic/memory/SoundExpireStrategy.java b/src/seventh/ai/basic/memory/SoundExpireStrategy.java index eabc8df..71f1617 100644 --- a/src/seventh/ai/basic/memory/SoundExpireStrategy.java +++ b/src/seventh/ai/basic/memory/SoundExpireStrategy.java @@ -6,11 +6,10 @@ public class SoundExpireStrategy implements ExpireStrategy{ protected SoundEmittedEvent sound; protected boolean isValid; - @Override - public void expire() { - this.sound.setId(-1); + @Override + public void expire() { + this.sound.setId(-1); this.sound.setSoundType(SoundType.MUTE); this.isValid = false; - } - + } } \ No newline at end of file From 913256b632214cc04572b54ab478dd82872f90fd Mon Sep 17 00:00:00 2001 From: bananapizza Date: Tue, 12 Jun 2018 11:34:11 +0900 Subject: [PATCH 47/47] Change tab to 4 spaces --- src/harenet/BitPacker.java | 6 +++--- src/harenet/BitStatement.java | 11 +++++------ src/harenet/ByteStatement.java | 16 ++++++++-------- src/harenet/Statement.java | 4 ++-- src/harenet/StatementFactory.java | 2 +- 5 files changed, 19 insertions(+), 20 deletions(-) diff --git a/src/harenet/BitPacker.java b/src/harenet/BitPacker.java index 2daab9b..7f62ec1 100644 --- a/src/harenet/BitPacker.java +++ b/src/harenet/BitPacker.java @@ -530,16 +530,16 @@ public BitPacker pad() { return this; } - + public static void dumpBytes(byte[] value) { - StatementFactory statementFactory = new StatementFactory(); + StatementFactory statementFactory = new StatementFactory(); Statement statement = statementFactory.getInstance(value); statement.print(); } public void dump() { - StatementFactory statementFactory = new StatementFactory(); + StatementFactory statementFactory = new StatementFactory(); Statement statement = statementFactory.getInstance(numBits,data); statement.print(); } diff --git a/src/harenet/BitStatement.java b/src/harenet/BitStatement.java index 8a74ea6..262e8b0 100644 --- a/src/harenet/BitStatement.java +++ b/src/harenet/BitStatement.java @@ -5,16 +5,16 @@ public class BitStatement extends Statement { private BitArray data; public BitStatement(int number,BitArray bitData) { - numBits = number; - data = bitData; - } - + numBits = number; + data = bitData; + } + protected void printHeaderContents() { System.out.println("| Dumping bitset, length: " + numBits); } public void printBody() { - int count = 0; + int count = 0; for (int i = 0; i < numBits; i++) { printBit(data.getBit(i)); @@ -24,5 +24,4 @@ public void printBody() { } } - } diff --git a/src/harenet/ByteStatement.java b/src/harenet/ByteStatement.java index e43ddc4..35170a4 100644 --- a/src/harenet/ByteStatement.java +++ b/src/harenet/ByteStatement.java @@ -1,18 +1,18 @@ package harenet; public class ByteStatement extends Statement { - private byte[] value; + private byte[] value; - public ByteStatement(byte[] byteValue) { - value = byteValue; - } - - protected void printHeaderContents() { + public ByteStatement(byte[] byteValue) { + value = byteValue; + } + + protected void printHeaderContents() { System.out.println("| Dumping bytes, length: " + (value.length * 8) + " (" + value.length + " byte(s))"); } - + public void printBody() { - int count = 0; + int count = 0; for (int j = 0; j < value.length; j++) { byte v = value[j]; diff --git a/src/harenet/Statement.java b/src/harenet/Statement.java index 3cc6c1b..b3923b1 100644 --- a/src/harenet/Statement.java +++ b/src/harenet/Statement.java @@ -27,7 +27,7 @@ private void printLine() { protected abstract void printHeaderContents(); protected void printBit(boolean isOne) { - if (isOne) { + if (isOne) { System.out.print("1"); } else { @@ -44,5 +44,5 @@ protected int countProcess(int count) { tempCount = 0; } return tempCount; - } + } } diff --git a/src/harenet/StatementFactory.java b/src/harenet/StatementFactory.java index 00a2940..31ad3f6 100644 --- a/src/harenet/StatementFactory.java +++ b/src/harenet/StatementFactory.java @@ -7,4 +7,4 @@ public Statement getInstance(byte[] value) { public Statement getInstance(int numBits, BitArray data) { return new BitStatement(numBits,data); } -} +} \ No newline at end of file