file_id
int64 1
250k
| content
stringlengths 0
562k
| repo
stringlengths 6
115
| path
stringlengths 1
147
|
---|---|---|---|
249,054 | public class Link implements Comparable<Link>{
public String ref;
public int weight;
public Link(String ref) {
this.ref=ref;
weight=1;
}
public Link(String ref, int weight) {
this.ref=ref;
this.weight=weight;
}
@Override
public boolean equals(Object obj) {
return ((Link)obj).ref.equalsIgnoreCase(ref);
}
@Override
public String toString() {
return ref+"("+weight+")";
}
@Override
public int compareTo(Link another) {
return ref.compareTo(another.ref);
}
}
| GrunCrow/Data-Structures-and-Algorithms | Laboratory 8/Laboratory 8/src/Link.java |
249,055 | // ****************************************************************************
//
// Copyright (c) 2000 - 2014, Lawrence Livermore National Security, LLC
// Produced at the Lawrence Livermore National Laboratory
// LLNL-CODE-442911
// All rights reserved.
//
// This file is part of VisIt. For details, see https://visit.llnl.gov/. The
// full copyright notice is contained in the file COPYRIGHT located at the root
// of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the disclaimer below.
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the disclaimer (as noted below) in the
// documentation and/or other materials provided with the distribution.
// - Neither the name of the LLNS/LLNL nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY,
// LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ****************************************************************************
import java.lang.ArrayIndexOutOfBoundsException;
import llnl.visit.avtDatabaseMetaData;
// ****************************************************************************
// Class: GetMetaData
//
// Purpose:
// This example program opens a database and gets the metadata, printing
// it to the console.
//
// Notes:
//
// Programmer: Brad Whitlock
// Creation: Mon Feb 25 12:01:43 PDT 2008
//
// Modifications:
//
// ****************************************************************************
public class GetMetaData extends RunViewer
{
public GetMetaData()
{
super();
}
protected void work(String[] args)
{
// Try and open a database
if(viewer.GetViewerMethods().RequestMetaData(viewer.GetDataPath() + "noise.silo",0))
{
avtDatabaseMetaData md = viewer.GetViewerState().GetDatabaseMetaData();
System.out.print(md.toString());
}
else
System.out.println("Could not get the metadata for the database!");
}
public static void main(String args[])
{
GetMetaData r = new GetMetaData();
r.run(args);
}
}
| ahota/visit_intel | java/GetMetaData.java |
249,056 | package gen6;
import battlecode.common.*;
import gen6.builder.BuildingHelper;
import gen6.builder.FarmingHelper;
import gen6.common.CommsHelper;
import gen6.common.MovementHelper;
import gen6.builder.MutationHelper;
import gen6.builder.BuilderType;
import gen6.common.util.LogCondition;
import gen6.common.util.Logger;
import gen6.common.util.Pair;
import gen6.sage.SageMovementHelper;
import static gen6.RobotPlayer.*;
import static gen6.common.Functions.*;
public strictfp class Builder {
public static class ConstructionInfo {
public MapLocation location;
public RobotType type;
public ConstructionInfo(RobotType t, MapLocation loc) {
type = t;
location = loc;
}
}
public static MapLocation myArchonLocation;
public static Direction myDirection;
public static int myArchonIndex;
private static ConstructionInfo nextBuilding;
private static ConstructionInfo constructedBuilding = null;
public static BuilderType myBuilderType;
private static MapLocation farmCenter = null;
private static void act() throws GameActionException {
MapLocation rn = rc.getLocation();
if (myBuilderType == BuilderType.FarmSeed && FarmingHelper.isLocationInFarm(rn) && rc.senseLead(rn) == 0) {
rc.disintegrate();
return;
}
Pair<MapLocation, Boolean> mutate = MutationHelper.getLocationToMutate();
if (mutate != null) {
if (mutate.b) {
if (rc.canMutate(mutate.a)) {
rc.mutate(mutate.a);
return;
}
} else {
MovementHelper.tryMove(rc.getLocation().directionTo(mutate.a), false);
}
}
MapLocation repair = BuildingHelper.getRepairLocation();
if (repair != null && rc.canRepair(repair)) {
rc.repair(repair);
return;
}
if (nextBuilding != null) {
Direction buildDirection = rc.getLocation().directionTo(nextBuilding.location);
if (
rc.getLocation().isWithinDistanceSquared(nextBuilding.location, 2)
) {
boolean highRubble = rc.senseRubble(nextBuilding.location) > 30;
if (rc.canBuildRobot(nextBuilding.type, buildDirection) && !highRubble) {
rc.buildRobot(nextBuilding.type, buildDirection);
switch (nextBuilding.type) {
case WATCHTOWER:
CommsHelper.incrementWatchtowersBuilt(myArchonIndex);
break;
case LABORATORY:
CommsHelper.updateLabBuilt(myArchonIndex);
}
constructedBuilding = nextBuilding;
nextBuilding = null;
} else if (nextBuilding.type == RobotType.LABORATORY) {
MapLocation req = nextBuilding.location;
RobotInfo lab = rc.senseRobotAtLocation(req);
Direction antiRight = getDirectionAlongEdge(true, 5),
antiLeft = getDirectionAlongEdge(false, 5);
if (
(lab != null && lab.mode == RobotMode.TURRET || highRubble)
&& antiRight != null && antiLeft != null
) {
MapLocation left = req.add(antiLeft), right = req.add(antiRight);
for (int d = 1; d < 4; d++) {
if (rc.canSenseLocation(left)) {
lab = rc.senseRobotAtLocation(left);
if ((lab == null || lab.mode != RobotMode.TURRET) && rc.senseRubble(left) <= 30) {
nextBuilding = new ConstructionInfo(
RobotType.LABORATORY, left
);
break;
}
}
if (rc.canSenseLocation(right)) {
lab = rc.senseRobotAtLocation(right);
if ((lab == null || lab.mode != RobotMode.TURRET) && rc.senseRubble(right) <= 30) {
nextBuilding = new ConstructionInfo(
RobotType.LABORATORY, right
);
break;
}
}
left = left.add(antiLeft);
right = right.add(antiRight);
}
}
}
} else {
MovementHelper.tryMove(buildDirection,
rc.getLocation().isWithinDistanceSquared(nextBuilding.location, 5));
}
}
}
private static boolean move() throws GameActionException {
if (!rc.isMovementReady()) {
return false;
}
if (myBuilderType == BuilderType.FarmSeed) {
MapLocation ml = FarmingHelper.getBaldSpot();
if (ml != null) {
return MovementHelper.tryMove(ml, false);
}
} else {
MapLocation repair = BuildingHelper.getRepairLocation();
if (repair != null) {
return MovementHelper.tryMove(repair, false);
}
}
SageMovementHelper.defenseRevolution(myArchonLocation);
return true;
}
public static void mutateLab() throws GameActionException{
if (constructedBuilding == null) {
return;
}
MapLocation my = rc.getLocation();
if (!my.isWithinDistanceSquared(constructedBuilding.location, myType.actionRadiusSquared)) {
if (rc.isMovementReady()) {
MovementHelper.tryMove(my, false);
}
}
if (!my.isWithinDistanceSquared(constructedBuilding.location, myType.actionRadiusSquared)) {
return;
}
RobotInfo lab = rc.senseRobotAtLocation(constructedBuilding.location);
if (lab == null) {
constructedBuilding = null;
return;
}
if (rc.canMutate(lab.location)) {
rc.mutate(lab.location);
if (lab.level == 3) {
constructedBuilding = null;
}
}
}
public static void run() throws GameActionException {
// update location each round
myArchonLocation = CommsHelper.getArchonLocation(myArchonIndex);
if (rc.getRoundNum() > 1150 && rc.getRoundNum() < 1425 && myBuilderType != BuilderType.FarmSeed) {
mutateLab();
}
if (rc.isActionReady()) {
act();
}
MapLocation construction = null;
if (nextBuilding != null && rc.getTeamLeadAmount(myTeam) > nextBuilding.type.buildCostLead) {
construction = nextBuilding.location;
}
if (rc.isMovementReady() && BuildingHelper.shouldMove(myArchonLocation, construction)) {
move();
}
}
public static void init() throws GameActionException {
maxArchonCount = 0;
MovementHelper.prepareBellmanFord(20);
for (int i = 0; i < 4; ++i) {
int value = rc.readSharedArray(i + 32);
if (getBits(value, 15, 15) == 1) {
++maxArchonCount;
value = rc.readSharedArray(i + 50);
MapLocation archonLocation = new MapLocation(
getBits(value, 6, 11), getBits(value, 0, 5)
);
if (rc.getLocation().distanceSquaredTo(archonLocation) <= 2) {
myArchonLocation = archonLocation;
myArchonIndex = i;
nextBuilding = BuildingHelper.getNextConstruction();
farmCenter = FarmingHelper.getFarmCenter();
}
} else {
break;
}
}
}
}
| dernosmirc/battlecode-2022 | src/gen6/Builder.java |
249,057 | package gen5;
import battlecode.common.*;
import gen5.builder.BuildingHelper;
import gen5.common.CommsHelper;
import gen5.common.MovementHelper;
import gen5.builder.MutationHelper;
import gen5.builder.BuilderType;
import gen5.common.util.Logger;
import gen5.common.util.Pair;
import gen5.sage.SageMovementHelper;
import static gen5.RobotPlayer.*;
import static gen5.common.Functions.getAntiEdgeDirection;
import static gen5.common.Functions.getBits;
public strictfp class Builder {
public static class ConstructionInfo {
public MapLocation location;
public RobotType type;
public ConstructionInfo(RobotType t, MapLocation loc) {
type = t;
location = loc;
}
}
public static MapLocation myArchonLocation;
public static Direction myDirection;
public static int myArchonIndex;
private static ConstructionInfo nextBuilding;
private static ConstructionInfo constructedBuilding = null;
public static BuilderType myBuilderType;
private static void act() throws GameActionException {
Pair<MapLocation, Boolean> mutate = MutationHelper.getLocationToMutate();
if (mutate != null) {
if (mutate.b) {
if (rc.canMutate(mutate.a)) {
rc.mutate(mutate.a);
return;
}
} else {
MovementHelper.tryMove(rc.getLocation().directionTo(mutate.a), false);
}
}
MapLocation repair = BuildingHelper.getRepairLocation();
if (repair != null && rc.canRepair(repair)) {
rc.repair(repair);
return;
}
if (nextBuilding != null) {
Direction buildDirection = rc.getLocation().directionTo(nextBuilding.location);
if (
rc.getLocation().isWithinDistanceSquared(nextBuilding.location, 2)
) {
if (rc.canBuildRobot(nextBuilding.type, buildDirection)) {
rc.buildRobot(nextBuilding.type, buildDirection);
switch (nextBuilding.type) {
case WATCHTOWER:
CommsHelper.incrementWatchtowersBuilt(myArchonIndex);
break;
case LABORATORY:
CommsHelper.updateLabBuilt(myArchonIndex);
}
constructedBuilding = nextBuilding;
nextBuilding = null;
} else if (nextBuilding.type == RobotType.LABORATORY) {
MapLocation req = nextBuilding.location;
RobotInfo lab = rc.senseRobotAtLocation(req);
Direction anti = getAntiEdgeDirection();
if (lab != null && lab.type == RobotType.LABORATORY && anti != null) {
nextBuilding = new ConstructionInfo(
RobotType.LABORATORY, req.add(anti)
);
}
}
} else {
MovementHelper.tryMove(buildDirection,
rc.getLocation().isWithinDistanceSquared(nextBuilding.location, 5));
}
}
}
private static boolean move() throws GameActionException {
Direction direction = BuildingHelper.getAntiArchonDirection(myArchonLocation);
if (direction != null) {
return MovementHelper.tryMove(direction, false);
}
MapLocation repair = BuildingHelper.getRepairLocation();
if (repair != null) {
return MovementHelper.moveBellmanFord(repair);
}
SageMovementHelper.defenseRevolution(myArchonLocation);
return true;
}
public static void mutateLab() throws GameActionException{
if (constructedBuilding == null) {
return;
}
MapLocation my = rc.getLocation();
if (!my.isWithinDistanceSquared(constructedBuilding.location, myType.actionRadiusSquared)) {
if (rc.isMovementReady()) {
MovementHelper.moveBellmanFord(my);
}
}
if (!my.isWithinDistanceSquared(constructedBuilding.location, myType.actionRadiusSquared)) {
return;
}
RobotInfo lab = rc.senseRobotAtLocation(constructedBuilding.location);
if (lab == null) {
constructedBuilding = null;
return;
}
if (rc.canMutate(lab.location)) {
rc.mutate(lab.location);
if (lab.level == 3) {
constructedBuilding = null;
}
}
}
public static void run() throws GameActionException {
rc.setIndicatorString(myBuilderType.name() + ", constr=" + (constructedBuilding != null) + ", next" + (nextBuilding != null));
Logger logger = new Logger("Builder", true);
if (rc.getRoundNum() > 1150 && rc.getRoundNum() < 1425){
mutateLab();
}
if (rc.isActionReady()) {
act();
}
MapLocation construction = null;
if (nextBuilding != null && rc.getTeamLeadAmount(myTeam) > nextBuilding.type.buildCostLead) {
construction = nextBuilding.location;
}
if (rc.isMovementReady() && BuildingHelper.shouldMove(myArchonLocation, construction)) {
move();
}
logger.flush();
}
public static void init() throws GameActionException {
maxArchonCount = 0;
MovementHelper.prepareBellmanFord(13);
for (int i = 32; i < 36; ++i) {
int value = rc.readSharedArray(i);
if (getBits(value, 15, 15) == 1) {
++maxArchonCount;
MapLocation archonLocation = new MapLocation(
getBits(value, 6, 11), getBits(value, 0, 5)
);
if (rc.getLocation().distanceSquaredTo(archonLocation) <= 2) {
myArchonLocation = new MapLocation(archonLocation.x, archonLocation.y);
myArchonIndex = i - 32;
nextBuilding = BuildingHelper.getNextConstruction();
}
} else {
break;
}
}
}
}
| dernosmirc/battlecode-2022 | src/gen5/Builder.java |
249,058 | package gen8;
import battlecode.common.*;
import gen8.builder.BuildingHelper;
import gen8.builder.FarmingHelper;
import gen8.common.CommsHelper;
import gen8.common.MovementHelper;
import gen8.builder.MutationHelper;
import gen8.builder.BuilderType;
import gen8.common.bellmanford.BellmanFord;
import gen8.common.util.Pair;
import gen8.sage.SageMovementHelper;
import gen8.soldier.TailHelper;
import gen8.miner.GoldMiningHelper;
import gen8.miner.LeadMiningHelper;
import static gen8.RobotPlayer.*;
import static gen8.common.Functions.*;
public strictfp class Builder {
public static class ConstructionInfo {
public MapLocation location;
public RobotType type;
public ConstructionInfo(RobotType t, MapLocation loc) {
type = t;
location = loc;
}
}
private static final int LAB_RUBBLE_THRESHOLD = 20;
public static MapLocation myArchonLocation;
public static Direction myDirection;
public static int myArchonIndex;
private static ConstructionInfo nextBuilding;
private static ConstructionInfo constructedBuilding = null;
public static BuilderType myBuilderType;
private static MapLocation farmCenter = null;
private static boolean amEarlyBuilder = false;
private static MapLocation labLocation = null;
private static boolean moveTowards(MapLocation ml) throws GameActionException {
if (rc.getLocation().isWithinDistanceSquared(ml, myType.actionRadiusSquared)) {
MovementHelper.lazyMove(ml);
return true;
}
if (rc.getLocation().isWithinDistanceSquared(ml, 5)) {
return MovementHelper.tryMove(ml, false);
}
return MovementHelper.moveBellmanFord(ml);
}
private static void act() throws GameActionException {
MapLocation rn = rc.getLocation();
if (!amEarlyBuilder && myBuilderType == BuilderType.FarmSeed
&& FarmingHelper.isLocationInFarm(rn) && rc.senseLead(rn) == 0) {
rc.disintegrate();
return;
}
Pair<MapLocation, Boolean> mutate = MutationHelper.getLocationToMutate();
if (mutate != null) {
if (mutate.b) {
if (rc.canMutate(mutate.a)) {
rc.mutate(mutate.a);
return;
}
} else {
moveTowards(mutate.a);
}
}
MapLocation repair = BuildingHelper.getRepairLocation();
if (repair != null && rc.canRepair(repair)) {
rc.repair(repair);
return;
}
if (amEarlyBuilder) {
if (labLocation != null && rc.getLocation().isAdjacentTo(labLocation)) {
RobotInfo lab = rc.senseRobotAtLocation(labLocation);
if (lab != null && lab.type == RobotType.LABORATORY && lab.team == myTeam) {
if (lab.health == lab.type.getMaxHealth(lab.level)) {
labLocation = null;
} else {
return;
}
}
}
if (rc.getTeamLeadAmount(myTeam) < RobotType.LABORATORY.buildCostLead - 80) {
MapLocation nearestCorner = BuildingHelper.getNearestCorner(myArchonIndex);
if (rc.getLocation().isWithinDistanceSquared(nearestCorner, 13)) {
labLocation = BuildingHelper.getOptimalEarlyLabLocation();
if (rc.isMovementReady()) {
moveTowards(labLocation);
}
} else {
labLocation = null;
if (rc.isMovementReady()) {
moveTowards(nearestCorner);
}
}
return;
}
if (rc.getTeamLeadAmount(myTeam) >= RobotType.LABORATORY.buildCostLead) {
int minRubble = 1000;
Direction optimalDirection = null;
int minEdgeDistance1 = rc.getMapWidth() * rc.getMapHeight();
int minEdgeDistance2 = minEdgeDistance1;
for (int i = directions.length; --i >= 0; ) {
Direction dir = directions[i];
if (rc.canBuildRobot(RobotType.LABORATORY, dir)) {
MapLocation location = rc.getLocation().add(dir);
int rubble = rc.senseRubble(location);
if (rubble < minRubble) {
minRubble = rubble;
optimalDirection = dir;
minEdgeDistance1 = BuildingHelper.getDistanceFromEdge(location);
minEdgeDistance2 = BuildingHelper.getLargerDistanceFromEdge(location);
} else if (rubble == minRubble) {
int edgeDistance1 = BuildingHelper.getDistanceFromEdge(location);
int edgeDistance2 = BuildingHelper.getLargerDistanceFromEdge(location);
if (edgeDistance1 < minEdgeDistance1) {
minRubble = rubble;
optimalDirection = dir;
minEdgeDistance1 = edgeDistance1;
minEdgeDistance2 = edgeDistance2;
} else if (edgeDistance1 == minEdgeDistance1 && edgeDistance2 < minEdgeDistance2) {
minRubble = rubble;
optimalDirection = dir;
minEdgeDistance1 = edgeDistance1;
minEdgeDistance2 = edgeDistance2;
}
}
}
}
if (optimalDirection != null && rc.canBuildRobot(RobotType.LABORATORY, optimalDirection)) {
rc.buildRobot(RobotType.LABORATORY, optimalDirection);
labLocation = rc.getLocation().add(optimalDirection);
CommsHelper.updateLabBuilt(myArchonIndex);
}
return;
}
if (labLocation == null) {
labLocation = BuildingHelper.getOptimalEarlyLabLocation();
}
if (rc.getLocation().equals(labLocation)) {
int minRubble = 1000;
Direction optimalDirection = null;
for (int i = directions.length; --i >= 0; ) {
Direction dir = directions[i];
MapLocation location = rc.getLocation().add(dir);
if (rc.canMove(dir)) {
int rubble = rc.senseRubble(location);
if (rubble < minRubble) {
minRubble = rubble;
optimalDirection = dir;
}
}
}
if (optimalDirection != null && rc.canMove(optimalDirection)) {
MovementHelper.tryMove(optimalDirection, true);
}
} else if (!rc.getLocation().isAdjacentTo(labLocation)) {
moveTowards(labLocation);
}
return;
}
if (nextBuilding != null) {
if (
rc.getLocation().isWithinDistanceSquared(nextBuilding.location, 2)
) {
Direction buildDirection = rc.getLocation().directionTo(nextBuilding.location);
boolean highRubble = rc.senseRubble(nextBuilding.location) > LAB_RUBBLE_THRESHOLD;
if (rc.canBuildRobot(nextBuilding.type, buildDirection) && !highRubble) {
rc.buildRobot(nextBuilding.type, buildDirection);
switch (nextBuilding.type) {
case WATCHTOWER:
CommsHelper.incrementWatchtowersBuilt(myArchonIndex);
break;
case LABORATORY:
CommsHelper.updateLabBuilt(myArchonIndex);
}
constructedBuilding = nextBuilding;
nextBuilding = null;
} else if (nextBuilding.type == RobotType.LABORATORY) {
MapLocation req = nextBuilding.location;
RobotInfo lab = rc.senseRobotAtLocation(req);
Direction antiRight = getDirectionAlongEdge(true, 5, false),
antiLeft = getDirectionAlongEdge(false, 5, false);
if (
(lab != null && lab.mode == RobotMode.TURRET || highRubble)
&& antiRight != null && antiLeft != null
) {
MapLocation left = req.add(antiLeft), right = req.add(antiRight);
for (int d = 1; d < 4; d++) {
if (rc.canSenseLocation(left)) {
lab = rc.senseRobotAtLocation(left);
if ((lab == null || lab.mode != RobotMode.TURRET) && rc.senseRubble(left) <= LAB_RUBBLE_THRESHOLD) {
nextBuilding = new ConstructionInfo(
RobotType.LABORATORY, left
);
break;
}
}
if (rc.canSenseLocation(right)) {
lab = rc.senseRobotAtLocation(right);
if ((lab == null || lab.mode != RobotMode.TURRET) && rc.senseRubble(right) <= LAB_RUBBLE_THRESHOLD) {
nextBuilding = new ConstructionInfo(
RobotType.LABORATORY, right
);
break;
}
}
left = left.add(antiLeft);
right = right.add(antiRight);
}
}
}
} else {
moveTowards(nextBuilding.location);
}
}
}
private static boolean move() throws GameActionException {
if (myBuilderType == BuilderType.FarmSeed) {
MapLocation ml = FarmingHelper.getBaldSpot();
if (ml != null) {
return MovementHelper.moveBellmanFord(ml);
}
} else {
MapLocation repair = BuildingHelper.getRepairLocation();
if (repair != null) {
return moveTowards(repair);
}
}
if (myArchonLocation != null) {
SageMovementHelper.defenseRevolution(myArchonLocation);
return true;
}
return false;
}
public static void mutateLab() throws GameActionException{
if (constructedBuilding == null) {
return;
}
MapLocation my = rc.getLocation();
if (!my.isWithinDistanceSquared(constructedBuilding.location, myType.actionRadiusSquared)) {
if (rc.isMovementReady()) {
moveTowards(my);
}
}
if (!my.isWithinDistanceSquared(constructedBuilding.location, myType.actionRadiusSquared)) {
return;
}
RobotInfo lab = rc.senseRobotAtLocation(constructedBuilding.location);
if (lab == null) {
constructedBuilding = null;
return;
}
if (rc.canMutate(lab.location)) {
rc.mutate(lab.location);
if (lab.level == 3) {
constructedBuilding = null;
}
}
}
public static void run() throws GameActionException {
// Update the builder count
// if (rc.getRoundNum()%2 == 1){
// rc.writeSharedArray(25, rc.readSharedArray(25) + 1);
// }
if (amEarlyBuilder){
rc.writeSharedArray(25, setBits(rc.readSharedArray(25), 15, 15, 1));
}
TailHelper.updateTarget();
if (!rc.isMovementReady()) {
BellmanFord.fillArrays();
}
// update location each round
myArchonLocation = CommsHelper.getArchonLocation(myArchonIndex);
if (rc.getRoundNum() > 1150 && rc.getRoundNum() < 1425 && myBuilderType != BuilderType.FarmSeed) {
mutateLab();
}
if (rc.isActionReady() || amEarlyBuilder) {
act();
}
if (amEarlyBuilder) {
GoldMiningHelper.updateGoldAmountInGridCell();
if (Clock.getBytecodesLeft() >= 4500) {
LeadMiningHelper.updateLeadAmountInGridCell();
}
return;
}
if (rc.isMovementReady()) {
move();
}
GoldMiningHelper.updateGoldAmountInGridCell();
if (Clock.getBytecodesLeft() >= 4500) {
LeadMiningHelper.updateLeadAmountInGridCell();
}
}
public static void init() throws GameActionException {
maxArchonCount = 0;
amEarlyBuilder = CommsHelper.isEarlyBuilder();
MovementHelper.prepareBellmanFord(20);
for (int i = 0; i < 4; ++i) {
int value = rc.readSharedArray(i + 32);
if (getBits(value, 15, 15) == 1) {
++maxArchonCount;
value = rc.readSharedArray(i + 50);
MapLocation archonLocation = new MapLocation(
getBits(value, 6, 11), getBits(value, 0, 5)
);
if (rc.getLocation().distanceSquaredTo(archonLocation) <= 2) {
myArchonLocation = archonLocation;
myArchonIndex = i;
nextBuilding = BuildingHelper.getNextConstruction();
farmCenter = FarmingHelper.getFarmCenter();
}
} else {
break;
}
}
}
}
| dernosmirc/battlecode-2022 | src/gen8/Builder.java |
249,059 | /*
The file is derived from Contrail Project which is developed by Michael Schatz,
Jeremy Chambers, Avijit Gupta, Rushil Gupta, David Kelley, Jeremy Lewi,
Deepak Nettem, Dan Sommer, Mihai Pop, Schatz Lab and Cold Spring Harbor Laboratory,
and is released under Apache License 2.0 at:
http://sourceforge.net/apps/mediawiki/contrail-bio/
*/
package Brush;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Collections;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.FloatWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.FileInputFormat;
import org.apache.hadoop.mapred.FileOutputFormat;
import org.apache.hadoop.mapred.JobClient;
import org.apache.hadoop.mapred.JobConf;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.Mapper;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
import org.apache.hadoop.mapred.RunningJob;
import org.apache.hadoop.mapred.SequenceFileInputFormat;
import org.apache.hadoop.mapred.SequenceFileOutputFormat;
import org.apache.hadoop.mapred.TextOutputFormat;
import org.apache.hadoop.mapred.TextInputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;
import org.apache.log4j.Logger;
public class Stats extends Configured implements Tool
{
private static final Logger sLogger = Logger.getLogger(Stats.class);
private static final int n50contigthreshold = 100;
private static class StatsMapper extends MapReduceBase
implements Mapper<LongWritable, Text, Text, Text>
{
private long smallcnt = 0;
private long smallsum = 0;
private long smalldeg = 0;
private double smallcov = 0;
private long medcnt = 0;
private long medsum = 0;
private long meddeg = 0;
private double medcov = 0;
OutputCollector<Text,Text> mOutput = null;
private static Set<String> fields = new HashSet<String>();
private static Node node = new Node();
public void configure(JobConf job)
{
fields.add(Node.STR);
fields.add(Node.COVERAGE);
fields.add("ff");
fields.add("fr");
fields.add("rr");
fields.add("rf");
}
public void map(LongWritable lineid, Text nodetxt,
OutputCollector<Text, Text> output, Reporter reporter)
throws IOException
{
mOutput = output;
node.fromNodeMsg(nodetxt.toString(), fields);
//String str = node.str();
//String raw = node.str_raw();
//String edges = node.edges();
int len = node.len();
int fdegree = node.degree("f");
int rdegree = node.degree("r");
float cov = node.cov();
if (len < n50contigthreshold)
{
if (len >= 50)
{
medcnt++;
medsum += len;
meddeg += (fdegree + rdegree) * len;
medcov += cov * len;
reporter.incrCounter("Brush", "mednodes", 1);
}
smallcnt++;
smallsum += len;
smalldeg += (fdegree + rdegree) * len;
smallcov += cov * len;
reporter.incrCounter("Brush", "smallnodes", 1);
}
else
{
output.collect(new Text(Integer.toString(len)),
new Text(Integer.toString(fdegree) + "\t" +
Integer.toString(rdegree) + "\t" +
Float.toString(cov)));
}
reporter.incrCounter("Brush", "nodes", 1);
}
public void close() throws IOException
{
if (mOutput != null)
{
if (smallcnt > 0)
{
mOutput.collect(new Text("SHORT"),
new Text("1" + "\t" +
Long.toString(smallcnt) + "\t" +
Long.toString(smallsum) + "\t" +
Long.toString(smalldeg) + "\t" +
Double.toString(smallcov)));
}
if (medcnt > 0)
{
mOutput.collect(new Text("SHORT"),
new Text("50" + "\t" +
Long.toString(medcnt) + "\t" +
Long.toString(medsum) + "\t" +
Long.toString(meddeg) + "\t" +
Double.toString(medcov)));
}
smallcnt = 0;
smallsum = 0;
smalldeg = 0;
smallcov = 0;
medcnt = 0;
medsum = 0;
meddeg = 0;
medcov = 0;
}
}
}
private static class StatsReducer extends MapReduceBase
implements Reducer<Text, Text, Text, Text>
{
OutputCollector<Text,Text> mOutput = null;
private long N50_TARGET = 0;
private final int TOPCNT = 10;
private List<Integer> n50sizes = new ArrayList<Integer>();
private static int [] cutoffs =
{ 1, 50, 100, 250, 500,
1000, 5000, 10000, 15000, 20000,
25000, 30000, 35000, 40000, 50000,
75000, 100000, 125000, 150000, 200000,
250000, 500000, 750000, 1000000 };
private long [] cnts = new long [cutoffs.length];
private long [] sums = new long [cutoffs.length];
private long [] degs = new long [cutoffs.length];
private long [] n50s = new long [cutoffs.length];
private long [] n50is = new long [cutoffs.length];
private double [] covs = new double [cutoffs.length];
public void configure(JobConf job) {
N50_TARGET = Long.parseLong(job.get("N50_TARGET"));
}
public void reduce(Text key, Iterator<Text> iter,
OutputCollector<Text, Text> output, Reporter reporter)
throws IOException
{
mOutput = output;
if (key.toString().compareTo("SHORT") == 0)
{
// my ($tag, $cutoff, $cnt, $sum, $degree, $cov) = split /\t/, $_;
while (iter.hasNext())
{
String valstr = iter.next().toString();
String [] values = valstr.split("\t");
//System.err.println(key.toString() + " " + valstr + "\n");
int cutoff = Integer.parseInt(values[0]);
long cnt = Long.parseLong(values[1]);
long sum = Long.parseLong(values[2]);
long deg = Long.parseLong(values[3]);
double cov = Double.parseDouble(values[4]);
int ci = -1;
for (int i = 0; i < cutoffs.length; i++)
{
if (cutoffs[i] == cutoff)
{
ci = i;
break;
}
}
if (ci == -1) { throw new IOException("Couldn't find cutoff index for " + cutoff); }
cnts[ci] += cnt;
sums[ci] += sum;
degs[ci] += deg;
covs[ci] += cov;
}
}
else
{
// my ($len, $fdegree, $rdegree, $cov) = split /\t/, $_;
int len = Integer.parseInt(key.toString());
while (iter.hasNext())
{
String valstr = iter.next().toString();
String [] values = valstr.split("\t");
//System.err.println(key.toString() + " " + valstr + "\n");
int fdegree = Integer.parseInt(values[0]);
int rdegree = Integer.parseInt(values[1]);
float cov = Float.parseFloat(values[2]);
if (len >= n50contigthreshold)
{
n50sizes.add(len);
}
for (int i = 0; i < cutoffs.length; i++)
{
if (len >= cutoffs[i])
{
cnts[i]++;
sums[i] += len;
degs[i] += (fdegree + rdegree) * len;
covs[i] += cov * len;
}
}
}
}
}
public void close() throws IOException
{
if (mOutput != null)
{
if (cnts[0] == 0) { throw new IOException("No contigs"); }
Collections.sort(n50sizes); // ascending sort
//mOutput.collect(new Text(),
// new Text(String.format("%-11s% 10s% 10s% 13s% 10s% 10s% 10s% 10s\n",
// "Threshold", "Cnt", "Sum", "Mean", "N50", "N50Cnt", "Deg", "Cov")));
mOutput.collect(new Text("Cutoff"), new Text("Cnt\tSum\tMean\tN50\tN50Cnt\tDeg\tCov"));
long n50sum = 0;
int n50candidates = n50sizes.size();
// find the largest cutoff with at least 1 contig
int curcutoff = -1;
for (int i = cutoffs.length - 1; i >= 0; i--)
{
if (cnts[i] > 0)
{
curcutoff = i;
break;
}
}
// compute the n50 for each cutoff in descending order
long n50cutoff = sums[curcutoff] / 2;
for (int i = 0; (i < n50candidates) && (curcutoff >= 0); i++)
{
int val = n50sizes.get(n50candidates - 1 - i);
n50sum += val;
if (n50sum >= n50cutoff)
{
n50s[curcutoff] = val;
n50is[curcutoff] = i+1;
curcutoff--;
while (curcutoff >= 0)
{
n50cutoff = sums[curcutoff] / 2;
if (n50sum >= n50cutoff)
{
n50s[curcutoff] = val;
n50is[curcutoff] = i+1;
curcutoff--;
}
else
{
break;
}
}
}
}
DecimalFormat df = new DecimalFormat("0.00");
// print stats at each cutoff
for (int i = cutoffs.length - 1; i >= 0; i--)
{
int t = cutoffs[i];
long c = cnts[i];
if (c > 0)
{
long s = sums[i];
long n50 = n50s[i];
long n50cnt = n50is[i];;
double degree = (double) degs[i] / (double) s;
double cov = (double) covs[i] / (double) s;
//mOutput.collect(new Text(),
// new Text(String.format(">%-10s% 10d% 10d%13.02f%10d%10d%10.02f%10.02f",
// t, c, s, (c > 0 ? s/c : 0.0), n50, n50cnt, degree, cov)));
mOutput.collect(new Text(">" + t),
new Text(c + "\t" + s + "\t" + df.format(c > 0 ? (float) s/ (float) c : 0.0) + "\t" +
n50 + "\t" + n50cnt + "\t" + df.format(degree) + "\t" + df.format(cov)));
}
}
// print the top N contig sizes
if (n50candidates > 0)
{
mOutput.collect(new Text(""), new Text(""));
long topsum = 0;
for (int i = 0; (i < TOPCNT) && (i < n50candidates); i++)
{
int val = n50sizes.get(n50candidates - 1 - i);
topsum += val;
int j = i+1;
mOutput.collect(new Text("max_" + j + ":"), new Text(val + "\t" + topsum));
}
}
// compute the N50 with respect to user specified genome size
if (N50_TARGET > 0)
{
mOutput.collect(new Text(""), new Text(""));
mOutput.collect(new Text("global_n50target:"), new Text(Long.toString(N50_TARGET)));
n50sum = 0;
n50cutoff = N50_TARGET/2;
boolean n50found = false;
for (int i = 0; i < n50candidates; i++)
{
int val = n50sizes.get(n50candidates - 1 - i);
n50sum += val;
if (n50sum >= n50cutoff)
{
int n50cnt = i + 1;
n50found = true;
mOutput.collect(new Text("global_n50:"), new Text(Integer.toString(val)));
mOutput.collect(new Text("global_n50cnt:"), new Text(Integer.toString(n50cnt)));
break;
}
}
if (!n50found)
{
mOutput.collect(new Text("global_n50:"), new Text("<" + n50contigthreshold));
mOutput.collect(new Text("global_n50cnt:"), new Text(">" + n50candidates));
}
}
}
}
}
public RunningJob run(String inputPath, String outputPath) throws Exception
{
sLogger.info("Tool name: Stats");
sLogger.info(" - input: " + inputPath);
sLogger.info(" - output: " + outputPath);
JobConf conf = new JobConf(Stats.class);
conf.setJobName("Stats " + inputPath);
BrushConfig.initializeConfiguration(conf);
conf.setNumReduceTasks(1);
FileInputFormat.addInputPath(conf, new Path(inputPath));
FileOutputFormat.setOutputPath(conf, new Path(outputPath));
conf.setInputFormat(TextInputFormat.class);
conf.setOutputFormat(TextOutputFormat.class);
conf.setMapOutputKeyClass(Text.class);
conf.setMapOutputValueClass(Text.class);
conf.setOutputKeyClass(Text.class);
conf.setOutputValueClass(Text.class);
conf.setMapperClass(StatsMapper.class);
conf.setReducerClass(StatsReducer.class);
//delete the output directory if it exists already
FileSystem.get(conf).delete(new Path(outputPath), true);
return JobClient.runJob(conf);
}
public int run(String[] args) throws Exception
{
String inputPath = ""; //args[0];
String outputPath = ""; //args[1];
BrushConfig.N50_TARGET = 1234;
run(inputPath, outputPath);
return 0;
}
public static void main(String[] args) throws Exception
{
int res = ToolRunner.run(new Configuration(), new Stats(), args);
System.exit(res);
}
}
| CSCLabTW/CloudBrush | src/Brush/Stats.java |
249,060 | import java.awt.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
// Define the graphical User Interface
class MakeChain extends Basic implements ActionListener {
/*
*********************************************************************
dl_poly/java GUI class to make chain polymer CONFIG files
copyright - daresbury laboratory
author - w.smith 2011
*********************************************************************
*/
public static GUI home;
public static MakeChain job;
private static JButton make,close;
private static JLabel lab1,lab2,lab3,lab4,lab5,pass;
private static JTextField nc,area,eon,gapz;
private static JCheckBox chk1,chk2;
private static JComboBox<String> head;
private static boolean flip,twin;
private static String headgroup;
private static int keyhed,ncarbons,nethos;
private static double zgap,harea;
private static double beta=.615479708;
private static double[] rot,uuu,vvv;
private static double[] xbs,ybs,zbs;
private static double[] cell;
private static double[][] xyz;
private static Element[] atoms;
public MakeChain(){
/*
*********************************************************************
dl_poly/java GUI routine
copyright - daresbury laboratory
author - w.smith 2011
*********************************************************************
*/
super();
setTitle("Make Chain");
getContentPane().setBackground(art.back);
getContentPane().setForeground(art.fore);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setFont(fontMain);
GridBagLayout grd = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
getContentPane().setLayout(grd);
gbc.fill=GridBagConstraints.BOTH;
// Define the Make button
make = new JButton("Make");
make.setBackground(art.butn);
make.setForeground(art.butf);
fix(make,grd,gbc,0,0,1,1);
// Define the Close button
close = new JButton("Close");
close.setBackground(art.butn);
close.setForeground(art.butf);
fix(close,grd,gbc,2,0,1,1);
// Spacer label
pass = new JLabel(" ");
fix(pass,grd,gbc,0,1,2,1);
// Instruction label 1
lab1 = new JLabel("Number of C atoms:",JLabel.LEFT);
fix(lab1,grd,gbc,0,2,2,1);
// Number of C atoms
nc = new JTextField(6);
nc.setBackground(art.scrn);
nc.setForeground(art.scrf);
fix(nc,grd,gbc,2,2,1,1);
// Instruction label 2
lab2 = new JLabel("Headgroup Area (A^2)",JLabel.LEFT);
fix(lab2,grd,gbc,0,3,2,1);
// Head group area
area = new JTextField(6);
area.setBackground(art.scrn);
area.setForeground(art.scrf);
fix(area,grd,gbc,2,3,1,1);
// Instruction label 3
lab3 = new JLabel("Head Group:",JLabel.LEFT);
fix(lab3,grd,gbc,0,4,2,1);
// Head group choice
head = new JComboBox<String>();
head.setBackground(art.scrn);
head.setForeground(art.scrf);
head.addItem("None");
head.addItem("Soap");
head.addItem("Carboxy");
head.addItem("Phenol");
head.addItem("TAB");
head.addItem("(EO)n");
fix(head,grd,gbc,2,4,1,1);
// Instruction label 4
lab4 = new JLabel("Number of (EO)n groups:",JLabel.LEFT);
fix(lab4,grd,gbc,0,5,2,1);
// Number of (EO)n groups
eon = new JTextField(6);
eon.setBackground(art.scrn);
eon.setForeground(art.scrf);
fix(eon,grd,gbc,2,5,1,1);
// Twin checkbox
chk1 = new JCheckBox("Twin");
chk1.setBackground(art.back);
chk1.setForeground(art.fore);
fix(chk1,grd,gbc,0,6,1,1);
// Flip checkbox
chk2 = new JCheckBox("Flip");
chk2.setBackground(art.back);
chk2.setForeground(art.fore);
fix(chk2,grd,gbc,2,6,1,1);
// Instruction label 5
lab5 = new JLabel("Z - gap (A):",JLabel.LEFT);
fix(lab5,grd,gbc,0,7,2,1);
// Z - gap between twins
gapz = new JTextField(6);
gapz.setBackground(art.scrn);
gapz.setForeground(art.scrf);
fix(gapz,grd,gbc,2,7,1,1);
// Register action buttons
make.addActionListener(this);
close.addActionListener(this);
}
// Constructor method
public MakeChain(GUI here) {
/*
*********************************************************************
dl_poly/java GUI routine
copyright - daresbury laboratory
author - w.smith 2011
*********************************************************************
*/
println("Activated panel for making chain polymer CONFIG file");
home=here;
// Define arrays
uuu=new double[3];
vvv=new double[3];
rot=new double[9];
xbs=new double[4];
ybs=new double[4];
zbs=new double[4];
// Set up Panel
job = new MakeChain();
job.pack();
job.setVisible(true);
setValues();
}
// Set initial values
void setValues() {
/*
*********************************************************************
dl_poly/java GUI routine
copyright - daresbury laboratory
author - w.smith 2011
*********************************************************************
*/
// set default values
keyhed=0;
ncarbons=1;
nethos=1;
zgap=10.0;
harea=25.0;
flip=false;
twin=false;
// define tetrahedral groups
setTetra();
nc.setText(String.valueOf(ncarbons));
area.setText(String.valueOf(harea));
eon.setText(String.valueOf(nethos));
gapz.setText(String.valueOf(zgap));
chk1.setSelected(twin);
chk2.setSelected(flip);
}
void setTetra() {
/*
*********************************************************************
dl_poly/java GUI routine
copyright - daresbury laboratory
author - w.smith 2011
*********************************************************************
*/
// define tetrahedral group
xbs[0]=0.577350269;
ybs[0]=0.0;
zbs[0]=-0.816496581;
xbs[1]=-0.577350269;
ybs[1]=0.816496581;
zbs[1]=0.0;
xbs[2]=-0.577350269;
ybs[2]=-0.816496581;
zbs[2]=0.0;
xbs[3]=0.577350269;
ybs[3]=0.0;
zbs[3]=0.816496581;
}
int chain() {
/*
*********************************************************************
dl_poly/java utility for generating a linear polymer chain
copyright daresbury laboratory
author w.smith 2011
*********************************************************************
*/
double size,xx0,yy0,zz0,dens,disp,gap,base,cc23,co23;
int imcon,natms;
cell=new double[9];
headgroup="";
// start position of chain
xx0=0.0;
yy0=0.0;
zz0=0.0;
// select head group
if(keyhed==1) {
headgroup="Soap";
cc23=0.5*(cc1b+cc2b);
natms=soap();
}
else if(keyhed==2) {
headgroup="Carboxy";
cc23=0.5*(cc1b+cc2b);
co23=0.5*(co1b+co2b);
natms=carboxy();
}
else if(keyhed==3) {
headgroup="Phenol";
cc23=0.5*(cc1b+ccab);
natms=phenol();
}
else if(keyhed==4) {
headgroup="Trimethylammonium Bromide";
natms=trimethyl();
}
else if(keyhed==5) {
headgroup="Ethoxy(n)";
natms=polyoxyeth();
}
else {
natms=3*ncarbons+2;
if(twin)natms*=2;
atoms=new Element[natms];
xyz=new double[3][natms];
headgroup="No";
atoms[0]=new Element("H_");
xyz[0][0]=ch1b*xbs[0]+xx0;
xyz[1][0]=ch1b*ybs[0]+yy0;
xyz[2][0]=ch1b*zbs[0]+zz0;
natms=1;
}
// attach chain to headgroup
for(int i=0;i<ncarbons;i++) {
atoms[natms]=new Element("C_3");
xyz[0][natms]=xx0;
xyz[1][natms]=yy0;
xyz[2][natms]=zz0;
atoms[natms+1]=new Element("H_");
xyz[0][natms+1]=ch1b*xbs[1]+xx0;
xyz[1][natms+1]=ch1b*ybs[1]+yy0;
xyz[2][natms+1]=ch1b*zbs[1]+zz0;
atoms[natms+2]=new Element("H_");
xyz[0][natms+2]=ch1b*xbs[2]+xx0;
xyz[1][natms+2]=ch1b*ybs[2]+yy0;
xyz[2][natms+2]=ch1b*zbs[2]+zz0;
atoms[natms+3]=new Element("H_");
xyz[0][natms+3]=ch1b*xbs[3]+xx0;
xyz[1][natms+3]=ch1b*ybs[3]+yy0;
xyz[2][natms+3]=ch1b*zbs[3]+zz0;
// growth direction vector
xx0=cc1b*xbs[3]+xx0;
yy0=cc1b*ybs[3]+yy0;
zz0=cc1b*zbs[3]+zz0;
xbs[0]=-xbs[0];
xbs[1]=-xbs[1];
xbs[2]=-xbs[2];
xbs[3]=-xbs[3];
natms+=3;
}
natms++;
// determine simulation cell dimensions
size=Math.sqrt(harea/0.866025403);
cell[0]=size*0.866025403;
cell[1]=-size*0.5;
cell[2]=0.0;
cell[3]=size*0.866025403;
cell[4]=size*0.5;
cell[5]=0.0;
cell[6]=0.0;
cell[7]=0.0;
cell[8]=xyz[2][natms-1]-xyz[2][0]+0.5*size;
// set first atom of chain to z=0
base=xyz[2][0];
for(int i=0;i<natms;i++) {
xyz[2][i]=xyz[2][i]-base;
}
// flip structure if required
if(flip) {
base=xyz[2][natms-1];
for(int i=0;i<natms;i++) {
xyz[1][i]=-xyz[1][i];
xyz[2][i]=-xyz[2][i]+base;
}
}
// twin the chains in the Z direction
if(twin) {
gap=0.5*zgap;
for(int i=0;i<natms;i++) {
xyz[2][i]+=gap;
atoms[i+natms]=new Element(atoms[i].zsym);
xyz[0][i+natms]=-xyz[0][i];
xyz[1][i+natms]= xyz[1][i];
xyz[2][i+natms]=-xyz[2][i];
}
natms=2*natms;
cell[8]=2.0*cell[8]+zgap;
} else {
for(int i=0;i<natms;i++)
xyz[2][i]-=cell[8]/2.0;
}
println("Chain terminated successfully");
println("Number of atoms generated:"+BML.fmt(natms,8));
imcon=3;
// Create Config object
config =new Config();
config.natms=natms;
config.pbc.imcon=imcon;
config.atoms=atoms;
config.pbc.cell=cell;
config.xyz=xyz;
config.title="Chain polymer with"+BML.fmt(ncarbons,4)+" units and "+headgroup+" Head Group";
config.pbc.buildBoundary(config.pbc.imcon);
config.structure=new Structure(config);
cfgsav=copyConfig(config);
// write CONFIG file
fname="CFGCHN."+String.valueOf(numchn);
if(!config.configWrite(fname)) return -4;
numchn++;
// Draw structure
if(!editor.isVisible())
editor.showEditor();
editor.pane.restore();
return 0;
}
// make the chosen head group
int soap() {
/*
**********************************************************************
dl_poly/java utility to make the head of a hydrocarbon chain
this one is for soap
copyright daresbury laboratory
author w.smith 2011
**********************************************************************
*/
int natms;
boolean op=false;
natms=3*ncarbons+5;
if(twin)natms*=2;
atoms=new Element[natms];
xyz=new double[3][natms];
atoms[0]=new Element("Na");
xyz[0][0]=0.0;
xyz[1][0]=0.0;
xyz[2][0]=-3.0*cc1b;
atoms[1]=new Element("C_2");
xyz[0][1]=0.0;
xyz[1][1]=0.0;
xyz[2][1]=-cc1b;
atoms[2]=new Element("O_R");
xyz[0][2]= coab*0.866025403;
xyz[1][2]=0.0;
xyz[2][2]=-cc1b-coab*0.5;
atoms[3]=new Element("O_R");
xyz[0][3]=-coab*0.866025403;
xyz[1][3]=0.0;
xyz[2][3]=-cc1b-coab*0.5;
AML.euler(0.0,-beta,0.0,rot);
for(int i=0;i<4;i++) {
uuu[0]=xyz[0][i];
uuu[1]=xyz[1][i];
uuu[2]=xyz[2][i];
AML.rotate(op,uuu,vvv,rot);
xyz[0][i]=vvv[0];
xyz[1][i]=vvv[1];
xyz[2][i]=vvv[2];
}
return 4;
}
int carboxy() {
/*
**********************************************************************
dl_poly/java utility to make the head of a hydrocarbon chain
this one is for carboxy head group
copyright daresbury laboratory
author w.smith 2011
**********************************************************************
*/
int natms;
boolean op=false;
natms=3*ncarbons+5;
if(twin)natms*=2;
atoms=new Element[natms];
xyz=new double[3][natms];
atoms[0]=new Element("H_");
xyz[0][0]= co1b*0.866025403;
xyz[1][0]=0.0;
xyz[2][0]=-cc1b-co1b*0.5-oh1b;
atoms[1]=new Element("C_2");
xyz[0][1]=0.0;
xyz[1][1]=0.0;
xyz[2][1]=-cc1b;
atoms[2]=new Element("O_3");
xyz[0][2]= co1b*0.866025403;
xyz[1][2]=0.0;
xyz[2][2]=-cc1b-co1b*0.5;
atoms[3]=new Element("O_2");
xyz[0][3]=-co2b*0.866025403;
xyz[1][3]=0.0;
xyz[2][3]=-cc1b-co2b*0.5;
AML.euler(0.0,-beta,0.0,rot);
for(int i=0;i<4;i++) {
uuu[0]=xyz[0][i];
uuu[1]=xyz[1][i];
uuu[2]=xyz[2][i];
AML.rotate(op,uuu,vvv,rot);
xyz[0][i]=vvv[0];
xyz[1][i]=vvv[1];
xyz[2][i]=vvv[2];
}
return 4;
}
int trimethyl() {
/*
*********************************************************************
dl_poly/java utility to make the head of a hydrocarbon chain
this one is for trimethylammonium
copyright daresbury laboratory
author w.smith 2011
**********************************************************************
*/
int natms;
boolean op=false;
double cgam=0.942809041;
double sgam=0.333333333;
natms=3*ncarbons+15;
if(twin)natms*=2;
atoms=new Element[natms];
xyz=new double[3][natms];
atoms[0]=new Element("Br");
xyz[0][0]=0.0;
xyz[1][0]=0.0;
xyz[2][0]=-3.0*cn1b-ch1b;
atoms[1]=new Element("H_");
xyz[0][1]=cgam*cn1b;
xyz[1][1]=0.0;
xyz[2][1]=-ch1b-cn1b-cn1b*sgam;
atoms[2]=new Element("C_3");
xyz[0][2]=cgam*cn1b;
xyz[1][2]=0.0;
xyz[2][2]=-cn1b-cn1b*sgam;
atoms[3]=new Element("H_");
xyz[0][3]=cn1b*cgam+ch1b*cgam*0.5;
xyz[1][3]=ch1b*cgam*0.866025403;
xyz[2][3]=-cn1b-cn1b*sgam+ch1b*sgam;
atoms[4]=new Element("H_");
xyz[0][4]=cn1b*cgam+ch1b*cgam*0.5;
xyz[1][4]=-ch1b*cgam*0.866025403;
xyz[2][4]=-cn1b-cn1b*sgam+ch1b*sgam;
for(int i=1;i<5;i++) {
atoms[i+4]=new Element(atoms[i].zsym);
xyz[0][i+4]=-0.5*xyz[0][i]-0.866025403*xyz[1][i];
xyz[1][i+4]=xyz[0][i]*0.866025403-0.5*xyz[1][i];
xyz[2][i+4]=xyz[2][i];
atoms[i+8]=new Element(atoms[i].zsym);
xyz[0][i+8]=-0.5*xyz[0][i]+0.866025403*xyz[1][i];
xyz[1][i+8]=-xyz[0][i]*0.866025403-0.5*xyz[1][i];
xyz[2][i+8]=xyz[2][i];
}
atoms[13]=new Element("N_3");
xyz[0][13]=0.0;
xyz[1][13]=0.0;
xyz[2][13]=-cn1b;
AML.euler(0.0,-beta,0.0,rot);
for(int i=0;i<14;i++) {
uuu[0]=xyz[0][i];
uuu[1]=xyz[1][i];
uuu[2]=xyz[2][i];
AML.rotate(op,uuu,vvv,rot);
xyz[0][i]=vvv[0];
xyz[1][i]=vvv[1];
xyz[2][i]=vvv[2];
}
return 14;
}
int phenol() {
/*
**********************************************************************
dl_poly/java utility to make the head of a hydrocarbon chain
this one is for p-phenol head group
copyright daresbury laboratory
author w.smith 2011
**********************************************************************
*/
int natms;
boolean op=false;
double f;
natms=3*ncarbons+13;
if(twin)natms*=2;
atoms=new Element[natms];
xyz=new double[3][natms];
f=1.03/1.09;
atoms[0]=new Element("H_");
xyz[0][0]= oh1b*0.866025403;
xyz[1][0]=0.0;
xyz[2][0]=-cc1b-ccab*2.0-coab-oh1b*0.5;
atoms[1]=new Element("O_R");
xyz[0][1]=0.0;
xyz[1][1]=0.0;
xyz[2][1]=-cc1b-ccab*2.0-coab;
atoms[2]=new Element("C_R");
xyz[0][2]=0.0;
xyz[1][2]=0.0;
xyz[2][2]=-cc1b-ccab*2.0;
atoms[3]=new Element("C_R");
xyz[0][3]=-ccab*0.866025403;
xyz[1][3]=0.0;
xyz[2][3]=-cc1b-ccab*1.5;
atoms[4]=new Element("C_R");
xyz[0][4]= ccab*0.866025403;
xyz[1][4]=0.0;
xyz[2][4]=-cc1b-ccab*1.5;
atoms[5]=new Element("C_R");
xyz[0][5]=-ccab*0.866025403;
xyz[1][5]=0.0;
xyz[2][5]=-cc1b-ccab*0.5;
atoms[6]=new Element("C_R");
xyz[0][6]= ccab*0.866025403;
xyz[1][6]=0.0;
xyz[2][6]=-cc1b-ccab*0.5;
atoms[7]=new Element("C_R");
xyz[0][7]=0.0;
xyz[1][7]=0.0;
xyz[2][7]=-cc1b;
atoms[8]=new Element("H_");
xyz[0][8]= (f*ch1b+ccab)*0.866025403;
xyz[1][8]=0.0;
xyz[2][8]=-cc1b-ccab*1.5-f*ch1b*0.5;
atoms[9]=new Element("H_");
xyz[0][9]=-(f*ch1b+ccab)*0.866025403;
xyz[1][9]=0.0;
xyz[2][9]=-cc1b-ccab*1.5-f*ch1b*0.5;
atoms[10]=new Element("H_");
xyz[0][10]=-(f*ch1b+ccab)*0.866025403;
xyz[1][10]=0.0;
xyz[2][10]=-cc1b+(f*ch1b-ccab)*0.5;
atoms[11]=new Element("H_");
xyz[0][11]= (f*ch1b+ccab)*0.866025403;
xyz[1][11]=0.0;
xyz[2][11]=-cc1b+(f*ch1b-ccab)*0.5;
AML.euler(0.0,-beta,0.0,rot);
for(int i=0;i<12;i++) {
uuu[0]=xyz[0][i];
uuu[1]=xyz[1][i];
uuu[2]=xyz[2][i];
AML.rotate(op,uuu,vvv,rot);
xyz[0][i]=vvv[0];
xyz[1][i]=vvv[1];
xyz[2][i]=vvv[2];
}
return 12;
}
int polyoxyeth() {
/*
*********************************************************************
dl_poly/java utility for generating a polyoxyethylene head group
copyright daresbury laboratory
author w.smith 2011
*********************************************************************
*/
int natms;
double xx0,yy0,zz0;
natms=3*ncarbons+7*nethos+3;
if(twin)natms*=2;
atoms=new Element[natms];
xyz=new double[3][natms];
// start position of chain
xx0=0.0;
yy0=0.0;
zz0=0.0;
natms=7*nethos+3;
for(int i=0;i<=3*nethos;i++) {
if(i%3==0) {
atoms[natms-2]=new Element("O_3");
xx0=xx0+co1b*xbs[0];
yy0=yy0+co1b*ybs[0];
zz0=zz0+co1b*zbs[0];
xyz[0][natms-2]=xx0;
xyz[1][natms-2]=yy0;
xyz[2][natms-2]=zz0;
natms--;
}
else {
xx0=xx0+cc1b*xbs[0];
yy0=yy0+cc1b*ybs[0];
zz0=zz0+cc1b*zbs[0];
atoms[natms-4]=new Element("C_3");
xyz[0][natms-4]=xx0;
xyz[1][natms-4]=yy0;
xyz[2][natms-4]=zz0;
atoms[natms-3]=new Element("H_");
xyz[0][natms-3]=xx0-ch1b*xbs[1];
xyz[1][natms-3]=yy0+ch1b*ybs[1];
xyz[2][natms-3]=zz0+ch1b*zbs[1];
atoms[natms-2]=new Element("H_");
xyz[0][natms-2]=xx0-ch1b*xbs[2];
xyz[1][natms-2]=yy0+ch1b*ybs[2];
xyz[2][natms-2]=zz0+ch1b*zbs[2];
natms-=3;
}
// growth direction vector
xbs[0]=-xbs[0];
xbs[1]=-xbs[1];
xbs[2]=-xbs[2];
xbs[3]=-xbs[3];
}
atoms[0]=new Element("H_");
xyz[0][0]=xx0+oh1b*xbs[0];
xyz[1][0]=yy0+oh1b*ybs[0];
xyz[2][0]=zz0+oh1b*zbs[0];
natms=7*nethos+2;
if(nethos%2 == 0) {
for(int i=0;i<natms;i++)
xyz[0][i]=-xyz[0][i];
}
return natms;
}
// Interpret the button and textfield actions
public void actionPerformed(ActionEvent e) {
/*
*********************************************************************
dl_poly/java GUI routine
copyright - daresbury laboratory
author - w.smith 2011
*********************************************************************
*/
int status;
String arg = (String)e.getActionCommand();
if (arg.equals("Make")) {
setTetra();
ncarbons=BML.giveInteger(nc.getText(),1);
harea=BML.giveDouble(area.getText(),1);
nethos=BML.giveInteger(eon.getText(),1);
zgap=BML.giveDouble(gapz.getText(),1);
keyhed=head.getSelectedIndex();
twin=chk1.isSelected();
flip=chk2.isSelected();
status=chain();
}
else if (arg.equals("Close")) {
job.dispose();
}
}
}
| dlpolyquantum/dlpoly_quantum | java/MakeChain.java |
249,061 | import java.io.*;
public class Molecule extends Basic {
/*
*********************************************************************
dl_poly/java class to define a molecule
copyright - daresbury laboratory
author - w.smith may 2006
*********************************************************************
*/
public int natm,nbnd,nang,ndih,ninv;
public String molname;
public Element[] atom;
public double[] chge;
public int[] list,mid;
public int[][] ibnd,iang,idih,invr,link;
public double[][] xyz;
private Config cfg;
Molecule(Config home,int ibeg,int itot,String molnam) {
/*
*********************************************************************
dl_poly/java constructor to define Molecule object from a CONFIG list
copyright - daresbury laboratory
author - w.smith june 2001
*********************************************************************
*/
super();
cfg=home;
int i=0;
nbnd=0;
nang=0;
ndih=0;
ninv=0;
natm=itot;
molname=molnam;
chge=new double[natm];
atom=new Element[natm];
xyz=new double[3][natm];
for(int j=ibeg;j<ibeg+itot;j++) {
chge[i]=0;
atom[i]=cfg.atoms[j];
xyz[0][i]=cfg.xyz[0][j];
xyz[1][i]=cfg.xyz[1][j];
xyz[2][i]=cfg.xyz[2][j];
i++;
}
bonds();
angles();
}
void bonds() {
/*
**********************************************************************
dl_poly/java utility to assign bonds in a molecule
based on a bond distance criterion
copyright daresbury laboratory
author w. smith september 2001
**********************************************************************
*/
int last,m1,m2,j,kkk,kbnd,ncl;
double det,ff,xd,yd,zd,ssx,ssy,ssz,xss,yss,zss,rsq,bndfac;
// initial values
ncl=12;
xd=0.0;
yd=0.0;
zd=0.0;
ssx=0.0;
ssy=0.0;
ssz=0.0;
xss=0.0;
yss=0.0;
zss=0.0;
rsq=0.0;
kbnd=natm;
bndfac=1.0+bondpc/100.0;
ibnd=new int[2][kbnd];
link=new int[ncl][natm];
// zero list array
list=new int[natm];
for(int i=0;i<natm;i++)
list[i]=0;
// determine bonds in molecule
nbnd=0;
last=natm;
m1=natm/2;
m2=(natm-1)/2;
for(int m=1;m<=m1;m++) {
if(m>m2)last=m1;
for(int i=0;i<last;i++) {
j=i+m;
if(j>=natm)j=j-natm;
ff=bndfac*(atom[i].zrad+atom[j].zrad);
xd=xyz[0][i]-xyz[0][j];
yd=xyz[1][i]-xyz[1][j];
zd=xyz[2][i]-xyz[2][j];
if(cfg.pbc.imcon>0) {
ssx=(cfg.pbc.rcell[0]*xd+cfg.pbc.rcell[3]*yd+cfg.pbc.rcell[6]*zd);
ssy=(cfg.pbc.rcell[1]*xd+cfg.pbc.rcell[4]*yd+cfg.pbc.rcell[7]*zd);
ssz=(cfg.pbc.rcell[2]*xd+cfg.pbc.rcell[5]*yd+cfg.pbc.rcell[8]*zd);
xss=ssx-BML.nint(ssx);
yss=ssy-BML.nint(ssy);
zss=ssz-BML.nint(ssz);
xd=(cfg.pbc.cell[0]*xss+cfg.pbc.cell[3]*yss+cfg.pbc.cell[6]*zss);
yd=(cfg.pbc.cell[1]*xss+cfg.pbc.cell[4]*yss+cfg.pbc.cell[7]*zss);
zd=(cfg.pbc.cell[2]*xss+cfg.pbc.cell[5]*yss+cfg.pbc.cell[8]*zss);
}
if((Math.abs(xd)<=ff) && (Math.abs(yd)<=ff) && (Math.abs(zd)<=ff)) {
rsq=xd*xd+yd*yd+zd*zd;
if(rsq<=ff*ff) {
if(nbnd==kbnd) {
int jbnd[][]=new int[2][2*kbnd];
for(int n=0;n<kbnd;n++) {
jbnd[0][n]=ibnd[0][n];
jbnd[1][n]=ibnd[1][n];
}
ibnd=jbnd;
kbnd*=2;
}
ibnd[0][nbnd]=Math.min(i,j);
ibnd[1][nbnd]=Math.max(i,j);
nbnd++;
kkk=Math.max(list[i],list[j]);
if(kkk==ncl) {
int kink[][]=new int[2*ncl][natm];
for (int n=0;n<natm;n++) {
for(int k=0;k<ncl;k++) {
kink[k][n]=link[k][n];
}
}
link=kink;
ncl*=2;
}
link[list[i]][i]=j;
link[list[j]][j]=i;
list[i]++;
list[j]++;
}
}
}
}
//println("Number of possible pair bonds found: "+BML.fmt(nbnd,6));
}
void angles() {
/*
**********************************************************************
dl_poly/java utility to assign bonds, valence angles,
dihedrals and inversion angles
copyright daresbury laboratory
author w. smith sepetember 2001
**********************************************************************
*/
int kang,kdih,kinv,jj,kk;
// determine valence angles in system
nang=0;
kang=natm;
iang=new int[3][kang];
for(int i=0;i<natm;i++) {
for(int j=1;j<list[i];j++) {
for(int k=0;k<j;k++) {
if(nang==kang) {
int jang[][]=new int[3][2*kang];
for(int n=0;n<kang;n++) {
jang[0][n]=iang[0][n];
jang[1][n]=iang[1][n];
jang[2][n]=iang[2][n];
}
iang=jang;
kang*=2;
}
iang[0][nang]=Math.min(link[j][i],link[k][i]);
iang[1][nang]=i;
iang[2][nang]=Math.max(link[j][i],link[k][i]);
nang++;
}
}
}
//println("Number of possible valence angles found: "+BML.fmt(nang,6));
// determine dihedral angles in system
ndih=0;
kdih=natm;
mid=new int[kdih];
idih=new int[4][kdih];
for(int i=0;i<nbnd;i++) {
jj=ibnd[0][i];
kk=ibnd[1][i];
for(int j=0;j<list[jj];j++) {
if(kk!=link[j][jj]) {
for(int k=0;k<list[kk];k++) {
if(jj!=link[k][kk]) {
if(ndih==kdih) {
int jid[]=new int[2*kdih];
int jdih[][]=new int[4][2*kdih];
for(int n=0;n<kdih;n++) {
jid[n]=mid[n];
jdih[0][n]=idih[0][n];
jdih[1][n]=idih[1][n];
jdih[2][n]=idih[2][n];
jdih[3][n]=idih[3][n];
}
idih=jdih;
mid=jid;
kdih*=2;
}
if(link[j][jj] != link[k][kk])
{
mid[ndih]=i;
idih[0][ndih]=link[j][jj];
idih[1][ndih]=jj;
idih[2][ndih]=kk;
idih[3][ndih]=link[k][kk];
ndih++;
}
}
}
}
}
}
//println("Number of possible dihedral angles found: "+BML.fmt(ndih,6));
// determine inversion angles in system
ninv=0;
kinv=natm;
invr=new int[4][kinv];
for(int i=0;i<natm;i++) {
if(list[i]>2) {
for(int j=0;j<list[i]-2;j++) {
for(int k=j+1;k<list[i]-1;k++) {
for(int m=k+1;m<list[i];m++) {
if(ninv==kinv) {
int jinv[][]=new int[4][2*kinv];
for(int n=0;n<kinv;n++) {
jinv[0][n]=invr[0][n];
jinv[1][n]=invr[1][n];
jinv[2][n]=invr[2][n];
jinv[3][n]=invr[3][n];
}
invr=jinv;
kinv*=2;
}
invr[0][ninv]=i;
invr[1][ninv]=link[j][i];
invr[2][ninv]=link[k][i];
invr[3][ninv]=link[m][i];
ninv++;
}
}
}
}
}
//println("Number of possible inversion angles found: "+BML.fmt(ninv,6));
}
}
| dlpolyquantum/dlpoly_quantum | java/Molecule.java |
249,062 | // ****************************************************************************
//
// Copyright (c) 2000 - 2014, Lawrence Livermore National Security, LLC
// Produced at the Lawrence Livermore National Laboratory
// LLNL-CODE-442911
// All rights reserved.
//
// This file is part of VisIt. For details, see https://visit.llnl.gov/. The
// full copyright notice is contained in the file COPYRIGHT located at the root
// of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the disclaimer below.
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the disclaimer (as noted below) in the
// documentation and/or other materials provided with the distribution.
// - Neither the name of the LLNS/LLNL nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY,
// LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ****************************************************************************
package llnl.visit;
// ****************************************************************************
// Class: Yielder
//
// Purpose:
// This class is used to yield the thread's cpu time until it ultimately
// starts sleeping and waking on a timeout.
//
// Notes:
//
// Programmer: Brad Whitlock
// Creation: Thu Aug 8 12:50:24 PDT 2002
//
// Modifications:
//
// ****************************************************************************
/**
* Yield the thread's cpu time until it ultimately starts sleeping and
* waking on a timeout.
*
* @author Brad Whitlock
*/
class Yielder
{
/**
* Constructor for the Yielder class.
*
* @param maxt The maximum timeout
*/
public Yielder(int maxt)
{
idlecount = 0;
maxtimeout = maxt;
}
/**
* Yields the CPU so the thread does not do any work.
*
* @param maxt The maximum timeout
*/
public void yield() throws java.lang.InterruptedException
{
++idlecount;
if(idlecount < 10)
{
// Yield to other threads.
Thread.currentThread().yield();
}
else
{
// The thread has been idle for a while, sleep
// instead of yield because sleep does not require
// any work.
int timeout = maxtimeout / 10;
if(idlecount > 50 && idlecount < 100)
timeout = maxtimeout / 4;
else if(idlecount >= 100)
timeout = maxtimeout / 2;
else if(idlecount >= 500)
timeout = maxtimeout;
Thread.currentThread().sleep(timeout);
}
}
/**
* Resets the idle count.
*
* @param maxt The maximum timeout
*/
public void reset()
{
idlecount = 0;
}
int idlecount;
int maxtimeout;
}
| ahota/visit_intel | java/Yielder.java |
249,063 | import java.awt.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
public class RDFCalc extends Basic implements ActionListener {
/*
*********************************************************************
dl_poly/java GUI class to calculate radial distribution function
copyright - daresbury laboratory
author - w.smith 2005
*********************************************************************
*/
public static RDFCalc job;
private static GUI home;
private static GraphDraw rdfplt=null;
private static double time0,time1,rcut,delr;
private static String name1,name2;
private static int nconf,lenrdf,mxrad,isampl;
private static JTextField atom1,atom2,history,configs,length,sample,cutoff;
private static JCheckBox format;
private static boolean form;
private static JButton run,close;
private static String[] name;
private static double[] rdf,cell,chge,weight,rrr;
private static double[][] xyz,vel,frc;
// Define the Graphical User Interface
public RDFCalc() {
/*
*********************************************************************
dl_poly/java GUI routine
copyright - daresbury laboratory
author - w.smith 2001
*********************************************************************
*/
setTitle("RDF Calculator");
getContentPane().setBackground(art.back);
getContentPane().setForeground(art.fore);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setFont(fontMain);
GridBagLayout grd = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
getContentPane().setLayout(grd);
gbc.fill=GridBagConstraints.BOTH;
// Define the Run button
run = new JButton("Run");
run.setBackground(art.butn);
run.setForeground(art.butf);
fix(run,grd,gbc,0,0,1,1);
fix(new JLabel(" "),grd,gbc,1,0,1,1);
// Define the Close button
close = new JButton("Close");
close.setBackground(art.butn);
close.setForeground(art.butf);
fix(close,grd,gbc,2,0,1,1);
// Instruction label 1
JLabel lab1 = new JLabel("Required HISTORY file:",JLabel.LEFT);
fix(lab1,grd,gbc,0,1,3,1);
// Name of HISTORY file
history = new JTextField(18);
history.setBackground(art.scrn);
history.setForeground(art.scrf);
fix(history,grd,gbc,0,2,3,1);
// History file format
format=new JCheckBox("File");
format.setBackground(art.back);
format.setForeground(art.fore);
//fix(format,grd,gbc,0,3,1,1);
JLabel lab2 = new JLabel("is formatted?",JLabel.LEFT);
//fix(lab2,grd,gbc,1,3,2,1);
// Instruction label 2
JLabel lab3 = new JLabel("Atomic names:",JLabel.LEFT);
fix(lab3,grd,gbc,0,4,3,1);
// Name of first atom type
atom1 = new JTextField(8);
atom1.setBackground(art.scrn);
atom1.setForeground(art.scrf);
fix(atom1,grd,gbc,0,5,1,1);
// Name of second atom type
atom2 = new JTextField(8);
atom2.setBackground(art.scrn);
atom2.setForeground(art.scrf);
fix(atom2,grd,gbc,2,5,1,1);
// Number of configurations
JLabel lab4 = new JLabel("No. configurations:",JLabel.LEFT);
fix(lab4,grd,gbc,0,6,2,1);
configs = new JTextField(8);
configs.setBackground(art.scrn);
configs.setForeground(art.scrf);
fix(configs,grd,gbc,2,6,1,1);
// MSD array length
JLabel lab5 = new JLabel("RDF array length:",JLabel.LEFT);
fix(lab5,grd,gbc,0,7,2,1);
length = new JTextField(8);
length.setBackground(art.scrn);
length.setForeground(art.scrf);
fix(length,grd,gbc,2,7,1,1);
// Sampling interval
JLabel lab6 = new JLabel("Sampling interval:",JLabel.LEFT);
fix(lab6,grd,gbc,0,8,2,1);
sample = new JTextField(8);
sample.setBackground(art.scrn);
sample.setForeground(art.scrf);
fix(sample,grd,gbc,2,8,1,1);
// Cutoff radius
JLabel lab7 = new JLabel("Cutoff radius (A):",JLabel.LEFT);
fix(lab7,grd,gbc,0,9,2,1);
cutoff = new JTextField(8);
cutoff.setBackground(art.scrn);
cutoff.setForeground(art.scrf);
fix(cutoff,grd,gbc,2,9,1,1);
// Register action buttons
run.addActionListener(this);
close.addActionListener(this);
}
public RDFCalc(GUI here) {
/*
*********************************************************************
dl_poly/java GUI routine
copyright - daresbury laboratory
author - w.smith 2001
*********************************************************************
*/
home=here;
println("Activated panel for calculating RDFs");
job=new RDFCalc();
job.pack();
job.setVisible(true);
name1="ALL";
name2="ALL";
fname="HISTORY";
nconf=1000;
lenrdf=512;
isampl=1;
rcut=7.5;
form=true;
atom1.setText(name1);
atom2.setText(name2);
history.setText(fname);
format.setSelected(form);
configs.setText(String.valueOf(nconf));
length.setText(String.valueOf(lenrdf));
sample.setText(String.valueOf(isampl));
cutoff.setText(String.valueOf(rcut));
}
public void actionPerformed(ActionEvent e) {
/*
*********************************************************************
dl_poly/java GUI routine
copyright - daresbury laboratory
author - w.smith 2001
*********************************************************************
*/
String arg = (String)e.getActionCommand();
if (arg.equals("Run")) {
name1=atom1.getText();
name2=atom2.getText();
fname=history.getText();
form=format.isSelected();
nconf=BML.giveInteger(configs.getText(),1);
lenrdf=BML.giveInteger(length.getText(),1);
isampl=BML.giveInteger(sample.getText(),1);
rcut=BML.giveDouble(cutoff.getText(),1);
gofr();
rdfFile();
}
else if (arg.equals("Close")) {
job.dispose();
}
}
void gofr() {
/*
*********************************************************************
dl_poly/java routine to calculate radial distribution
function for selected atoms from dl_poly HISTORY file
copyright - daresbury laboratory
author - w.smith may 2005
*********************************************************************
*/
boolean all1,all2;
LineNumberReader lnr=null;
int nat1=0,nat2=0;
int iconf,natms,k,imcon;
double rad,rsq,rcut2,rnrm,tx,ty,tz,ux,uy,uz,f1,f2,tcut;
double[] bcell,work;
double cell[]=new double[9];
double avcell[]=new double[9];
double info[]=new double[10];
rnrm=0.0;
all1=false;
all2=false;
if(name1.toUpperCase().equals("ALL"))all1=true;
if(name2.toUpperCase().equals("ALL"))all2=true;
mxrad=Math.max(64,4*(int)lenrdf/4);
rcut2=rcut*rcut;
delr=rcut/mxrad;
// write control variables
println("Name of target HISTORY file : "+fname);
println("Label of atom 1 : "+name1);
println("Label of atom 2 : "+name2);
println("Length of RDF array : "+BML.fmt(lenrdf,8));
println("Number of configurations : "+BML.fmt(nconf,8));
println("Cutoff radius : "+BML.fmt(rcut,10));
println("RDF bin width : "+BML.fmt(delr,10));
// initialize average cell vectors
for(int i=0;i<9;i++)
avcell[i]=0.0;
// initialise RDF array
rdf=new double[mxrad];
for(int j=0;j<mxrad;j++)
rdf[j]=0.0;
// process the HISTORY file data
for(int i=0;i<9;i++)
cell[i]=0.0;
cell[0]=1.0;
cell[4]=1.0;
cell[8]=1.0;
// initialise control parameters for HISTORY file reader
info[0]=0.0;
info[1]=999999;
info[2]=0.0;
info[3]=0.0;
info[4]=0.0;
info[5]=0.0;
if(form) {
lnr=hread(fname,name,lnr,info,cell,chge,weight,xyz,vel,frc);
if(BML.nint(info[3])<0 && BML.nint(info[3])!=-1) {
println("Error - HISTORY file data error");
return;
}
}
else {
println("Error - unformatted read option not active");
return;
}
natms=BML.nint(info[7]);
imcon=BML.nint(info[5]);
if(imcon < 1 || imcon > 3) {
println("Error - incorrect periodic boundary condition");
info[0]=-1.0;
lnr=hread(fname,name,lnr,info,cell,chge,weight,xyz,vel,frc);
return;
}
name=new String[natms];
chge=new double[natms];
weight=new double[natms];
xyz=new double[3][natms];
OUT:
for(iconf=0;iconf<nconf;iconf++) {
lnr=hread(fname,name,lnr,info,cell,chge,weight,xyz,vel,frc);
if(BML.nint(info[3])<0 && BML.nint(info[3])!=-1) {
println("Error - HISTORY file data error");
info[0]=-1.0;
lnr=hread(fname,name,lnr,info,cell,chge,weight,xyz,vel,frc);
return;
}
if(lnr == null) break OUT;
if(iconf==0) {
info[9]=info[6];
for(int i=0;i<natms;i++) {
if(all1 || name1.equals(name[i]))nat1++;
if(all2 || name2.equals(name[i]))nat2++;
}
}
if(iconf == 0){
bcell=AML.dcell(cell);
tcut=0.5*BML.min(bcell[6],bcell[7],bcell[8]);
if(rcut > tcut){
println("Warning - cut off reset to "+BML.fmt(tcut,10));
rcut=tcut;
rcut2=rcut*rcut;
delr=rcut/mxrad;
}
}
work=AML.invert(cell);
for(int i=0;i<natms;i++) {
tx=xyz[0][i];
ty=xyz[1][i];
tz=xyz[2][i];
xyz[0][i]=work[0]*tx+work[3]*ty+work[6]*tz;
xyz[1][i]=work[1]*tx+work[4]*ty+work[7]*tz;
xyz[2][i]=work[2]*tx+work[5]*ty+work[8]*tz;
}
if(BML.nint(info[3])==-1)break OUT;
// running average of cell vectors
f1=((double)iconf)/(iconf+1);
f2=1.0/(iconf+1);
for(int i=0;i<9;i++)
avcell[i]=f1*avcell[i]+f2*cell[i];
// calculate radial distribution function
for(int i=1;i<natms;i++) {
if(all1 || name1.equals(name[i])) {
for(int j=0;j<i;j++) {
if(all2 || name2.equals(name[j])) {
tx=xyz[0][i]-xyz[0][j];
ty=xyz[1][i]-xyz[1][j];
tz=xyz[2][i]-xyz[2][j];
tx-=BML.nint(tx);
ty-=BML.nint(ty);
tz-=BML.nint(tz);
ux=tx*avcell[0]+ty*avcell[3]+tz*avcell[6];
uy=tx*avcell[1]+ty*avcell[4]+tz*avcell[7];
uz=tx*avcell[2]+ty*avcell[5]+tz*avcell[8];
rsq=ux*ux+uy*uy+uz*uz;
if(rsq < rcut2) {
rad=Math.sqrt(rsq);
k=(int)(rad/delr);
if(name[i].equals(name[j]) || name1.equals(name2)) {
rdf[k]+=2.0;
}
else {
rdf[k]+=1.0;
}
}
}
}
}
}
}
if(iconf==nconf-1) {
info[0]=-1.0;
lnr=hread(fname,name,lnr,info,cell,chge,weight,xyz,vel,frc);
}
if(BML.nint(info[3])==-1) iconf--;
println("Number of configurations read: "+BML.fmt(iconf,8));
// normalise radial distribution function
work=AML.dcell(avcell);
rnrm=0.25*work[9]/(Math.PI*(double)(nat1*nat2)*(double)iconf);
for(int i=0;i<mxrad;i++)
rdf[i]=rnrm*rdf[i]/(Math.pow(delr,3)*(Math.pow(i+0.5,2)+1.0/12.0));
}
void rdfFile() {
/*
*********************************************************************
dl_poly/java GUI routine to create a RDFDAT file
copyright - daresbury laboratory
author - w.smith 2005
*********************************************************************
*/
rrr = new double[lenrdf];
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream("RDFDAT"));
out.writeBytes("Radial distribution function for atoms "+name1+" "+name2+"\n");
out.writeBytes(BML.fmt(1,10)+BML.fmt(mxrad,10)+"\n");
out.writeBytes(BML.fmt(name1,8)+BML.fmt(name2,8)+"\n");
for(int i=0;i<mxrad;i++) {
rrr[i]=delr*(i+0.5);
out.writeBytes(BML.fmt(rrr[i],14)+BML.fmt(rdf[i],14)+"\n");
}
out.close();
if(graf != null)
graf.job.dispose();
graf=new GraphDraw(home);
graf.xlabel.setText("r (A)");
graf.ylabel.setText("t (ps)");
graf.plabel.setText("RDF of "+name1.trim()+" "+name2.trim());
graf.extraPlot(lenrdf,rrr,rdf);
}
catch(Exception e) {
println("Error - file RDFDAT");
}
println("File RDFDAT created");
}
}
| dlpolyquantum/dlpoly_quantum | java/RDFCalc.java |
249,064 | import java.io.*;
import java.awt.*;
public class Config extends Basic {
/*
*********************************************************************
dl_poly/java class to define the contents of a CONFIG file
copyright - daresbury laboratory
author - w.smith may 2006
*********************************************************************
*/
public GUI home;
public String fname;
public String title;
public int natms,levcfg;
public CellBoundary pbc;
public double[][] xyz;
public Element[] atoms;
public Structure structure;
Config(){
/*
*********************************************************************
dl_poly/java constructor to define Config class
copyright - daresbury laboratory
author - w.smith march 2011
*********************************************************************
*/
super();
fname=null;
home=null;
natms=0;
levcfg=0;
title="GUI Reference : "+dateToday();
structure=null;
pbc=new CellBoundary();
xyz=new double[3][MXATMS];
atoms=new Element[MXATMS];
}
boolean configWrite(String filename) {
/*
*********************************************************************
dl_poly/java routine to write a DL_POLY CONFIG file
copyright - daresbury laboratory
author - w.smith march 2011
*********************************************************************
*/
try {
DataOutputStream outStream = new DataOutputStream(new FileOutputStream(filename));
outStream.writeBytes(title+"\n");
outStream.writeBytes(BML.fmt(0,10)+BML.fmt(pbc.imcon,10)+"\n");
if(pbc.imcon>0) {
outStream.writeBytes(BML.fmt(pbc.cell[0],20)+BML.fmt(pbc.cell[1],20)+BML.fmt(pbc.cell[2],20)+"\n");
outStream.writeBytes(BML.fmt(pbc.cell[3],20)+BML.fmt(pbc.cell[4],20)+BML.fmt(pbc.cell[5],20)+"\n");
outStream.writeBytes(BML.fmt(pbc.cell[6],20)+BML.fmt(pbc.cell[7],20)+BML.fmt(pbc.cell[8],20)+"\n");
}
for (int k=0;k<natms;k++) {
outStream.writeBytes(BML.fmt(atoms[k].zsym,8)+BML.fmt(k+1,10)+BML.fmt(atoms[k].znum,10)+"\n");
outStream.writeBytes(BML.fmt(xyz[0][k],20)+BML.fmt(xyz[1][k],20)+BML.fmt(xyz[2][k],20)+"\n");
}
outStream.close();
println("New CONFIG file created: "+filename);
}
catch(Exception e) {
println("Error - writing file: "+filename);
return false;
}
return true;
}
boolean rdCFG(String fname) {
/*
*********************************************************************
dl_poly/java routine to read a DL_POLY CONFIG file
copyright - daresbury laboratory
author - w.smith march 2011
*********************************************************************
*/
int i,j,k,m;
LineNumberReader lnr=null;
String record="",namstr="";
double xlo=0,xhi=0,ylo=0,yhi=0,zlo=0,zhi=0,ddd;
// open the CONFIG file
try {
lnr = new LineNumberReader(new FileReader(fname));
println("Reading file: "+fname);
title = lnr.readLine();
println("File header record: "+title);
record = lnr.readLine();
levcfg=BML.giveInteger(record,1);
pbc.imcon =BML.giveInteger(record,2);
if(pbc.imcon > 0) {
record = lnr.readLine();
pbc.cell[0]=BML.giveDouble(record,1);
pbc.cell[1]=BML.giveDouble(record,2);
pbc.cell[2]=BML.giveDouble(record,3);
record = lnr.readLine();
pbc.cell[3]=BML.giveDouble(record,1);
pbc.cell[4]=BML.giveDouble(record,2);
pbc.cell[5]=BML.giveDouble(record,3);
record = lnr.readLine();
pbc.cell[6]=BML.giveDouble(record,1);
pbc.cell[7]=BML.giveDouble(record,2);
pbc.cell[8]=BML.giveDouble(record,3);
}
// read coordinates
i=0;
j=0;
natms=0;
k=levcfg+2;
while((record=lnr.readLine()) != null) {
i=j/k;
m=j-k*i;
if(m == 0) {
namstr = BML.fmt(BML.giveWord(record,1),8);
if(natms == atoms.length)
resizeArrays();
if(!namstr.equals("")) {
atoms[i]=new Element(namstr);
natms++;
}
else {
println("Error - unknown atom type in CONFIG file: "+namstr);
lnr.close();
return false;
}
}
if(m == 1) {
xyz[0][i]=BML.giveDouble(record,1);
xyz[1][i]=BML.giveDouble(record,2);
xyz[2][i]=BML.giveDouble(record,3);
if(pbc.imcon == 0) {
xlo=Math.min(xlo,xyz[0][i]);
ylo=Math.min(ylo,xyz[1][i]);
zlo=Math.min(zlo,xyz[2][i]);
xhi=Math.max(xhi,xyz[0][i]);
yhi=Math.max(yhi,xyz[1][i]);
zhi=Math.max(zhi,xyz[2][i]);
}
}
j++;
}
lnr.close();
}
catch(FileNotFoundException e) {
println("Error - file not found: " + fname);
return false;
}
catch(Exception e) {
println("Error reading file: " + fname + " "+e);
return false;
}
// construct virtual cell for imcon=0
if(pbc.imcon == 0) {
pbc.imcon=2;
ddd=Math.max(xhi-xlo,yhi-ylo);
ddd=Math.max(ddd,zhi-zlo)+10;
pbc.cell[0]=ddd;
pbc.cell[4]=ddd;
pbc.cell[8]=ddd;
}
pbc.buildBoundary(pbc.imcon);
if(pbc.imcon > 0)
pbc.images(natms,xyz);
structure = new Structure(this);
println("Selected CONFIG file loaded successfully");
println("Number of atoms found: "+natms);
return true;
}
boolean rdFRG(String fname) {
/*
*********************************************************************
dl_poly/java routine to read a DL_POLY FRAGMENT file
copyright - daresbury laboratory
author - w.smith march 2011
*********************************************************************
*/
int i,j,k,m;
LineNumberReader lnr=null;
String record="",namstr="";
// open the FRAGMENT file
try {
InputStream instream = this.getClass().getResourceAsStream(fname);
InputStreamReader isr = new InputStreamReader(instream);
BufferedReader reader = new BufferedReader(isr);
println("Reading file: "+fname);
title = reader.readLine();
println("File header record: "+title);
record = reader.readLine();
levcfg=BML.giveInteger(record,1);
pbc.imcon =BML.giveInteger(record,2);
// read coordinates
i=0;
j=0;
natms=0;
k=levcfg+2;
while((record=reader.readLine()) != null) {
i=j/k;
m=j-k*i;
if(m == 0) {
namstr = BML.fmt(BML.giveWord(record,1),8);
if(natms == atoms.length)
resizeArrays();
if(!namstr.equals("")) {
atoms[i]=new Element(namstr);
natms++;
}
else {
println("Error - unknown atom type in CONFIG file: "+namstr);
reader.close();
return false;
}
}
if(m == 1) {
xyz[0][i]=BML.giveDouble(record,1);
xyz[1][i]=BML.giveDouble(record,2);
xyz[2][i]=BML.giveDouble(record,3);
}
j++;
}
reader.close();
}
catch(FileNotFoundException e) {
println("Error - file not found: " + fname);
return false;
}
catch(Exception e) {
println("Error reading file: " + fname + " "+e);
return false;
}
structure = new Structure(this);
println("Selected FRAGMENT file loaded successfully");
println("Number of atoms found: "+natms);
return true;
}
boolean rdXYZ(String fname) {
/*
*********************************************************************
dl_poly/java routine to read an XYZ configuration file
copyright - daresbury laboratory
author - w.smith march 2011
*********************************************************************
*/
LineNumberReader lnr=null;
String record="",namstr="";
double xlo,xhi,ylo,yhi,zlo,zhi,ddd;
xlo=0.0;
ylo=0.0;
zlo=0.0;
xhi=0.0;
yhi=0.0;
zhi=0.0;
pbc.imcon=2;
levcfg=0;
// open XYZ file
try {
lnr = new LineNumberReader(new FileReader(fname));
println("Reading file: "+fname);
record = lnr.readLine();
natms = BML.giveInteger(record,1);
println("Number of atoms in file : "+natms);
if(natms > atoms.length) {
atoms=new Element[natms];
xyz=new double[3][natms];
}
title = lnr.readLine();
println("File header record: "+title);
// read coordinates
for(int i=0;i<natms;i++) {
record = lnr.readLine();
namstr = BML.fmt(BML.giveWord(record,1),8);
if(!namstr.equals(""))
atoms[i]=new Element(namstr);
else {
println("Error - unknown atom type in XYZ file: "+namstr);
lnr.close();
return false;
}
xyz[0][i]=BML.giveDouble(record,2);
xyz[1][i]=BML.giveDouble(record,3);
xyz[2][i]=BML.giveDouble(record,4);
xlo=Math.min(xlo,xyz[0][i]);
ylo=Math.min(ylo,xyz[1][i]);
zlo=Math.min(zlo,xyz[2][i]);
xhi=Math.max(xhi,xyz[0][i]);
yhi=Math.max(yhi,xyz[1][i]);
zhi=Math.max(zhi,xyz[2][i]);
}
lnr.close();
}
catch(FileNotFoundException e) {
println("Error - file not found: " + fname);
return false;
}
catch(Exception e) {
println("Error reading file: " + fname + " "+e);
return false;
}
// centre the cell contents
for(int i=0;i<natms;i++) {
xyz[0][i]-=(xhi-xlo)/2.0;
xyz[1][i]-=(yhi-ylo)/2.0;
xyz[2][i]-=(zhi-zlo)/2.0;
}
// build boundary condition
ddd=Math.pow(((xhi-xlo)*(yhi-ylo)*(zhi-zlo)/natms),(1.0/3.0));
pbc.cell[0]=-(xlo-xhi)+ddd;
pbc.cell[4]=-(ylo-yhi)+ddd;
pbc.cell[8]=-(zlo-zhi)+ddd;
pbc.buildBoundary(pbc.imcon);
structure = new Structure(this);
println("Selected XYZ file loaded successfully");
return true;
}
boolean rdPDB(String fname) {
/*
*********************************************************************
dl_poly/java routine to read a PDB configuration file
copyright - daresbury laboratory
author - w.smith may 2011
*********************************************************************
*/
LineNumberReader lnr=null;
String record="",namstr="";
String label,header,atom,hetatm,pdbres,remark;
double x,y,z,xlo,xhi,ylo,yhi,zlo,zhi,ddd;
natms=0;
pbc.imcon=2;
levcfg=0;
xlo=0.0;
ylo=0.0;
zlo=0.0;
xhi=0.0;
yhi=0.0;
zhi=0.0;
header="HEADER";
atom="ATOM";
hetatm="HETATM";
pdbres="PDBRES";
remark="REMARK";
// open PDB file
try {
lnr = new LineNumberReader(new FileReader(fname));
println("Reading file: "+fname);
// read configuration
while((record=lnr.readLine()) != null) {
if(record.indexOf(header)>=0) {
title=record.substring(9,79);
println("Header: "+title);
}
else if(record.indexOf(remark)>=0) {
println("Remark: "+record.substring(9));
}
else if(record.indexOf(atom)>=0 || record.indexOf(hetatm)>=0) {
if(natms == atoms.length)
resizeArrays();
label=BML.giveWord(record,1);
namstr=BML.fmt(BML.giveWord(record,3).trim(),8);
x=BML.giveDouble(record,6);
y=BML.giveDouble(record,7);
z=BML.giveDouble(record,8);
if(label.indexOf(hetatm)>=0 && namstr.equals("O ")) namstr="OW ";
atoms[natms]=new Element(namstr);
xyz[0][natms]=x;
xyz[1][natms]=y;
xyz[2][natms]=z;
if(natms == 0) {
xlo=xhi=x;
ylo=yhi=y;
zlo=zhi=z;
}
else {
xlo=Math.min(xlo,x);
ylo=Math.min(ylo,y);
zlo=Math.min(zlo,z);
xhi=Math.max(xhi,x);
yhi=Math.max(yhi,y);
zhi=Math.max(zhi,z);
}
natms++;
}
}
lnr.close();
}
catch(FileNotFoundException e) {
println("Error - file not found: " + fname);
return false;
}
catch(Exception e) {
println("Error reading file: " + fname + " "+e);
return false;
}
// centre the cell contents
for(int i=0;i<natms;i++) {
xyz[0][i]-=(xhi+xlo)/2.0;
xyz[1][i]-=(yhi+ylo)/2.0;
xyz[2][i]-=(zhi+zlo)/2.0;
}
// build boundary condition
ddd=Math.max(Math.max(xhi-xlo,yhi-ylo),zhi-zlo);
ddd=Math.pow((ddd*ddd*ddd/natms),(1.0/3.0));
pbc.cell[0]=-(xlo-xhi)+ddd;
pbc.cell[4]=-(ylo-yhi)+ddd;
pbc.cell[8]=-(zlo-zhi)+ddd;
pbc.buildBoundary(pbc.imcon);
structure = new Structure(this);
println("Number of atoms found: "+natms);
println("Selected PDB file loaded successfully");
return true;
}
boolean rdMSI(String fname) {
/*
*********************************************************************
dl_poly/java utility to read a CERIUS 2 configuration file
CERIUS 2 is the copyright of Molecular Simulations Inc
copyright - daresbury laboratory
author - w.smith may 2011
*********************************************************************
*/
LineNumberReader lnr=null;
String record="",namstr="";
int keypbc,i,j,k,m;
double xlo=0,xhi=0,ylo=0,yhi=0,zlo=0,zhi=0,ddd;
natms=0;
pbc.imcon=2;
levcfg=0;
// open the CERIUS file
try {
lnr = new LineNumberReader(new FileReader(fname));
println("Reading file: "+fname);
title=lnr.readLine();
println("File header record: "+title);
while((record=lnr.readLine()) != null) {
if(record.indexOf("Model")>=0) {
// do nothing in current implementation
}
else if((m=record.indexOf("PeriodicType"))>=0) {
record=record.substring(m+12);
keypbc=BML.giveInteger(record,1);
if(keypbc==100)pbc.imcon=1;
}
else if((m=record.indexOf("A3"))>=0) {
record=record.substring(m+2);
pbc.cell[0]=BML.giveDouble(record,1);
pbc.cell[1]=BML.giveDouble(record,2);
pbc.cell[2]=BML.giveDouble(record,3);
}
else if((m=record.indexOf("B3"))>=0) {
record=record.substring(m+2);
pbc.cell[3]=BML.giveDouble(record,1);
pbc.cell[4]=BML.giveDouble(record,2);
pbc.cell[5]=BML.giveDouble(record,3);
}
else if((m=record.indexOf("C3"))>=0) {
record=record.substring(m+2);
pbc.cell[6]=BML.giveDouble(record,1);
pbc.cell[7]=BML.giveDouble(record,2);
pbc.cell[8]=BML.giveDouble(record,3);
}
else if(record.indexOf("Atom1")>=0) {
//Ignore!
}
else if(record.indexOf("Atom2")>=0) {
//Ignore!
}
else if(record.indexOf("Atom")>=0) {
if(natms == atoms.length) {
Element atomz[]=new Element[2*atoms.length];
double uvw[][]=new double[3][2*atoms.length];
for(int n=0;n<atoms.length;n++) {
atomz[n]=new Element(atoms[n].zsym);
uvw[0][n]=xyz[0][n];
uvw[1][n]=xyz[1][n];
uvw[2][n]=xyz[2][n];
}
atoms=atomz;
xyz=uvw;
}
xyz[0][natms]=0.0;
xyz[1][natms]=0.0;
xyz[2][natms]=0.0;
namstr=" ";
OUT:
for(k=0;k<100;k++) {
record=lnr.readLine();
record=record.trim();
if(record.charAt(0)==')') {
natms++;
break OUT;
}
else if((m=record.indexOf("FFType"))>=0) {
record=record.substring(m+6);
namstr=BML.giveWord(record,1);
if(namstr.equals("H___A")) namstr="H__HB";
atoms[natms]=new Element(namstr);
}
else if((m=record.indexOf("Charge"))>=0) {
record=record.substring(m+6);
atoms[natms].zchg=BML.giveDouble(record,1);
}
else if((m=record.indexOf("Mass"))>=0) {
record=record.substring(m+4);
atoms[natms].zmas=BML.giveDouble(record,1);
}
else if((m=record.indexOf("XYZ"))>=0) {
record=record.substring(m+3);
xyz[0][natms]=BML.giveDouble(record,1);
xyz[1][natms]=BML.giveDouble(record,2);
xyz[2][natms]=BML.giveDouble(record,3);
if(pbc.imcon == 0) {
xlo=Math.min(xlo,xyz[0][natms]);
ylo=Math.min(ylo,xyz[1][natms]);
zlo=Math.min(zlo,xyz[2][natms]);
xhi=Math.max(xhi,xyz[0][natms]);
yhi=Math.max(yhi,xyz[1][natms]);
zhi=Math.max(zhi,xyz[2][natms]);
}
}
}
}
}
lnr.close();
}
catch(FileNotFoundException e) {
println("Error - file not found: " + fname);
return false;
}
catch(Exception e) {
println("Error reading file: " + fname + " "+e);
println(record);
return false;
}
if(pbc.imcon == 0) {
// centre the cell contents
for(i=0;i<natms;i++) {
xyz[0][i]-=(xhi-xlo)/2.0;
xyz[1][i]-=(yhi-ylo)/2.0;
xyz[2][i]-=(zhi-zlo)/2.0;
}
// build boundary condition
pbc.imcon=2;
ddd=Math.pow((xhi-xlo)*(yhi-ylo)*(zhi-zlo)/natms,(1.0/3.0));
pbc.cell[0]=-(xlo-xhi)+ddd;
pbc.cell[4]=-(ylo-yhi)+ddd;
pbc.cell[8]=-(zlo-zhi)+ddd;
}
pbc.buildBoundary(pbc.imcon);
structure = new Structure(this);
println("CERIUS file loaded successfully");
println("Number of atoms found: "+natms);
return true;
}
public void resizeArrays(){
/*
*********************************************************************
dl_poly/java routine to resize the arrays of a DL_POLY CONFIG file
copyright - daresbury laboratory
author - w.smith march 2011
*********************************************************************
*/
Element atomz[]=new Element[atoms.length+MXATMS];
double uvw[][]=new double[3][atoms.length+MXATMS];
for(int n=0;n<natms;n++) {
atomz[n]=new Element();
atomz[n].znum=atoms[n].znum;
atomz[n].zmas=atoms[n].zmas;
atomz[n].zchg=atoms[n].zchg;
atomz[n].zrad=atoms[n].zrad;
atomz[n].zsym=new String(atoms[n].zsym);
atomz[n].zcol=new Color(atoms[n].zcol.getRGB());
atomz[n].covalent=atoms[n].covalent;
atomz[n].dotify=atoms[n].dotify;
uvw[0][n]=xyz[0][n];
uvw[1][n]=xyz[1][n];
uvw[2][n]=xyz[2][n];
}
atoms=atomz;
xyz=uvw;
}
}
| dlpolyquantum/dlpoly_quantum | java/Config.java |
249,065 | package labexercise;
// Constructor overloading
public class Overloading {
//instance variables of the class
int id;
String name;
Overloading(){
System.out.println("this a default constructor");
}
Overloading(int i, String n){
id = i;
name = n;
}
public static void main(String[] args) {
//object creation
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);
System.out.println("\nParameterized Constructor values: \n");
Student student = new Student();
System.out.println("Student Id : "+student.id + "\nStudent Name : "
"+student.name); "
}
}
// Method Overloading: changing no. of arguments
class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
class MethodOverloading {
private static void display(int a){
System.out.println("Arguments: " + a);
}
OOP PROGRAMMING WITH JAVA LABORATORY [21CSL35]
SJCIT, Chickballapur 27 2022-23
private static void display(int a, int b){
System.out.println("Arguments: " + a + " and " + b);
}
public static void main(String[] args) {
display(1);
display(1, 4);
}
}
//Method Overloading: changing data type of arguments
class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
class MethodOverloading {
// this method accepts int
private static void display(int a){
System.out.println("Got Integer data.");
}
// this method accepts String object
private static void display(String a){
System.out.println("Got String object.");
}
public static void main(String[] args) {
display(1);
display("Hello");
}
}
| vinodkayara/java | Overloading.java |
249,067 | /**Andrew Ninh
* Ninh Laboratory of Computational Biology
* FASTA File Reader and Writer version 1.0
*/
import java.io.*;
import java.util.*;
public class FASTAFile
{
public String readFASTA(String fname)throws IOException{
BufferedReader r = new BufferedReader(new FileReader(fname));
Scanner input = new Scanner(r);
String dna = "";
String sDescription = input.nextLine();
while(input.hasNext()){
dna += input.nextLine().trim();
}
return dna;
}
public void writeFASTA(String fName, String sDescription, String sSequence, String fLoc)throws IOException{
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(fLoc + fName)));
int nStart=0;
int nNum = 70;
out.println(sDescription);
while (nStart < sSequence.length()){
if (sSequence.length() - nStart < nNum)
out.println(sSequence.substring(nStart));
else
out.println(sSequence.substring(nStart, nStart+70));
nStart = nStart + nNum;
}
out.close();
}
}
| Ninh/GeneColoring | GA/FASTAFile.java |
249,070 | package baller;
import java.util.*;
import battlecode.common.*;
public class Comms {
static Information scan(RobotController rc, int type) throws GameActionException {
Information answer = new Information();
if ((type & CommConstants.SCAN_LEAD) != 0) {
int totalLead = 0; //get total lead
MapLocation[] temp = rc.senseNearbyLocationsWithLead();
int i = 0, size = temp.length;
while (i < size) {
totalLead += rc.senseLead(temp[i]);
i++;
}
answer.lead = totalLead;
}
if ((type & CommConstants.SCAN_ENEMY) != 0) {
Team opponent = rc.getTeam().opponent();
answer.enemy = rc.senseNearbyRobots(-1, opponent);
}
if ((type & CommConstants.SCAN_FRIENDLY) != 0) {
Team self = rc.getTeam();
answer.friendly = rc.senseNearbyRobots(-1, self);
}
return answer;
}
static int encode(Information info) {
// bit 1 - lead level
// bits 2 to 4 - danger levels
int wt = 0, sg = 0, sl = 0, mn = 0;
int enc = CommConstants.VERY_LOW;
boolean found = false;
if (info == null)
return CommConstants.UNKNOWN;
if (info.enemy == null)
return CommConstants.UNKNOWN | (info.lead != 0 ? CommConstants.HAS_LEAD : CommConstants.NO_LEAD);
for (RobotInfo e : info.enemy) {
switch (e.getType()) {
case ARCHON:
enc = CommConstants.ARCHON;
found = true;
break;
case LABORATORY:
enc = CommConstants.LABORATORY;
found = true;
break;
case WATCHTOWER:
wt++;
break;
case SAGE:
sg++;
break;
case SOLDIER:
sl++;
break;
case MINER:
mn++;
break;
}
if (found)
break;
}
if (!found) {
int dangerLevel = 4 * wt + 3 * sg + 2 * sl + mn;
if (dangerLevel > 10)
enc = CommConstants.CRITICAL;
else if (dangerLevel > 5)
enc = CommConstants.HIGH;
else if (dangerLevel > 2)
enc = CommConstants.MEDIUM;
else if (dangerLevel > 0)
enc = CommConstants.LOW;
}
return enc | (info.lead != 0 ? CommConstants.HAS_LEAD : CommConstants.NO_LEAD);
}
public static final int ZONE_WIDTH = 5;
public static final int ZONE_HEIGHT = 5;
static void write(int zoneX, int zoneY, int message, RobotController rc) throws GameActionException {
int encLocation = zoneX * 12 + zoneY; // 12 is max number of zones per strip (MAP_WIDTH / ZONE_HEIGHT)
// We're encoding 4 pieces of information per zone
int arrayIndex = encLocation / 4;
int bitIndex = 4 * (encLocation % 4);
int curVal = (rc.readSharedArray(arrayIndex) | (0b1111 << bitIndex)) ^ (0b1111 << bitIndex) ^ (message << bitIndex);
rc.writeSharedArray(arrayIndex, curVal);
}
static void write(int message, RobotController rc) throws GameActionException {
MapLocation me = rc.getLocation();
int zx = me.x / ZONE_WIDTH, zy = me.y / ZONE_HEIGHT; // 5 is zone size
write(zx, zy, message, rc);
}
static void encodeAndWrite(Information info, RobotController rc) throws GameActionException {
write(encode(info), rc);
}
static CommInformation read(int zoneX, int zoneY, RobotController rc) throws GameActionException {
int encLocation = zoneX * 12 + zoneY; // 12 is max number of zones per strip (MAP_WIDTH / ZONE_HEIGHT)
// We're encoding 4 pieces of information per zone
int arrayIndex = encLocation / 4;
int bitIndex = 4 * (encLocation % 4);
int val = (rc.readSharedArray(arrayIndex) >> bitIndex) & 0b1111;
boolean hasLead = val >> 3 > 0;
int dangerLevel = val & 0b111;
return new CommInformation(zoneX, zoneY, dangerLevel, hasLead);
}
static CommInformation[][] readAllZones(RobotController rc) throws GameActionException {
int width = rc.getMapWidth() / ZONE_WIDTH, height = rc.getMapHeight() / ZONE_HEIGHT;
CommInformation[][] info = new CommInformation[height][width];
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
info[y][x] = read(x, y, rc);
}
}
return info;
}
static MapLocation getZonePosition(int ArrayIndex, int index) {
return new MapLocation(((63-ArrayIndex) * 4)/12, ((63-ArrayIndex) * 4 + index/4)%12);
}
static String getIndex(RobotController rc, int ArrayIndex) throws GameActionException {
int val = rc.readSharedArray(ArrayIndex);
String currentBits = String.format("%16s", Integer.toBinaryString(val)).replace(" ", "0");
return currentBits;
}
}
class CommInformation {
private int zoneX, zoneY;
private int dangerLevel;
private boolean lead;
public int getZoneX() {
return zoneX;
}
public void setZoneX(int zoneX) {
this.zoneX = zoneX;
}
public int getZoneY() {
return zoneY;
}
public void setZoneY(int zoneY) {
this.zoneY = zoneY;
}
public int getDangerLevel() {
return dangerLevel;
}
public void setDangerLevel(int dangerLevel) {
this.dangerLevel = dangerLevel;
}
public boolean hasLead() {
return lead;
}
public void setHasLead(boolean hasLead) {
this.lead = hasLead;
}
public CommInformation(int zoneX, int zoneY, int dangerLevel, boolean hasLead) {
this.zoneX = zoneX;
this.zoneY = zoneY;
this.dangerLevel = dangerLevel;
this.lead = hasLead;
}
}
class Information {
public Information() {
lead = 0;
enemy = null;
friendly = null;
}
int lead;
RobotInfo[] enemy;
RobotInfo[] friendly;
}
| jessechoe10/Battlecode-2022 | src/baller/Comms.java |
249,071 | /* ------------------------------------------------------------------------- */
/* Copyright (C) 2011 Marius C. Silaghi
Author: Marius Silaghi: msilaghi@fit.edu
Florida Tech, Human Decision Support Systems Laboratory
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation; either the current version of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
/* ------------------------------------------------------------------------- */
package util;
import java.util.Calendar;
import ASN1.Encoder;
public class Util {
public static final int MAX_DUMP = 20;
public static final int MAX_UPDATE_DUMP = 400;
static String HEX[]={"0","1","2","3","4","5","6","7","8","9",
"A","B","C","D","E","F"};
public static String byteToHex(byte[] b, int off, int len, String separator){
if(b==null) return "NULL";
String result="";
for(int i=off; i<off+len; i++)
result = result+separator+HEX[(b[i]>>4)&0x0f]+HEX[b[i]&0x0f];
return result;
}
public static String byteToHex(byte[] b, String sep){
if(b==null) return "NULL";
String result="";
for(int i=0; i<b.length; i++)
result = result+sep+HEX[(b[i]>>4)&0x0f]+HEX[b[i]&0x0f];
return result;
}
public static String byteToHex(byte[] b){
return Util.byteToHex(b,"");
}
public static String getGeneralizedTime(){
return Encoder.getGeneralizedTime(Calendar.getInstance());
}
public static Calendar getCalendar(String gdate) {
Calendar date = Calendar.getInstance();
if((gdate==null) || (gdate.length()<14)) {
return null;
}
date.set(Integer.parseInt(gdate.substring(0, 4)),
Integer.parseInt(gdate.substring(4, 6)),
Integer.parseInt(gdate.substring(6, 8)),
Integer.parseInt(gdate.substring(8, 10)),
Integer.parseInt(gdate.substring(10, 12)),
Integer.parseInt(gdate.substring(12, 14)));
return date;
}
}
| Ryan-Knowles/P2P_Space_Game | src/util/Util.java |
249,072 | /*
* (C) Copyright 2009-2013 CNRS.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
Luc Hogie (CNRS, I3S laboratory, University of Nice-Sophia Antipolis)
Aurelien Lancin (Coati research team, Inria)
Christian Glacet (LaBRi, Bordeaux)
David Coudert (Coati research team, Inria)
Fabien Crequis (Coati research team, Inria)
Grégory Morel (Coati research team, Inria)
Issam Tahiri (Coati research team, Inria)
Julien Fighiera (Aoste research team, Inria)
Laurent Viennot (Gang research-team, Inria)
Michel Syska (I3S, University of Nice-Sophia Antipolis)
Nathann Cohen (LRI, Saclay)
*/
package grph;
import toools.set.IntSet;
import com.carrotsearch.hppc.IntObjectMap;
import com.carrotsearch.hppc.IntObjectOpenHashMap;
public class Cache
{
private final IntObjectMap<Object> key_value = new IntObjectOpenHashMap();
public Cache(Grph g)
{
g.getTopologyListeners().add(new TopologyListener() {
@Override
public void vertexRemoved(Grph graph, int vertex)
{
clear();
}
@Override
public void vertexAdded(Grph graph, int vertex)
{
clear();
}
@Override
public void directedSimpleEdgeAdded(Grph Grph, int edge, int src, int dest)
{
clear();
}
@Override
public void undirectedSimpleEdgeAdded(Grph Grph, int edge, int a, int b)
{
clear();
}
@Override
public void undirectedHyperEdgeAdded(Grph graph, int edge)
{
clear();
}
@Override
public void directedHyperEdgeAdded(Grph graph, int edge)
{
clear();
}
@Override
public void directedSimpleEdgeRemoved(Grph Grph, int edge, int a, int b)
{
clear();
}
@Override
public void undirectedSimpleEdgeRemoved(Grph Grph, int edge, int a, int b)
{
clear();
}
@Override
public void undirectedHyperEdgeRemoved(Grph graph, int edge, IntSet incidentVertices)
{
clear();
}
@Override
public void directedHyperEdgeRemoved(Grph graph, int edge, IntSet src, IntSet dest)
{
clear();
}
@Override
public void vertexAddedToDirectedHyperEdgeTail(Grph Grph, int e, int v)
{
clear();
}
@Override
public void vertexAddedToDirectedHyperEdgeHead(Grph Grph, int e, int v)
{
clear();
}
@Override
public void vertexAddedToUndirectedSimpleEdge(Grph Grph, int edge, int vertex)
{
clear();
}
@Override
public void vertexRemovedFromUndirectedHyperEdge(Grph g, int edge, int vertex)
{
clear();
}
@Override
public void vertexRemovedFromDirectedHyperEdgeTail(Grph g, int e, int v)
{
clear();
}
@Override
public void vertexRemovedFromDirectedHyperEdgeHead(Grph g, int e, int v)
{
clear();
}
});
}
public void put(Object value, Object algo, Object... parameters)
{
key_value.put(computeKey(algo, parameters), value);
}
public Object get(Object algo, Object... parameters)
{
return key_value.get(computeKey(algo, parameters));
}
protected int computeKey(Object algo, Object... parameters)
{
StringBuilder b = new StringBuilder();
b.append(algo.getClass().hashCode());
b.append(':');
for (Object o : parameters)
{
b.append(o.hashCode());
b.append(':');
}
return b.hashCode();
}
private void clear()
{
key_value.clear();
}
}
| MichaelRoeder/Grph | src/main/java/grph/Cache.java |
249,073 | /**
* @Copyright(C) 2008 Software Engineering Laboratory (SELAB), Department of Computer
* Science, SUN YAT-SEN UNIVERSITY. All rights reserved.
**/
package parser;
import exceptions.*;
/**
* Main program of the expression based calculator ExprEval
*
* @author [PENDING your name]
* @version 1.00 (Last update: [PENDING the last update])
**/
public class Calculator
{
/**
* The main program of the parser. You should substitute the body of this method
* with your experiment result.
*
* @param expression user input to the calculator from GUI.
* @return if the expression is well-formed, return the evaluation result of it.
* @throws ExpressionException if the expression has error, a corresponding
* exception will be raised.
**/
public double calculate(String expression) throws ExpressionException
{
// You should substitute this method body ...
Parser par = new Parser();
par.readin(expression);
double result = par.parsing();
return result;
}
}
| laosiaudi/ExprEval | src/Calculator.java |
249,075 | // ****************************************************************************
//
// Copyright (c) 2000 - 2019, Lawrence Livermore National Security, LLC
// Produced at the Lawrence Livermore National Laboratory
// LLNL-CODE-442911
// All rights reserved.
//
// This file is part of VisIt. For details, see https://visit.llnl.gov/. The
// full copyright notice is contained in the file COPYRIGHT located at the root
// of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the disclaimer below.
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the disclaimer (as noted below) in the
// documentation and/or other materials provided with the distribution.
// - Neither the name of the LLNS/LLNL nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY,
// LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ****************************************************************************
package llnl.visit;
// ****************************************************************************
// Interface: Plugin
//
// Purpose:
// This interface is implemented by plot and operator plugin classes.
//
// Notes:
//
// Programmer: Brad Whitlock
// Creation: Wed Aug 14 13:46:57 PST 2002
//
// Modifications:
//
// ****************************************************************************
/**
* Defines the interface that all plugin classes must provide.
*
* @author Brad Whitlock
*/
public interface Plugin
{
/**
* Returns the plugin's name.
*/
public String GetName();
/**
* Returns the plugin's version string.
*/
public String GetVersion();
}
| keichi/visit | src/java/Plugin.java |
249,076 | // ****************************************************************************
//
// Copyright (c) 2000 - 2014, Lawrence Livermore National Security, LLC
// Produced at the Lawrence Livermore National Laboratory
// LLNL-CODE-442911
// All rights reserved.
//
// This file is part of VisIt. For details, see https://visit.llnl.gov/. The
// full copyright notice is contained in the file COPYRIGHT located at the root
// of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the disclaimer below.
// - Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the disclaimer (as noted below) in the
// documentation and/or other materials provided with the distribution.
// - Neither the name of the LLNS/LLNL nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY,
// LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
//
// ****************************************************************************
import llnl.visit.View3DAttributes;
import llnl.visit.plots.PseudocolorAttributes;
// ****************************************************************************
// Class: PlotAtts
//
// Purpose:
// This is an example program that shows how to set plot attributes.
//
// Notes:
//
// Programmer: Brad Whitlock
// Creation: Thu Aug 15 16:09:03 PST 2002
//
// Modifications:
// Brad Whitlock, Tue Sep 24 08:05:51 PDT 2002
// I changed it so the view is set after the plot is drawn.
//
// Eric Brugger, Wed Aug 27 09:04:55 PDT 2003
// I modified it to use the new view interface.
//
// Brad Whitlock, Mon Jun 6 17:25:34 PST 2005
// I made it use GetDataPath to locate the data.
//
// Brad Whitlock, Thu Jul 14 12:15:42 PDT 2005
// Updated.
//
// Brad Whitlock, Mon Feb 25 11:07:24 PDT 2008
// Changed to new ViewerProxy interface.
//
// ****************************************************************************
public class PlotAtts extends RunViewer
{
public PlotAtts()
{
super();
}
protected void work(String[] args)
{
if(viewer.GetViewerMethods().OpenDatabase(viewer.GetDataPath() + "globe.silo"))
{
// Create a plot.
viewer.GetViewerMethods().AddPlot("Pseudocolor", "u");
// Set the pseudocolor attributes
PseudocolorAttributes p = (PseudocolorAttributes)viewer.GetPlotAttributes("Pseudocolor");
p.SetOpacity(0.3);
p.Notify();
viewer.GetViewerMethods().SetPlotOptions("Pseudocolor");
// Draw the plot
viewer.GetViewerMethods().DrawPlots();
// Set the view
View3DAttributes v = viewer.GetViewerState().GetView3DAttributes();
v.SetViewNormal(0.456808, 0.335583, 0.823839);
v.SetFocus(-0.927295, -1.22113, 1.01159);
v.SetViewUp(-0.184554, 0.941716, -0.281266);
v.SetParallelScale(15.7041);
v.SetNearPlane(-34.641);
v.SetFarPlane(34.641);
v.Notify();
viewer.GetViewerMethods().SetView3D();
}
else
System.out.println("Could not open the database!");
}
public static void main(String args[])
{
PlotAtts r = new PlotAtts();
r.run(args);
}
}
| ahota/visit_intel | java/PlotAtts.java |
249,077 | import java.awt.*;
import java.io.*;
import java.awt.event.*;
import javax.swing.*;
public class RunMSD extends Basic implements ActionListener {
/*
*********************************************************************
dl_poly/java GUI class to calculate mean square displacement
copyright - daresbury laboratory
author - w.smith 2001
*********************************************************************
*/
public static RunMSD job;
private static GUI home;
private static String atname;
private static boolean form;
private static double[] xx,yy;
private static String[] name;
private static int[] imd,msm;
private static double[] chge,weight;
private static double[][] xyz,vel,frc,xy0,xy1,acm,msd;
private static double[][][] msd0;
private static int npnts,nconf,nmsd,isampl,iomsd;
private static JTextField atom1,history,configs,length,sample,origin;
private static JCheckBox format;
private static JButton run,close;
// Define the Graphical User Interface
public RunMSD() {
/*
*********************************************************************
dl_poly/java GUI routine
copyright - daresbury laboratory
author - w.smith 2001
*********************************************************************
*/
setTitle("MSD Panel");
getContentPane().setBackground(art.back);
getContentPane().setForeground(art.fore);
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
setFont(fontMain);
GridBagLayout grd = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
getContentPane().setLayout(grd);
gbc.fill=GridBagConstraints.BOTH;
// Define the Run button
run = new JButton("Run");
run.setBackground(art.butn);
run.setForeground(art.butf);
fix(run,grd,gbc,0,0,1,1);
fix(new JLabel(" "),grd,gbc,1,0,1,1);
// Define the Close button
close = new JButton("Close");
close.setBackground(art.butn);
close.setForeground(art.butf);
fix(close,grd,gbc,2,0,1,1);
// Name of HISTORY file
JLabel lab1 = new JLabel("Required HISTORY file:",JLabel.LEFT);
fix(lab1,grd,gbc,0,1,3,1);
history = new JTextField(18);
history.setBackground(art.scrn);
history.setForeground(art.scrf);
fix(history,grd,gbc,0,2,3,1);
// History file format
format=new JCheckBox("Formatted");
format.setBackground(art.back);
format.setForeground(art.fore);
//fix(format,grd,gbc,0,3,1,1);
JLabel lab2 = new JLabel("file?",JLabel.LEFT);
//fix(lab2,grd,gbc,1,3,2,1);
// Name of atomic species
JLabel lab3 = new JLabel("Atom name:",JLabel.LEFT);
fix(lab3,grd,gbc,0,4,2,1);
atom1 = new JTextField(8);
atom1.setBackground(art.scrn);
atom1.setForeground(art.scrf);
fix(atom1,grd,gbc,2,4,1,1);
// Number of configurations
JLabel lab4 = new JLabel("No. configurations:",JLabel.LEFT);
fix(lab4,grd,gbc,0,5,2,1);
configs = new JTextField(8);
configs.setBackground(art.scrn);
configs.setForeground(art.scrf);
fix(configs,grd,gbc,2,5,1,1);
// MSD array length
JLabel lab5 = new JLabel("MSD array length:",JLabel.LEFT);
fix(lab5,grd,gbc,0,6,2,1);
length = new JTextField(8);
length.setBackground(art.scrn);
length.setForeground(art.scrf);
fix(length,grd,gbc,2,6,1,1);
// Sampling interval
JLabel lab6 = new JLabel("Sampling interval:",JLabel.LEFT);
fix(lab6,grd,gbc,0,7,2,1);
sample = new JTextField(8);
sample.setBackground(art.scrn);
sample.setForeground(art.scrf);
fix(sample,grd,gbc,2,7,1,1);
// Origin interval
JLabel lab7 = new JLabel("Origin interval:",JLabel.LEFT);
fix(lab7,grd,gbc,0,8,2,1);
origin = new JTextField(8);
origin.setBackground(art.scrn);
origin.setForeground(art.scrf);
fix(origin,grd,gbc,2,8,1,1);
// Register action buttons
run.addActionListener(this);
close.addActionListener(this);
}
public RunMSD(GUI here) {
/*
*********************************************************************
dl_poly/java GUI routine
copyright - daresbury laboratory
author - w.smith 2001
*********************************************************************
*/
home=here;
println("Activated MSD panel");
job=new RunMSD();
job.pack();
job.setVisible(true);
npnts=0;
form=true;
atname="ALL";
fname="HISTORY";
nconf=1000;
nmsd=512;
isampl=1;
iomsd=1;
format.setSelected(form);
atom1.setText(atname);
history.setText(fname);
configs.setText(String.valueOf(nconf));
length.setText(String.valueOf(nmsd));
sample.setText(String.valueOf(isampl));
origin.setText(String.valueOf(iomsd));
}
public void actionPerformed(ActionEvent e) {
/*
*********************************************************************
dl_poly/java GUI routine
copyright - daresbury laboratory
author - w.smith 2001
*********************************************************************
*/
String arg = (String)e.getActionCommand();
if (arg.equals("Run")) {
form=format.isSelected();
atname=atom1.getText();
fname=history.getText();
nconf=BML.giveInteger(configs.getText(),1);
nmsd=BML.giveInteger(length.getText(),1);
isampl=BML.giveInteger(sample.getText(),1);
iomsd=BML.giveInteger(origin.getText(),1);
println("Started MSD calculation .....");
npnts=calcMSD();
if(npnts>0) {
msdXY(npnts,atname);
if(graf != null)
graf.job.dispose();
graf=new GraphDraw(home);
graf.xlabel.setText("Time (ps)");
graf.ylabel.setText("MSD (A^2)");
graf.plabel.setText("MSD of "+atname.trim());
graf.extraPlot(npnts,xx,yy);
}
}
else if (arg.equals("Close")) {
job.dispose();
}
}
int calcMSD() {
/*
*********************************************************************
dl_poly/java routine to calculate mean square displacement
for selected atoms from dl_poly HISTORY file
copyright - daresbury laboratory
author - w.smith march 2001
*********************************************************************
*/
boolean all;
int m,n,nat,natms,nomsd,lsr,msr,nsmsd,imcon,iconf;
double f1,f2,uuu,vvv,www,rmsx,rmsy,rmsz,rr2,tstep;
LineNumberReader lnr=null;
double cell[]=new double[9];
double info[]=new double[10];
double rcell[]=new double[9];
double avcell[]=new double[9];
nat=0;
npnts=0;
all=false;
tstep=0.0;
if(atname.toUpperCase().equals("ALL"))all=true;
if(nmsd%iomsd != 0) {
nmsd=iomsd*(nmsd/iomsd);
println("Warning - msd array dimension reset to "+BML.fmt(nmsd,8));
}
nomsd=nmsd/iomsd;
xx=new double[nmsd];
yy=new double[nmsd];
imd=new int[nmsd];
msm=new int[nmsd];
// write control variables
println("Name of target HISTORY file : "+fname);
println("Label of atom of interest : "+atname);
println("Length of correlation arrays : "+BML.fmt(nmsd,8));
println("Number of configurations : "+BML.fmt(nconf,8));
println("Sampling interval : "+BML.fmt(isampl,8));
println("Interval between origins : "+BML.fmt(iomsd,8));
// initialize cell vector arrays
for(int i=0;i<9;i++) {
cell[i]=0.0;
avcell[i]=0.0;
}
cell[0]=1.0;
cell[4]=1.0;
cell[8]=1.0;
// initialise msd variables
lsr=0;
msr=-1;
nsmsd=0;
// initialise control parameters for HISTORY file reader
info[0]=0.0;
info[1]=999999.;
info[2]=0.0;
info[3]=0.0;
info[4]=0.0;
info[5]=0.0;
if(form) {
lnr=hread(fname,name,lnr,info,cell,chge,weight,xyz,vel,frc);
if(BML.nint(info[3])<0 && BML.nint(info[3])!=-1) {
println("Error - cannot open HISTORY file");
return -1;
}
}
else {
println("Error - unformatted read option not active");
return -2;
}
// initialise msd arrays
natms=BML.nint(info[7]);
name=new String[natms];
chge=new double[natms];
weight=new double[natms];
xyz=new double[3][natms];
xy0=new double[3][natms];
xy1=new double[3][natms];
acm=new double[3][natms];
msd=new double[nmsd][natms];
msd0=new double[nmsd][natms][3];
for(int i=0;i<natms;i++) {
acm[0][i]=0.0;
acm[1][i]=0.0;
acm[2][i]=0.0;
}
for(int j=0;j<nmsd;j++) {
msm[j]=0;
for(int i=0;i<natms;i++) {
msd[j][i]=0.0;
msd0[j][i][0]=0.0;
msd0[j][i][1]=0.0;
msd0[j][i][2]=0.0;
}
}
OUT:
for(iconf=0;iconf<nconf;iconf++) {
lnr=hread(fname,name,lnr,info,cell,chge,weight,xyz,vel,frc);
if(BML.nint(info[3])<0 && BML.nint(info[3])!=-1) {
println("Error - HISTORY file data error");
info[0]=-1.0;
lnr=hread(fname,name,lnr,info,cell,chge,weight,xyz,vel,frc);
return -3;
}
if(lnr == null)break OUT;
if(iconf==0)info[9]=info[6];
if(iconf==1)tstep=info[8]*(info[6]-info[9]);
if(BML.nint(info[3])==-1)break OUT;
imcon=BML.nint(info[5]);
if(imcon>=1 && imcon<=3) {
rcell=AML.invert(cell);
}
else {
println("Error - incorrect periodic boundary condition");
info[0]=-1.0;
lnr=hread(fname,name,lnr,info,cell,chge,weight,xyz,vel,frc);
return -4;
}
n=0;
for(int i=0;i<natms;i++) {
if(all || name[i].equals(atname)) {
if(n==natms) {
println("Error - too many atoms of specified type");
info[0]=-1.0;
lnr=hread(fname,name,lnr,info,cell,chge,weight,xyz,vel,frc);
return -5;
}
xy1[0][n]=xyz[0][i]*rcell[0]+xyz[1][i]*rcell[3]+xyz[2][i]*rcell[6];
xy1[1][n]=xyz[0][i]*rcell[1]+xyz[1][i]*rcell[4]+xyz[2][i]*rcell[7];
xy1[2][n]=xyz[0][i]*rcell[2]+xyz[1][i]*rcell[5]+xyz[2][i]*rcell[8];
n++;
}
}
nat=n;
if(iconf==0) {
println("Number of atoms of selected type : "+BML.fmt(nat,8));
}
if(nat == 0) {
println("Error - zero atoms of specified type");
info[0]=-1.0;
lnr=hread(fname,name,lnr,info,cell,chge,weight,xyz,vel,frc);
return -6;
}
// running average of cell vectors
f1=((double)iconf)/(iconf+1);
f2=1.0/(iconf+1);
for(int i=0;i<9;i++) {
avcell[i]=f1*avcell[i]+f2*cell[i];
}
if(iconf>0) {
// accumulate incremental distances
for(int i=0;i<nat;i++) {
uuu=xy1[0][i]-xy0[0][i];
vvv=xy1[1][i]-xy0[1][i];
www=xy1[2][i]-xy0[2][i];
uuu=uuu-BML.nint(uuu);
vvv=vvv-BML.nint(vvv);
www=www-BML.nint(www);
acm[0][i]+=(uuu*avcell[0]+vvv*avcell[3]+www*avcell[6]);
acm[1][i]+=(uuu*avcell[1]+vvv*avcell[4]+www*avcell[7]);
acm[2][i]+=(uuu*avcell[2]+vvv*avcell[5]+www*avcell[8]);
}
}
for(int i=0;i<nat;i++) {
xy0[0][i]=xy1[0][i];
xy0[1][i]=xy1[1][i];
xy0[2][i]=xy1[2][i];
}
// calculate mean square displacement
if(iconf > 0) {
if(iconf%isampl==0) {
if(nsmsd%iomsd==0) {
lsr=Math.min(lsr+1,nomsd);
msr=(msr+1)%nomsd;
imd[msr]=0;
for(int i=0;i<nat;i++) {
msd0[msr][i][0]=0.0;
msd0[msr][i][1]=0.0;
msd0[msr][i][2]=0.0;
}
}
nsmsd++;
for(int j=0;j<lsr;j++) {
m=imd[j];
imd[j]=m+1;
msm[m]++;
for(int i=0;i<nat;i++) {
rmsx=msd0[j][i][0]+acm[0][i];
rmsy=msd0[j][i][1]+acm[1][i];
rmsz=msd0[j][i][2]+acm[2][i];
msd[m][i]+=(rmsx*rmsx+rmsy*rmsy+rmsz*rmsz);
msd0[j][i][0]=rmsx;
msd0[j][i][1]=rmsy;
msd0[j][i][2]=rmsz;
}
}
for(int i=0;i<natms;i++) {
acm[0][i]=0.0;
acm[1][i]=0.0;
acm[2][i]=0.0;
}
}
}
if(iconf==nconf-1) {
info[0]=-1.0;
lnr=hread(fname,name,lnr,info,cell,chge,weight,xyz,vel,frc);
}
}
if(BML.nint(info[3])==-1) iconf--;
npnts=Math.min(nsmsd,nmsd);
println("Number of configurations read: "+BML.fmt(iconf,8));
// normalise mean square displacement
for(int j=0;j<npnts;j++) {
rr2=0.0;
for(int i=0;i<nat;i++) {
rr2+=msd[j][i];
}
rr2=rr2/msm[j];
xx[j]=tstep*isampl*j;
yy[j]=rr2/nat;
}
return npnts;
}
void msdXY(int npts,String anam1) {
/*
*********************************************************************
dl_poly/java GUI routine to create a MSD XY file
copyright - daresbury laboratory
author - w.smith 2001
*********************************************************************
*/
String fname;
String[] header;
int nhead=4,call;
header=new String[nhead];
fname="MSD"+String.valueOf(nummsd)+".XY";
nummsd++;
header[0]=" MSD Plotting Program";
header[1]=" MSD Plot: "+anam1.trim();
header[2]=" Time (ps)";
header[3]=" MSD";
call=putXY(fname,header,nhead,npts,xx,yy);
if(call==0)
println("PLOT file "+fname+" created");
}
}
| dlpolyquantum/dlpoly_quantum | java/RunMSD.java |
249,078 | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class myFrame extends JFrame implements ActionListener
{
private JLabel mainText;
private JTextField inputLine;
private JTextArea outputBox;
private JButton oddNums;
private JButton evenNums;
private int[] intArray = new int[10];
private int curInt = 0;
public myFrame()
{
super("Laboratory 6");
setLayout(new FlowLayout());
mainText = new JLabel("Enter an Integer and press CR\n");
add(mainText);
inputLine = new JTextField(20);
inputLine.addActionListener(this);
add(inputLine);
oddNums = new JButton("Find Odd Numbers");
oddNums.addActionListener(this);
add(oddNums);
evenNums = new JButton("Find Even Numbers");
evenNums.addActionListener(this);
add(evenNums);
outputBox = new JTextArea(15, 15);
add(outputBox);
}
public void actionPerformed(ActionEvent event)
{
String input;
if (event.getSource() == inputLine)
{
input = inputLine.getText();
intArray[curInt++] = Integer.parseInt(input);
inputLine.setText("");
}
else if (event.getSource() == oddNums)
{
outputBox.append("The odd numbers are:\n");
for (int i = 0; i < curInt; i++)
{
if (!isEven(intArray[i]))
outputBox.append(intArray[i] + "\n");
}
}
else if (event.getSource() == evenNums)
{
outputBox.append("The even numbers are:\n");
for (int i = 0; i < curInt; i++)
{
if (isEven(intArray[i]))
outputBox.append(intArray[i] + "\n");
}
}
}
private boolean isEven(int i)
{
return ((i % 2 == 0) ? true : false);
}
}
public class lab6
{
public static void main(String[] args)
{
myFrame aFrame = new myFrame();
aFrame.setSize(350, 300);
aFrame.setVisible(true);
}
}
| LainIwakura/school-assignments | Java/Lab06/lab6.java |
249,079 | public class Simple
{
public static void main(String[] args)
{
System.out.println("Welcome to ICT 2304");
System.out.println("Object Orienented Programming Laboratory Course");
}
}
| rvdrover/JAVA_Lesson | 2 Lesson/Simple.java |
249,081 | package Laboratory;
import java.util.Scanner;
import java.util.regex.*;
public class Activity4 {
public static void main(String[] args) {
{
try
{
Scanner validation = new Scanner(System.in);
System.out.print("Email: ");
String emailAddress = validation.nextLine();
System.out.print("Number: ");
String number = validation.nextLine();
Pattern emailP = Pattern.compile("[a-z0-9]+@[a-z]+\\.[a-z]");
Matcher emailM = emailP.matcher(emailAddress);
Pattern numberP = Pattern.compile("^\\+63-9[0-9]{2}-[0-9]{3}-[0-9]{4}");
Matcher numberM = numberP.matcher(number);
validation.close();
boolean matchFound = emailM.find();
if (matchFound)
{
System.out.print("\n\tValid Email Address");
}
else
{
System.out.print("\n\tInvalid Email Address");
}
if(numberM.matches() == true)
{
System.out.println("\n\n\tValid Mobile Number");
}
else
{
System.out.println("\n\n\tInvalid Mobile Number");
}
}
catch (Exception e)
{
System.out.println("e.getMessage()");
}
}
}
}
| horhebush/Intermediate-Programming | RegEx.java |
249,082 | package Laboratory;
import java.util.Scanner;
public class Array {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] z = new int[10];
System.out.println("\n\tFind the Greatest and Lowest number using Array");
System.out.println();
for (int i = 0; i < 1; i++)
{
System.out.print("Enter 1st Number: ");
z[i] = input.nextInt();
}
for (int i = 1; i < 2; i++)
{
System.out.print("Enter 2nd Number: ");
z[i] = input.nextInt();
}
for (int i = 2; i < 3; i++)
{
System.out.print("Enter 3rd Number: ");
z[i] = input.nextInt();
}
for (int i = 3; i < 10; i++)
{
System.out.print("Enter " + (i + 1) + "th Number: ");
z[i] = input.nextInt();
}
input.close();
int max = z[0];
int min = z[0];
for (int value = 0; value < 10; value++)
{
if (z[value] > max)
{
max = z[value];
}
if (z[value] < min)
{
min = z[value];
}
}
System.out.println();
System.out.println("Greatest Value: " + max);
System.out.print("Lowest Value: " + min);
}
}
| horhebush/Fundamentals-of-Programming | Array.java |
249,083 | package opuntia;
public enum BOT {
NONE(0),
MINER(1),
SOLDIER(2),
BUILDER(3),
SAGE(4),
WATCHTOWER(5),
LABORATORY(6),
;
private final int id;
BOT(int id) { this.id = id; }
public int getValue() { return id; }
}
| JackLee9355/Battlecode2022 | src/opuntia/BOT.java |
249,084 | package rebutia;
public enum BOT {
NONE(0),
MINER(1),
SOLDIER(2),
BUILDER(3),
SAGE(4),
WATCHTOWER(5),
LABORATORY(6),
;
private final int id;
BOT(int id) { this.id = id; }
public int getValue() { return id; }
}
| JackLee9355/Battlecode2022 | src/rebutia/BOT.java |
249,088 | import java.util.ArrayList;
import jdk.nashorn.api.tree.WithTree;
public class Ocean
{
private int length;
private int width;
public Ocean(int length, int width)
{
this.length = length;
this.width = width;
}
public void displayOcean()
{
Square board = new Square();
ArrayList<ArrayList<String>> myBoard = board.getSquare();
ArrayList<String> boardWidth = new ArrayList<String>(width);
for(int i = 0; i < length; i++)
{
myBoard.add(boardWidth);
}
for(int i = 0; i < this.length; i++)
{
for(int j = 0; j < this.width; j++)
{
myBoard.get(i).add("[ ]");
}
}
for(int i = 0; i < this.length; i++)
{
for(int j = 0; j < this.width; j++)
{
System.out.print(myBoard.get(i).get(j));
}
System.out.println();
}
}
} // end class Ocean | CodecoolGlobal/battle-ship-in-the-oo-way-thejavawarriors | Ocean.java |
249,090 |
/**
* (Fill in description and author info here)
*/
public class Ocean
{
/**
* Represent an ocean of the given dimensions.
* @param height The height of the ocean.
* @param width The width of the ocean.
*/
public Ocean(int height, int width)
{
// some code needs to go here
}
/**
* Return the fish at the given location, if any.
* @param row The desired row.
* @param col The desired column.
* @return The fish at the given location, or null if there is none.
*/
public Fish getFishAt(int row, int col)
{
// put code here
return null;
}
/**
* @return The height of the ocean.
*/
public int getHeight()
{
// put something here
return 200;
}
/**
* @return The width of the ocean.
*/
public int getWidth()
{
// and something here
return 200;
}
}
| Danhfg/Simulacao_LP | src/Ocean.java |
249,093 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class Desert here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class Ocean extends World
{
OceanTreasures gemsFactory;
public Ocean()
{
super(800, 600, 1);
gemsFactory = new GemsFactory();
addObject(new Ship(), 270, 210);
addObject(gemsFactory.getActor(), (int)(10*Math.random())*60, (int)(8*Math.random())*60);
}
}
| nguyensjsu/sp18-202-nintendo | Pirates/Ocean.java |
249,095 | /* Ocean.java */
/**
* The Ocean class defines an object that models an ocean full of sharks and
* fish. Descriptions of the methods you must implement appear below. They
* include a constructor of the form
*
* public Ocean(int i, int j, int starveTime);
*
* that creates an empty ocean having width i and height j, in which sharks
* starve after starveTime timesteps.
*
* See the README file accompanying this project for additional details.
*/
public class Ocean {
/**
* Do not rename these constants. WARNING: if you change the numbers, you
* will need to recompile Test4.java. Failure to do so will give you a very
* hard-to-find bug.
*/
public final static int EMPTY = 0;
public final static int SHARK = 1;
public final static int FISH = 2;
/**
* Define any variables associated with an Ocean object here. These
* variables MUST be private.
*/
private int width;
private int height;
private int starveTime;
private OceanTile[][] grid;
/**
* The following methods are required for Part I.
*/
/**
* Ocean() is a constructor that creates an empty ocean having width i and
* height j, in which sharks starve after starveTime timesteps.
* @param i is the width of the ocean.
* @param j is the height of the ocean.
* @param starveTime is the number of timesteps sharks survive without food.
*/
public Ocean(int i, int j, int starveTime) {
width = i;
height = j;
this.starveTime = starveTime;
grid = new OceanTile[width][height];
for(int x = 0; x < width; x++) {
for(int y = 0; y < height; y++) {
grid[x][y] = new EmptyTile(x, y);
}
}
}
/**
* width() returns the width of an Ocean object.
* @return the width of the ocean.
*/
public int width() {return width;}
/**
* height() returns the height of an Ocean object.
* @return the height of the ocean.
*/
public int height() {return height;}
/**
* starveTime() returns the number of timesteps sharks survive without food.
* @return the number of timesteps sharks survive without food.
*/
public int starveTime() {return starveTime;}
/**
* addFish() places a fish in cell (x, y) if the cell is empty. If the
* cell is already occupied, leave the cell as it is.
* @param x is the x-coordinate of the cell to place a fish in.
* @param y is the y-coordinate of the cell to place a fish in.
*/
public void addFish(int x, int y) {
if(grid[x][y].getContents() == EMPTY)
grid[x][y] = new FishTile(x, y);
}
/**
* addShark() (with two parameters) places a newborn shark in cell (x, y) if
* the cell is empty. A "newborn" shark is equivalent to a shark that has
* just eaten. If the cell is already occupied, leave the cell as it is.
* @param x is the x-coordinate of the cell to place a shark in.
* @param y is the y-coordinate of the cell to place a shark in.
*/
public void addShark(int x, int y) {
if(grid[x][y].getContents() == EMPTY)
grid[x][y] = new SharkTile(x, y, starveTime);
}
/**
* cellContents() returns EMPTY if cell (x, y) is empty, FISH if it contains
* a fish, and SHARK if it contains a shark.
* @param x is the x-coordinate of the cell whose contents are queried.
* @param y is the y-coordinate of the cell whose contents are queried.
*/
public int cellContents(int x, int y) {return grid[x][y].getContents();}
public int cellContents(int i) {return cellContents(i % width, i / width);}
/**
* timeStep() performs a simulation timestep as described in README.
* @return an ocean representing the elapse of one timestep.
*/
public Ocean timeStep() {
Ocean futureOcean = new Ocean(width, height, starveTime);
int[] surroundings;
for(int y = 0; y < height; y++) {
for(int x = 0; x < width; x++) {
surroundings = getSurroundings(validateX(x), validateY(y));
futureOcean.grid[x][y] = grid[x][y].step(surroundings[FISH], surroundings[SHARK]);
}
}
return futureOcean;
}
private int[] getSurroundings(int xCoord, int yCoord) {
int[] surroundings = new int[3];
//System.out.println("origin = " + xCoord + ", " + yCoord);
for(int y = yCoord - 1; y <= yCoord + 1; y++) {
for(int x = xCoord - 1; x <= xCoord + 1; x++) {
if(!((validateX(x) == xCoord) && (validateY(y) == yCoord))){
//System.out.println("\tchecking: " + validateX(x) + ", " + validateY(y));
if(cellContents(validateX(x), validateY(y)) == FISH) {
// System.out.println("\t\tfish found");
surroundings[FISH]++;
}
else if(cellContents(validateX(x), validateY(y)) == SHARK) {
// System.out.println("\t\tshark found");
surroundings[SHARK]++;
}
}
}
}
return surroundings;
}
private int validateX(int x) {
if(x < 0)
return width - 1;
if(x >= width)
return 0;
return x;
}
private int validateY(int y) {
if(y < 0)
return height - 1;
if(y >= height)
return 0;
return y;
}
/**
* The following method is required for Part II.
*/
/**
* addShark() (with three parameters) places a shark in cell (x, y) if the
* cell is empty. The shark's hunger is represented by the third parameter.
* If the cell is already occupied, leave the cell as it is. You will need
* this method to help convert run-length encodings to Oceans.
* @param x is the x-coordinate of the cell to place a shark in.
* @param y is the y-coordinate of the cell to place a shark in.
* @param feeding is an integer that indicates the shark's hunger. You may
* encode it any way you want; for instance, "feeding" may be the
* last timestep the shark was fed, or the amount of time that has
* passed since the shark was last fed, or the amount of time left
* before the shark will starve. It's up to you, but be consistent.
*/
public void addShark(int x, int y, int feeding) {
if(grid[x][y].getContents() == EMPTY)
grid[x][y] = new SharkTile(x, y, feeding);
}
/**
* The following method is required for Part III.
*/
/**
* sharkFeeding() returns an integer that indicates the hunger of the shark
* in cell (x, y), using the same "feeding" representation as the parameter
* to addShark() described above. If cell (x, y) does not contain a shark,
* then its return value is undefined--that is, anything you want.
* Normally, this method should not be called if cell (x, y) does not
* contain a shark. You will need this method to help convert Oceans to
* run-length encodings.
* @param x is the x-coordinate of the cell whose contents are queried.
* @param y is the y-coordinate of the cell whose contents are queried.
*/
public int sharkFeeding(int x, int y) {
if(grid[x][y] instanceof SharkTile)
return ((SharkTile)grid[x][y]).getHunger();
return -1;
}
public int sharkFeeding(int i) {return sharkFeeding(i % width, i / width);}
abstract class OceanTile {
int xCoord;
int yCoord;
int contains;
public int getContents() {return contains;}
public abstract OceanTile step(int fish, int sharks);
}
final class SharkTile extends OceanTile {
int hunger;
public SharkTile(int x, int y, int hunger) {
xCoord = x;
yCoord = y;
contains = Ocean.SHARK;
this.hunger = hunger;
}
public OceanTile step(int fish, int sharks) {
if(fish > 0)
hunger = starveTime() + 1;
if(hunger - 1 < 0)
return new EmptyTile(xCoord, yCoord);
return new SharkTile(xCoord, yCoord, hunger - 1);
}
public int getHunger() {return hunger;}
}
final class EmptyTile extends OceanTile {
public EmptyTile(int x, int y) {
xCoord = x;
yCoord = y;
contains = Ocean.EMPTY;
}
public OceanTile step(int fish, int sharks) {
if(fish < 2)
return new EmptyTile(xCoord, yCoord);
else if(sharks < 2)
return new FishTile(xCoord, yCoord);
return new SharkTile(xCoord, yCoord, starveTime());
}
}
final class FishTile extends OceanTile {
public FishTile(int x, int y) {
xCoord = x;
yCoord = y;
contains = Ocean.FISH;
}
public OceanTile step(int fish, int sharks) {
if(sharks == 1)
return new EmptyTile(xCoord, yCoord);
else if(sharks > 1)
return new SharkTile(xCoord, yCoord, starveTime());
return new FishTile(xCoord, yCoord);
}
}
public void printGrid() {
for(int i = 0; i < width + 2; i++)
System.out.print("_");
System.out.println();
for(int y = 0; y < height; y++) {
System.out.print("|");
for(int x = 0; x < width; x++) {
if(grid[x][y] instanceof EmptyTile)
System.out.print(" ");
else if(grid[x][y] instanceof FishTile)
System.out.print("~");
else
System.out.print("S"); //System.out.print(sharkFeeding(x, y));
}
System.out.println("|");
}
for(int i = 0; i < width + 2; i++)
System.out.print("_");
System.out.println();
}
public static void main(String[] args) {
Ocean o = new Ocean(50, 37, 3);
o.printGrid();
o.addFish(1, 1);
System.out.println();
o.printGrid();
}
} | JBarth86/Proj1 | src/Ocean.java |
249,096 | import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class OceanGrid
{
private Location[][] ocean;
/**
* Creates a new OceanGrid enum to distinguish a space on the grid
*/
public enum Location
{
WATER, SHIP, ATTACKEDWATER, ATTACKEDSHIP
}
/**
* Constructs an OceanGrid object that is a 10 x 10 2D Array
*/
public OceanGrid()
{
ocean = new Location[10][10];
for (int x = 0; x < ocean.length; x++)
for (int y = 0; y < ocean[0].length; y++)
ocean[x][y] = Location.WATER;
}
/**
* addShip adds a ship to the OceanGrid
* @param choice determines whether the user will want the ship placed vertically or horizontally
* @param ship the shipType of the ship being added
* @param x the number of the column where the ship will be added
* @param y the number of the row where the ship will be added
*/
public boolean addShip(int choice, Ship ship, int x, int y)
{
if (choice == 0)
{
if (y > 10-ship.getSize()) return false;
for (int i = 0; i<ship.getSize(); i++ )
{
if (ocean[x][y+i] == Location.SHIP)
return false;
}
for (int i = 0; i<ship.getSize(); i++ )
{
ocean[x][y+i] = Location.SHIP;
}
return true;
}
else if (choice == 1)
{
if ( x > 10 - ship.getSize()) return false;
for (int i = 0; i < ship.getSize(); i++)
{
if (ocean[x+i][y] == Location.SHIP)
return false;
}
for (int i = 0; i < ship.getSize(); i++)
{
ocean[x+i][y] = Location.SHIP;
}
return true;
}
return false;
}
/**
* attack determines what Location enum was selected by the user
* @param x the x-coordinate of the selected location
* @param y the y-coordinate of the selected location
*/
public Location attack(int x, int y)
{
Location temp = ocean[x][y];
switch (temp)
{
case ATTACKEDSHIP:
return Location.ATTACKEDSHIP;
case ATTACKEDWATER:
return Location.ATTACKEDWATER;
case WATER:
ocean[x][y] = Location.ATTACKEDWATER; break;
case SHIP:
ocean[x][y] = Location.ATTACKEDSHIP; break;
}
return temp;
}
/**
* shipExists determines if a ship still remains on an OceanGrid
* @return whether or not a ship exists
*/
public boolean shipExists()
{
for (int x = 0; x < ocean.length; x++)
{
for (int y = 0; y < ocean[0].length; y++)
{
if(ocean[x][y] == Location.SHIP)
{
return true;
}
}
}
return false;
}
/**
* getGrid returns the OceanGrid
* @return the current OceanGrid
*/
public Location[][] getGrid()
{
return ocean;
}
/**
* getFullButtonGrid gets the bottom OceanGrid set up
* @return a 2D Array of JButtons
*/
public JButton[][] getFullButtonGrid()
{
JButton[][] ret = new JButton[10][10];
for (int a = 0; a < 10; a ++)
for (int b = 0; b < 10; b++)
{
JButton temp = new JButton();
temp.setPreferredSize(new Dimension(25, 25));
switch (ocean[a][b])
{
case SHIP:
temp.setBackground(Color.black);
temp.setOpaque(true);
break;
case WATER:
temp.setBackground(Color.blue);
temp.setOpaque(true);
break;
case ATTACKEDSHIP:
temp.setBackground(Color.red);
temp.setOpaque(true);
break;
case ATTACKEDWATER:
temp.setBackground(Color.gray);
temp.setOpaque(true);
break;
}
ret[a][b] = temp;
}
return ret;
}
/**
* getLimitedButtonGrid gets the upper OceanGrid set up
* @return a 2D Array of JButtons
*/
public JButton[][] getLimitedButtonGrid()
{
JButton[][] ret = new JButton[10][10];
for (int a = 0; a < 10; a ++)
for (int b = 0; b < 10; b++)
{
JButton temp = new JButton();
temp.setPreferredSize(new Dimension(25, 25));
switch (ocean[a][b])
{
case SHIP:
temp.setBackground(Color.blue);
temp.setOpaque(true);
break;
case WATER:
temp.setBackground(Color.blue);
temp.setOpaque(true);
break;
case ATTACKEDSHIP:
temp.setBackground(Color.red);
temp.setOpaque(true);
break;
case ATTACKEDWATER:
temp.setBackground(Color.lightGray);
temp.setOpaque(true);
break;
}
ret[a][b] = temp;
}
return ret;
}
} | michaelzetune/Battleship | OceanGrid.java |
249,097 | package battleship;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
public class OceanTest {
Ocean ocean;
@Before
public void setUp() throws Exception {
ocean = new Ocean();
}
@Test
public void testPrint() {
// ocean.print();
}
@Test
public void testPlaceOneShipRandomly() {
ocean.placeAllShipsRandomly();
// ocean.print();
}
@Test
public void testShootAt() {
ocean.placeAllShipsRandomly();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
ocean.shootAt(i, j);
}
}
ocean.print();
}
}
| dingz212445/cit590-Battleship | OceanTest.java |
249,100 | import greenfoot.*;
public class Ryba extends Actor
{
boolean zlapana = false;
Woda ocean;
int v;
public Ryba(){
ocean = new Woda();
}
public void act() {
if (zlapana){
wyciagajRybe();
} else {
move(v);
odbicia();
}
lapRyby();
}
private void odbicia(){
if(isAtEdge()) {
if (getY()==0 || getY()==599) setRotation(-getRotation());
else {
setRotation(180-getRotation());
getImage().mirrorVertically(); }
}
}
private void wyciagajRybe(){
setLocation(getX(), getY()-5);
if (isAtEdge()) {
zlapana = false;
getWorld().removeObject(this);
}
}
private void lapRyby(){
if (Greenfoot.mousePressed(this)){
String nazwa=this.getClass().getName();
if(nazwa=="Pretnik") {
ocean.liczbaP++;
} else if(nazwa=="Zlota") {
ocean.liczbaZ++;
} else {
ocean.liczbaR++;
}
zlapana = true;
getWorld().addObject(new Haczyk(), this.getX(), this.getY());
}
}
}
| MistrzowieKodowania/akwariumFB | Ryba.java |
249,103 | package gfx;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.imageio.ImageIO;
import debug.Debug;
import tile.Tiles;
public class Sources {
public static Tiles[] tiles;
// --------TILES--------------
public static BufferedImage FILLER;
public static BufferedImage GRASS;
public static BufferedImage DIRT;
public static BufferedImage WOODENPLANKS;
public static BufferedImage SAND;
public static BufferedImage HOLE;
public static BufferedImage HOLE_SIMPLE;
public static BufferedImage WOODEN_DOOR_TOP;
public static BufferedImage WOODEN_DOOR_BOTTOM;
public static BufferedImage WOODEN_DOOR_CLOSED;
public static BufferedImage WOODEN_DOOR_OPEN;
public static BufferedImage STONE_WALL_DOUBLE;
public static BufferedImage DUST_STONE;
public static BufferedImage ROCK;
public static BufferedImage STONE_FLOORING;
public static BufferedImage GLASS;
public static BufferedImage WOODEN_BRIDGE;
public static BufferedImage LOG;
public static BufferedImage SIGN;
public static BufferedImage PEBBLES;
public static BufferedImage SMALL_CHEST;
public static BufferedImage OAK_TREE_STUMP;
public static BufferedImage OAK_SAPLING;
public static BufferedImage WOODEN_BARREL;
public static BufferedImage STONE;
public static BufferedImage IRON_BUCKET;
public static BufferedImage EFFECT_FOOTPRINT;
public static BufferedImage WATER_FLOW;
public static BufferedImage STONE_WALL;
public static BufferedImage BLACK;
public static BufferedImage STICK;
public static BufferedImage DARK_GRASS;
public static BufferedImage STONE_TILE;
public static BufferedImage WORKBENCH_LEFT;
public static BufferedImage WORKBENCH_RIGHT;
public static BufferedImage CONTAINER_AREA;
public static BufferedImage[] OCEAN = new BufferedImage[3];
public static BufferedImage[] playerUp;
public static BufferedImage[] playerDown;
public static BufferedImage[] playerLeft;
public static BufferedImage[] playerRight;
public static BufferedImage playerSheet;
// Entities
public static BufferedImage MOB_PIG;
// GUI
public static BufferedImage BUTTON_HOVER;
public static BufferedImage BUTTON_LOCKED;
public static BufferedImage BUTTON;
public static BufferedImage BASIC_BUTTON;
public static BufferedImage MOUSE_NOINTERACT;
public static BufferedImage GUI_ERROR;
public static BufferedImage GUI_MAGNIFY;
public static BufferedImage GUI_NEWMAP;
public static BufferedImage GUI_FULLSCREEN;
public static BufferedImage GUI_BOX;
public static BufferedImage[] playerRightAttack;
public static BufferedImage tree;
public static BufferedImage shadow;
public static BufferedImage healthbar;
public static BufferedImage energybar;
public static BufferedImage hotbar;
public static BufferedImage water1;
public static BufferedImage water2;
public static BufferedImage water3;
public static BufferedImage[] playerRightHead;
public static BufferedImage[] playerLeftHead;
public static BufferedImage inventory;
public static BufferedImage invSelect;
public static BufferedImage rain;
public static BufferedImage[] splash;
public static BufferedImage[] weather;
public static BufferedImage[][] MOB_CHICKEN;
public static BufferedImage pickaxe;
public static BufferedImage spritesheet;
public static BufferedImage player;
public static BufferedImage grass;
public static BufferedImage stonebrick;
// ITEMS////
public static BufferedImage wood;
public static BufferedImage torch;
public static BufferedImage scythe;
public static BufferedImage scytheR;
public static BufferedImage ironaxe;
public static BufferedImage TOOL_AXE_IRON;
// Entities
public static BufferedImage tallgrass;
public static BufferedImage pinetree;
public static BufferedImage WORLD_DEMO_TEMP_DELETE;
//
int ms = 16;
//
public void loadImages() {
tiles = new Tiles[200];
playerUp = new BufferedImage[5];
playerDown = new BufferedImage[5];
playerLeft = new BufferedImage[5];
playerRight = new BufferedImage[5];
playerRight = new BufferedImage[5];
playerRightHead = new BufferedImage[3];
playerLeftHead = new BufferedImage[3];
playerRightAttack = new BufferedImage[3];
weather = new BufferedImage[3];
MOB_CHICKEN = new BufferedImage[2][4];
splash = new BufferedImage[3];
OCEAN = new BufferedImage[4];
try {
// Tiles;
// InputStream e =
// this.getClass().getResourceAsStream("//Tiles/Outside/Grass/grass.png");
// GRASS = ImageIO.read(e);
// GRASS =
// ImageIO.read(new FileInputStream(("Textures/Tiles/Outside/Grass/grass.png")));
FILLER = ImageIO.read(new FileInputStream("Textures/filler.png"));
GRASS = ImageIO.read(new FileInputStream("Textures/Tiles/Outside/Grass/grass.png"));
HOLE = ImageIO.read(new FileInputStream("Textures/Tiles/Outside/hole.png"));
HOLE_SIMPLE = ImageIO.read(new FileInputStream("Textures/Tiles/Outside/holesimple.png"));
DARK_GRASS = ImageIO.read(new FileInputStream("Textures/Tiles/Outside/Grass/darkgrass.png"));
DIRT = ImageIO.read(new FileInputStream(("Textures/Tiles/Outside/Dirt/dirt.png")));
WOODENPLANKS = ImageIO.read(new FileInputStream("Textures/Tiles/Buildings/planks.png"));
SAND = ImageIO.read(new FileInputStream(("Textures/Tiles/Outside/Sand/sand.png")));
ROCK = ImageIO.read(new FileInputStream(("Textures/Tiles/Outside/Obstacles/rock.png")));
STONE_FLOORING = ImageIO
.read(new FileInputStream(("Textures/Tiles/Outside/Obstacles/stoneflooring.png")));
GLASS = ImageIO.read(new FileInputStream(("Textures/Tiles/Outside/Obstacles/glass.png")));
WOODEN_BRIDGE = ImageIO
.read(new FileInputStream(("Textures/Tiles/Outside/Obstacles/woodenbridge.png")));
LOG = ImageIO.read(new FileInputStream(("Textures/Tiles/Outside/Obstacles/log.png")));
STONE_WALL = ImageIO.read(new FileInputStream(("Textures/Tiles/Outside/Obstacles/stonewall.png")));
SIGN = ImageIO.read(new FileInputStream(("Textures/Tiles/Outside/Obstacles/sign.png")));
PEBBLES = ImageIO.read(new FileInputStream(("Textures/Tiles/Outside/Obstacles/pebbles.png")));
SMALL_CHEST = ImageIO.read(new FileInputStream(("Textures/Tiles/Container/chest.png")));
OAK_TREE_STUMP = ImageIO.read(new FileInputStream(("Textures/Tiles/Nature/treestump.png")));
OAK_SAPLING = ImageIO.read(new FileInputStream(("Textures/Tiles/Nature/Saplings/oaksapling.png")));
WOODEN_BARREL = ImageIO.read(new FileInputStream(("Textures/Tiles/Container/woodenbarrel.png")));
STONE = ImageIO.read(new FileInputStream(("Textures/Things/Ressources/stone.png")));
IRON_BUCKET = ImageIO.read(new FileInputStream(("Textures/Things/Tools/metalbucket.png")));
BLACK = ImageIO.read(new FileInputStream(("Textures/Tiles/Buildings/black.png")));
STICK = ImageIO.read(new FileInputStream(("Textures/Tiles/Outside/Obstacles/stick.png")));
STONE_TILE = ImageIO.read(new FileInputStream("Textures/Tiles/Nature/stone.png"));
WORKBENCH_LEFT = ImageIO.read(new FileInputStream("Textures/Tiles/Utilities/workbench_left.png"));
WORKBENCH_RIGHT = ImageIO.read(new FileInputStream("Textures/Tiles/Utilities/workbench_right.png"));
WOODEN_DOOR_TOP = ImageIO
.read(new FileInputStream("Textures/Tiles/Furniture/WoodenDoorTopClosed.png"));
WOODEN_DOOR_BOTTOM = ImageIO
.read(new FileInputStream("Textures/Tiles/Furniture/WoodenDoorBottomClosed.png"));
WOODEN_DOOR_CLOSED = ImageIO.read(new FileInputStream("Textures/Tiles/Furniture/Wooden_Door.png"));
WOODEN_DOOR_OPEN = ImageIO.read(new FileInputStream("Textures/Tiles/Furniture/Wooden_Door_Open.png"));
STONE_WALL_DOUBLE = ImageIO
.read(new FileInputStream("Textures/Tiles/Furniture/Stone_Doublewall.png"));
DUST_STONE = ImageIO.read(new FileInputStream("Textures/Tiles/Ores/stonefloor.png"));
// WORLD_DEMO_TEMP_DELETE = ImageIO.read(new
// File("D:/world1/2016_08_23_16-35-54.png"));
// Animated
WATER_FLOW = ImageIO.read(new FileInputStream(("Textures/Tiles/Liquid/Flow/FlowWater.png")));
OCEAN[0] = ImageIO.read(new FileInputStream("Textures/Tiles/Liquid/water1.png"));
OCEAN[1] = ImageIO.read(new FileInputStream("Textures/Tiles/Liquid/water2.png"));
OCEAN[2] = ImageIO.read(new FileInputStream("Textures/Tiles/Liquid/water3.png"));
OCEAN[3] = ImageIO.read(new FileInputStream("Textures/Tiles/Liquid/water2.png"));
EFFECT_FOOTPRINT = ImageIO.read(new FileInputStream(("Textures/Effects/footprint.png")));
CONTAINER_AREA = ImageIO.read(new FileInputStream(("Textures/Tiles/Container/container.png")));
// TOOLS
TOOL_AXE_IRON = ImageIO.read(new FileInputStream("Textures/Things/Tools/ironaxe.png"));
// Mobs
BufferedImage chickenSheet = ImageIO.read(new FileInputStream("Textures/Mobs/chicken.png"));
MOB_PIG = ImageIO.read(new FileInputStream(("Textures/Mobs/pig.png")));
int base = 16;
MOB_CHICKEN[0][0] = chickenSheet.getSubimage(base * 0, base * 0, base, base);
MOB_CHICKEN[0][1] = chickenSheet.getSubimage(base * 1, base * 0, base, base);
MOUSE_NOINTERACT = ImageIO.read(new FileInputStream("Textures/GUI/mouse.png"));
GUI_ERROR = ImageIO.read(new FileInputStream("Textures/GUI/error.png"));
GUI_MAGNIFY = ImageIO.read(new FileInputStream("Textures/GUI/Editor/magnify.png"));
GUI_NEWMAP = ImageIO.read(new FileInputStream("Textures/GUI/Editor/newfile.png"));
GUI_FULLSCREEN = ImageIO.read(new FileInputStream("Textures/GUI/fullscreen.png"));
GUI_BOX = ImageIO.read(new FileInputStream("Textures/GUI/button.png"));
BASIC_BUTTON = ImageIO.read(new FileInputStream("Textures/GUI/Basic_Button.png"));
BUTTON = ImageIO.read(new FileInputStream("Textures/GUI/GUI_Button.png"));
BUTTON_LOCKED = ImageIO.read(new FileInputStream("Textures/GUI/GUI_Button_Locked.png"));
BUTTON_HOVER = ImageIO.read(new FileInputStream("Textures/GUI/GUI_Button_Hover.png"));
// grass =
// ImageIO.read(new FileInputStream(("Textures/Tiles/grass.png")));
// healthbar =
// ImageIO.read(new FileInputStream("Textures/Tiles/grass.png"));
stonebrick = ImageIO.read(new FileInputStream("Textures/Tiles/Buildings/brick.png"));
// Name - Texture - ID - isSolid - entityTile
/*
* tiles[0] = new Tiles("Null", null, 0, false, false, false, 0);
* tiles[1] = new Tiles("Grass", grass, 1, false, false, true, 1);
* tiles[2] = new Tiles("Sand",
* ImageIO.read(new FileInputStream("Textures/Tiles/sand.png")
* ), 2, false, false, false, 1); tiles[3] = new Tiles("Stone Brick"
* , ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Buildings/brick.png")), 3, true, false, false, 1);
* tiles[4] = new Tiles("Shaded Stone Brick",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Buildings/shadedbrick.png")), 4, true, false, false, 1);
* tiles[5] = new Tiles("Wooden Planks",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Buildings/planks.png")), 5, false, false, false, 1);
* tiles[6] = new Tiles("Stone",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Nature/stone.png")), 6, true, false, false, 1); tiles[7]
* = new Tiles("Shaded Planks",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Buildings/planksshaded.png")), 7, false, false, false,
* 1); tiles[8] = new Tiles("Shaded Grass",
* ImageIO.read(Sources.class.getResourceAsStream((
* "/Tiles/shadedgrass.png"))), 8, false, false, false, 1);
* tiles[15] = new Tiles("Dirt",
* ImageIO.read(Sources.class.getResourceAsStream((
* "/Tiles/Outside/Dirt/dirt.png"))), 15, false, false, false, 1);
* tiles[9] = new Tiles("Stone",
* ImageIO.read(Sources.class.getResourceAsStream((
* "/Tiles/Ores/stonefloor.png"))), 8, false, false, false, 1);
* tiles[10] = new Tiles("Water",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Liquid/water1.png")), 10, false, false, false, 1);
* tiles[11] = new Tiles("Water - Grass - Down",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Liquid/Grass/watergrassDown.png")), 11, false, false,
* false, 1); tiles[12] = new Tiles("Water - Grass - Left",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Liquid/Grass/watergrassLeft.png")), 12, false, false,
* false, 1); tiles[20] = new Tiles("Black",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Buildings/black.png")), 20, false, false, false, 1);
* tiles[21] = new Tiles("Drawer",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Furniture/drawer.png")), 21, true, false, false, 1);
* tiles[22] = new Tiles("Bed Top",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Furniture/bedtop.png")), 22, true, false, false, 1);
* tiles[25] = new Tiles("Fire Pit",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Structures/firepit.png")), 25, true, false, false, 2);
* tiles[23] = new Tiles("Bed Bottom",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Furniture/bedbottom.png")), 23, true, false, false, 1);
* tiles[40] = new Tiles("Zatarium Ore",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Ores/zatariumore.png")), 40, true, false, false, 1);
* tiles[50] = new Tiles("Dead Grass",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Nature/deadgrass.png")), 50, false, false, false, 1);
* tiles[51] = new Tiles("Grass Variation 1",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Outside/Grass/grassVar1.png")), 51, false, false, true,
* 1); tiles[52] = new Tiles("Grass Variation 2",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Outside/Grass/grassVar2.png")), 52, false, false, true,
* 1); tiles[55] = new Tiles("Tree Stump",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Nature/treestump.png")), 55, true, false, false, 2);
* tiles[120] = new Tiles("Chest",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Furniture/chest.png")), 120, true, false, false, 1);
* tiles[110] = new Tiles("Fence H",
* ImageIO.read(Sources.class.getResourceAsStream(
* "/Tiles/Outside/fenceH.png")), 110, true, false, false, 3);
* tiles[60] = new Tiles("Tall Grass Tile", null, 60, false, true,
* false, 3);
*/
spritesheet = ImageIO.read(new FileInputStream("Textures/Player/playerSpriteSheet.png"));
playerDown[0] = spritesheet.getSubimage(0, 0, 16, 32);
playerDown[1] = spritesheet.getSubimage(0, 0, 16, 32);
playerDown[2] = spritesheet.getSubimage(16, 0, 16, 32);
playerDown[3] = spritesheet.getSubimage(32, 0, 16, 32);
playerDown[4] = spritesheet.getSubimage(16, 0, 16, 32);
// tallgrass =
// ImageIO.read(new FileInputStream("Textures/Tiles/Nature/tallgrass.png"));
pinetree = ImageIO.read(new FileInputStream("Textures/Tiles/Nature/pinetree.png"));
playerRight[0] = ImageIO.read(new FileInputStream("Textures/Player/playerRightStill.png"));
playerRight[1] = ImageIO.read(new FileInputStream("Textures/Player/playerRight1.png"));
playerRight[2] = ImageIO.read(new FileInputStream("Textures/Player/playerRight2.png"));
playerRight[3] = ImageIO.read(new FileInputStream("Textures/Player/playerRight3.png"));
playerRight[4] = ImageIO.read(new FileInputStream("Textures/Player/playerRight4.png"));
playerRightAttack[0] = ImageIO
.read(new FileInputStream("Textures/Player/Attack/playerRightAttack1.png"));
playerRightAttack[1] = ImageIO
.read(new FileInputStream("Textures/Player/Attack/playerRightAttack2.png"));
playerRightAttack[2] = ImageIO
.read(new FileInputStream("Textures/Player/Attack/playerRightAttack3.png"));
playerLeft[0] = ImageIO.read(new FileInputStream("Textures/Player/playerLeftStill.png"));
playerLeft[1] = ImageIO.read(new FileInputStream("Textures/Player/playerLeft1.png"));
playerLeft[2] = ImageIO.read(new FileInputStream("Textures/Player/playerLeft2.png"));
playerLeft[3] = ImageIO.read(new FileInputStream("Textures/Player/playerLeft3.png"));
playerLeft[4] = ImageIO.read(new FileInputStream("Textures/Player/playerLeft4.png"));
playerRightHead[0] = ImageIO.read(new FileInputStream("Textures/Player/playerRightHead.png"));
playerRightHead[1] = ImageIO.read(new FileInputStream("Textures/Player/rightHeadBlink1.png"));
playerRightHead[2] = ImageIO.read(new FileInputStream("Textures/Player/rightHeadBlink2.png"));
playerLeftHead[0] = ImageIO.read(new FileInputStream("Textures/Player/playerLeftHead.png"));
playerLeftHead[1] = ImageIO.read(new FileInputStream("Textures/Player/leftHeadBlink1.png"));
playerLeftHead[2] = ImageIO.read(new FileInputStream("Textures/Player/leftHeadBlink2.png"));
weather[0] = ImageIO.read(new FileInputStream("Textures/GUI/sunweather.png"));
weather[1] = ImageIO.read(new FileInputStream("Textures/GUI/rainweather.png"));
weather[2] = ImageIO.read(new FileInputStream("Textures/GUI/stormweather.png"));
// playerRight[3] =
// ImageIO.read(new FileInputStream("Textures/Player/playerRightStill.png"));
tree = ImageIO.read(new FileInputStream("Textures/tree.png"));
tallgrass = ImageIO.read(new FileInputStream("Textures/Tiles/Nature/tallgrass.png"));
shadow = ImageIO.read(new FileInputStream("Textures/Effects/treeshadow.png"));
healthbar = ImageIO.read(new FileInputStream("Textures/GUI/healthbar.png"));
energybar = ImageIO.read(new FileInputStream("Textures/GUI/energybar.png"));
hotbar = ImageIO.read(new FileInputStream("Textures/GUI/hotbar.png"));
inventory = ImageIO.read(new FileInputStream("Textures/GUI/inventory.png"));
invSelect = ImageIO.read(new FileInputStream("Textures/GUI/hotbarselect.png"));
rain = ImageIO.read(new FileInputStream("Textures/Effects/rain.png"));
splash[0] = ImageIO.read(new FileInputStream("Textures/Effects/rainsplash1.png"));
splash[1] = ImageIO.read(new FileInputStream("Textures/Effects/rainsplash2.png"));
splash[2] = ImageIO.read(new FileInputStream("Textures/Effects/rainsplash3.png"));
///////// ITEMS //////////
pickaxe = ImageIO.read(new FileInputStream("Textures/Things/pickaxe.png"));
torch = ImageIO.read(new FileInputStream("Textures/Things/torch.png"));
wood = ImageIO.read(new FileInputStream("Textures/Things/wood.png"));
scythe = ImageIO.read(new FileInputStream("Textures/Things/scythe.png"));
scytheR = ImageIO.read(new FileInputStream("Textures/Things/scytheR.png"));
ironaxe = ImageIO.read(new FileInputStream("Textures/Things/Tools/ironaxe.png"));
} catch (IOException e) {
e.printStackTrace();
System.out.println("Failed to load some images or the FileInputStream might be corrupt! Oh noes :o");
} catch (IllegalArgumentException e) {
System.out.println("Failed to load some images or they may be corrupt!");
System.out.println("--------------------");
e.printStackTrace();
System.out.println("--------------------");
}
}
public void loadImage(String path) {
}
}
| Jason-Addison/Flet | src/gfx/Sources.java |
249,105 | import javax.swing.*;
import javax.swing.plaf.metal.*;
import java.awt.*;
import java.awt.event.*;
public class LookAndFeelDemo extends JFrame implements ActionListener {
private JPanel panel;
private JButton nimbus, system, metal, ocean;
public LookAndFeelDemo() {
super("Look and Feel Demo");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(800, 600);
setLayout(new FlowLayout(FlowLayout.LEFT));
panel = new JPanel();
nimbus = new JButton("Nimbus");
nimbus.addActionListener(this);
system = new JButton("System");
system.addActionListener(this);
metal = new JButton("Metal");
metal.addActionListener(this);
ocean = new JButton("Ocean");
ocean.addActionListener(this);
panel.add(nimbus);
panel.add(system);
panel.add(metal);
panel.add(ocean);
add(panel);
}
public static void setLookAndFeel() {
try {
UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
} catch (Exception e) {
System.err.println(e);
}
}
public void setLookAndFeel(String className) {
try {
UIManager.setLookAndFeel(className);
} catch (Exception e) {
System.err.println(e);
}
SwingUtilities.updateComponentTreeUI(this);
}
public void setLookAndFeel(LookAndFeel lookAndFeel) {
try {
UIManager.setLookAndFeel(lookAndFeel);
} catch (Exception e) {
System.err.println(e);
}
SwingUtilities.updateComponentTreeUI(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == nimbus)
setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel");
else if (e.getSource() == system)
setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
else if (e.getSource() == metal) {
MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
setLookAndFeel(new MetalLookAndFeel());
}
else if (e.getSource() == ocean) {
MetalLookAndFeel.setCurrentTheme(new OceanTheme());
setLookAndFeel(new MetalLookAndFeel());
}
}
public static void main(String[] args) {
LookAndFeelDemo.setLookAndFeel();
LookAndFeelDemo demo = new LookAndFeelDemo();
demo.setVisible(true);
}
}
| ataylor89/Java | LookAndFeelDemo.java |
249,106 | import java.util.ArrayList;
import java.util.Arrays;
public class oceanView {
public static void main(String[] args) {
ArrayList<Integer> houses = new ArrayList<>(Arrays.asList(3, 7, 2, 8, 9));
System.out.println(solution(houses));
}
public static int solution(ArrayList<Integer> houses) {
int max = 0;
int count = 0;
for (int i = 0; i < houses.size(); i++) {
if (houses.get(i) > max) {
max = houses.get(i);
count++;
}
}
return count;
}
}
| wenghaishi/leetcode-grind | oceanView.java |
249,107 | /*
Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent,
the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right
and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
Note:
The order of returned grid coordinates does not matter.
Both m and n are less than 150.
Example:
Given the following 5x5 matrix:
Pacific ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
~ 2 4 (5) 3 1 *
~ (6) (7) 1 4 5 *
~ (5) 1 1 2 4 *
* * * * * Atlantic
Return:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
Author: Erich Meissner
Date: 3/25/21
Time: 7:42 PM
*/
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
public class OceanWaterFlow {
public static void main(String[] args) {
}
private static final int[][] DIRECTIONS = new int[][]{{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
private int numRows;
private int numCols;
private int[][] landHeights;
public List<List<Integer>> pacificAtlantic(int[][] matrix) {
// Check if input is empty
if (matrix.length == 0 || matrix[0].length == 0) {
return new ArrayList<>();
}
// Save initial values to parameters
numRows = matrix.length;
numCols = matrix[0].length;
landHeights = matrix;
// Setup each queue with cells adjacent to their respective ocean
Queue<int[]> pacificQueue = new LinkedList<>();
Queue<int[]> atlanticQueue = new LinkedList<>();
for (int i = 0; i < numRows; i++) {
pacificQueue.offer(new int[]{i, 0});
atlanticQueue.offer(new int[]{i, numCols - 1});
}
for (int i = 0; i < numCols; i++) {
pacificQueue.offer(new int[]{0, i});
atlanticQueue.offer(new int[]{numRows - 1, i});
}
// Perform a BFS for each ocean to find all cells accessible by each ocean
boolean[][] pacificReachable = bfs(pacificQueue);
boolean[][] atlanticReachable = bfs(atlanticQueue);
// Find all cells that can reach both oceans
List<List<Integer>> commonCells = new ArrayList<>();
for (int i = 0; i < numRows; i++) {
for (int j = 0; j < numCols; j++) {
if (pacificReachable[i][j] && atlanticReachable[i][j]) {
commonCells.add(List.of(i, j));
}
}
}
return commonCells;
}
private boolean[][] bfs(Queue<int[]> queue) {
boolean[][] reachable = new boolean[numRows][numCols];
while (!queue.isEmpty()) {
int[] cell = queue.poll();
// This cell is reachable, so mark it
reachable[cell[0]][cell[1]] = true;
for (int[] dir : DIRECTIONS) { // Check all 4 directions
int newRow = cell[0] + dir[0];
int newCol = cell[1] + dir[1];
// Check if new cell is within bounds
if (newRow < 0 || newRow >= numRows || newCol < 0 || newCol >= numCols) {
continue;
}
// Check that the new cell hasn't already been visited
if (reachable[newRow][newCol]) {
continue;
}
// Check that the new cell has a higher or equal height,
// So that water can flow from the new cell to the old cell
if (landHeights[newRow][newCol] < landHeights[cell[0]][cell[1]]) {
continue;
}
// If we've gotten this far, that means the new cell is reachable
queue.offer(new int[]{newRow, newCol});
}
}
return reachable;
}
| meissnere/Algorithms | OceanWaterFlow.java |
249,110 | package glaces;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Random;
import java.util.Iterator;
public class Jeu {
private boolean play;
private ArcticImage image;
private Ocean ocean;
private Pingouin pingouin;
private ArrayList<Poisson> poissons;
private int fatigueMax;
private int stadeFatigue;
private int xPingouin;
private int yPingouin;
private int taillePingouin;
private int vitessePingouin;
private int nbPoisson;
private int largeurPoisson;
private int hauteurPoisson;
private int vitessePoisson;
/**
* Constructeur
*/
public Jeu() {
fatigueMax = 30;
stadeFatigue = 15;
xPingouin = 50;
yPingouin = 50;
taillePingouin = 14;
vitessePingouin = 28;
nbPoisson = 50;
largeurPoisson = 5;
hauteurPoisson = 10;
vitessePoisson = 21;
play = true;
ocean = new Ocean();
pingouin = new Pingouin(xPingouin, yPingouin, taillePingouin, vitessePingouin); // on met le pingouin au milieu
image = new ArcticImage(ocean.getWidth(), ocean.getHeight()); // on cree l'image
poissons = InitPoissons(); // on cree les poissons
image.setColors(creeCarte(ocean.getWidth(), ocean.getHeight(), ocean, pingouin, poissons)); // on met les couleurs
}
/**
* Initialise les poissons
* @return liste des poissons
*/
public ArrayList<Poisson> InitPoissons(){
poissons = new ArrayList<Poisson>();
Random random = new Random();
for (int i = 0; i < nbPoisson; i++) {
random = new Random();
poissons.add(new Poisson(largeurPoisson, hauteurPoisson, random.nextInt(2), // direction = 0 ou 1
random.nextInt(2) + 4, // couleur = entre 4 et 5
random.nextInt(3) + 1, // nombre aller retoure avant de mourir = entre 1 et 3
random.nextInt(ocean.getWidth() - 5),
random.nextInt(ocean.getHeight() - 10),
vitessePoisson));
}
updatePoisson(); // on met les poissons a leur place
return poissons;
}
/**
* Deplace le pingouin en fonction de l'input de l'utilisateur
* @param scanner scanner pour recuperer l'input
*/
public void updatePingouin(Scanner scanner) {
for (Iceberg2D iceberg : ocean.getIcebergs()) {
if (pingouin.estSurIceberg(iceberg)){
pingouin.estRepose();
// on verifie si l'iceberg est assez grand pour supporter le pingouin
if (iceberg.largeur() < pingouin.getTaille() * 2 || iceberg.hauteur() < pingouin.getTaille() * 2)
{
iceberg.fondre(1);
System.out.println("L'iceberg a casser sous le pingouin");
}
}
}
System.out.println("deplacer le pingouin (z,q,s,d) et appuyer sur entree (0 pour quitter)");
String input = scanner.nextLine();
switch (input.toLowerCase()) {
case "z":
deplacerPingouin(0, 1);
break;
case "q":
deplacerPingouin(-1, 0);
break;
case "s":
deplacerPingouin(0, -1);
break;
case "d":
deplacerPingouin(1, 0);
break;
case "0":
play = false;
break;
default:
// on fait rien
break;
}
if (pingouin.getFatigue() == stadeFatigue) pingouin.estFatigue();
}
/**
* Deplace les poissons et les supprime si ils sont morts
*/
public void updatePoisson() {
for (int i = 0; i < poissons.size(); i++) {
Poisson poisson = poissons.get(i);
poisson.deplacer();
if (poisson.getDirection() == 1){
if (poisson.getX() + (poisson.getHauteur() + poisson.getVitesse()) >= ocean.getWidth())
{
poisson.setX(0);
poisson.perdVie();
}
if (poisson.getX() < 0)
{
poisson.setX(ocean.getWidth() - poisson.getLargeur());
poisson.perdVie();
}
} else {
if (poisson.getY() + (poisson.getHauteur() + poisson.getVitesse()) >= ocean.getHeight())
{
poisson.setY(0);
poisson.perdVie();
}
if (poisson.getY() < 0)
{
poisson.setY(ocean.getHeight() - poisson.getHauteur());
poisson.perdVie();
}
}
if (poisson.estMange(pingouin)) {
for (Iceberg2D iceberg : ocean.getIcebergs()){
if (!poisson.estEnDessousIceBerg(iceberg)){
poisson.meurt();
pingouin.estRepose();
}
}
}
if (poisson.estMort()) {
poissons.remove(i);
i--;
}
}
}
/**
* Fait fondre un iceberg aleatoirement
*/
public void updateIceBerg(){
Random random = new Random();
if (random.nextInt(20) == 0)
ocean.fondreOcean(0.2);
}
/**
* fonction qui regarde si le jeu est fini et arrete
* le jeu si c'est le cas
*/
public void estFini(){
if (poissons.size() <= 0 || pingouin.getFatigue() > fatigueMax)
{
play = false;
}
}
/**
* fonction qui permet de voir si le joueur a gagner
* @return 1 : il a gagner 0 : il a perdu -1 : le jeu a été couper au mileu
*/
public int estGagne(){
if (poissons.size() <= 0)
{
return 1;
}
else if (pingouin.getFatigue() > fatigueMax) // si il reste des poissons alors le pingouin n'as pas gagne
{
return 0;
}else
{
return -1;
}
}
/**
* Boucle principale du jeu
*/
public void jouer() {
Scanner scanner = new Scanner(System.in);
while (play)
{
updatePingouin(scanner);
updateIceBerg();
updatePoisson();
if (poissons.size() > 0)
{
image.setColors(creeCarte(ocean.getWidth(), ocean.getHeight(), ocean, pingouin, poissons));
}
estFini();
}
if (estGagne() == 1){
System.out.println("Vous avez gagne !");
}else if (estGagne() == 0){
System.out.println("Vous avez perdu");
}
image.fermer();
}
/**
* Deplace le pingouin de dx et dy (en gerant les limites de l'ocean)
* @param dx
* @param dy
*/
private void deplacerPingouin(int dx, int dy) {
int newX = pingouin.getX() + dx * pingouin.getVitesse();
int newY = pingouin.getY() + dy * pingouin.getVitesse();
if (newX >= 0
&& newX < ocean.getWidth() - pingouin.getTaille()
&& newY >= 0
&& newY < ocean.getHeight() - pingouin.getTaille()) {
pingouin.deplacer(dx, dy);
}
}
/**
* Cree la carte avec les couleurs des poissons, du pingouin et des icebergs
* @param mapWidth
* @param mapHeight
* @param ocean
* @param pingouin
* @param poissons
* @return
*/
private int[][] creeCarte(int mapWidth, int mapHeight, Ocean ocean, Pingouin pingouin, ArrayList<Poisson> poissons) {
int[][] carte = new int[mapWidth][mapHeight];
ajouterPoissons(carte, poissons);
ajouterIceberg(carte, ocean);
ajouterPingouin(carte, pingouin);
return carte;
}
/**
* Ajoute les icebergs a la carte
* @param carte tableau de couleurs
* @param ocean ocean
*/
private void ajouterIceberg(int[][] carte, Ocean ocean) {
for (Iceberg2D iceberg : ocean.getIcebergs()) {
int x1 = (int) iceberg.coinEnBasAGauche().getAbscisse();
int y1 = (int) iceberg.coinEnBasAGauche().getOrdonnee();
int x2 = (int) iceberg.coinEnHautADroite().getAbscisse();
int y2 = (int) iceberg.coinEnHautADroite().getOrdonnee();
for (int i = x1; i < x2; i++) {
for (int j = y1; j < y2; j++) {
carte[i][j] = 1; // on met la couleur de l'iceberg
}
}
}
}
/**
* Ajoute le pingouin a la carte
* @param carte tableau de couleurs
* @param pingouin
*/
private void ajouterPingouin(int[][] carte, Pingouin pingouin) {
for (int i = pingouin.getX(); i < pingouin.getX() + pingouin.getTaille(); i++) {
for (int j = pingouin.getY(); j < pingouin.getY() + pingouin.getTaille(); j++) {
carte[i][j] = pingouin.getCouleur();
}
}
}
/**
* Ajoute les poissons a la carte
* @param carte tableau de couleurs
* @param poissons
*/
private void ajouterPoissons(int[][] carte, ArrayList<Poisson> poissons) {
for (Poisson poisson : poissons) {
if (poisson.getDirection() == 0) // horizontal
for (int i = poisson.getX(); i < poisson.getX() + poisson.getLargeur(); i++) {
for (int j = poisson.getY(); j < poisson.getY() + poisson.getHauteur(); j++) {
carte[i][j] = poisson.getCouleurs();
}
}
else // vertical
for (int i = poisson.getX(); i < poisson.getX() + poisson.getHauteur(); i++) {
for (int j = poisson.getY(); j < poisson.getY() + poisson.getLargeur(); j++) {
carte[i][j] = poisson.getCouleurs();
}
}
}
}
public static void main(String[] args) {
Jeu jeu = new Jeu();
jeu.jouer();
}
} | MMMatth/artic-game-java | glaces/Jeu.java |
249,111 | public class OceanCell extends Cell {
protected MissedHit firstHit() {
return new MissedHit();
}
} | btrd/BatailleNavale | OceanCell.java |
249,113 | import java.awt.Point;
import java.util.Random;
// This class is responsible for generate a grid representing the island map
// and randomly placing islands onto the grid.
public class OceanMap {
private static OceanMap uniqueInstance;
boolean[][] islands;
int dimensions;
int islandCount;
Random rand = new Random();
Point shipLocation;
int treasuresLeft;
Point[] treasureLocations;
//checked each time
private boolean gameWin = false;
boolean gameLose = false;
// Constructor
// Not adding validation code so make sure islandCount is much less than dimension^2
private OceanMap(){
//default setting when constructed first time.
buildMap(new EasyDifficulty());
}
public static OceanMap getInstance(){
if(uniqueInstance == null){
uniqueInstance = new OceanMap();
}
return uniqueInstance;
}
//responsible for building the map when a difficulty setting is selected and the game starts.
public void buildMap(DifficultySetting difficulty){
this.dimensions = difficulty.getMapSize();
this.islandCount = difficulty.getNumIslands();
createGrid();
placeIslands();
shipLocation = placeShip();
//nullify treasure locations for multiple games.
treasureLocations = null;
treasuresLeft = 0;
gameWin = false;
gameLose = false;
}
// Create an empty map
private void createGrid(){
islands = new boolean[dimensions][dimensions];
for(int x = 0; x < dimensions; x++)
for(int y = 0; y < dimensions; y++)
islands[x][y] = false;
}
// Place islands onto map
private void placeIslands(){
int islandsToPlace = islandCount;
while(islandsToPlace >0){
int x = rand.nextInt(dimensions);
int y = rand.nextInt(dimensions);
if(islands[x][y] == false){
islands[x][y] = true;
islandsToPlace--;
}
}
}
private Point placeShip(){
boolean placedShip = false;
int x=0,y=0;
while(!placedShip){
x = rand.nextInt(dimensions);
y = rand.nextInt(dimensions);
if(islands[x][y] == false){
placedShip = true;
}
}
return new Point(x,y);
}
//Bug: treasure being placed on
public Point placeTreasure(){
boolean placedTreasure = false;
int x=0,y=0;
//Point ship = getShipLocation();
while(!placedTreasure){
x = rand.nextInt(dimensions);
y = rand.nextInt(dimensions);
//if location is ocean and not a treasure.
if(isOcean(x,y) && !isTreasure(x,y)){
placedTreasure = true;
}
}
//put the treasure in the locations list and increase number of treasures left.
Point location = new Point(x,y);
treasuresLeft++;
if(treasureLocations == null){
treasureLocations = new Point[1];
treasureLocations[0] = location;
}else{
Point[] tmp = new Point[treasureLocations.length+1];
for(int i = 0; i < treasureLocations.length; i++){
tmp[i] = treasureLocations[i];
}
tmp[treasureLocations.length] = location;
treasureLocations = tmp;
}
return location;
}
public Point placeMonster(){
boolean placedMonster = false;
int x=0,y=0;
Point ship = getShipLocation();
while(!placedMonster){
x = rand.nextInt(dimensions);
y = rand.nextInt(dimensions);
if(islands[x][y] == false && !(x!= ship.getX() && y!= ship.getY())){ //prevents pirate being placed on ship
//prevents monster being placed on top of treasure.
for(int i = 0; i < treasureLocations.length; i++){
if(treasureLocations[i].getX() == x && treasureLocations[i].getY() == y){
placedMonster = false;
break;
} else placedMonster = true;
}
}
}
return new Point(x,y);
}
public Point getShipLocation(){
return shipLocation;
}
// Return generated map
public boolean[][] getMap(){
return islands;
}
public int getDimensions(){
return dimensions;
}
public boolean isOcean(int x, int y){
if (!islands[x][y])
return true;
else
return false;
}
public boolean isTreasure(int x, int y){
if(treasureLocations == null) return false;
for(int i = 0; i < treasureLocations.length; i++){
if(treasureLocations[i].getX() == x && treasureLocations[i].getY() == y){
return true;
}
}
return false;
}
//is the current location containing a treasure.
public boolean checkForTreasure(int x, int y){
for(int i = 0; i < treasureLocations.length; i++){
if(treasureLocations[i].getX() == x && treasureLocations[i].getY() == y){
this.treasuresLeft--;
removeTreasure(x,y);
checkGameWin(allTreasuresGotten());
return true;
}
}
return false;
}
//decreases treasure locations on the map.
private void removeTreasure(int x, int y){
Point[] tmp = new Point[treasureLocations.length - 1];
int tmpIndex = 0;
for(int i = 0; i < treasureLocations.length; i++){
if(treasureLocations[i].getX() != x || treasureLocations[i].getY() != y){
tmp[tmpIndex] = treasureLocations[i];
tmpIndex++;
}
}
treasureLocations = tmp;
return;
}
private boolean allTreasuresGotten(){
if(this.treasuresLeft > 0) return false;
else return true;
}
private void checkGameWin(boolean state){
if(!state) return;
else this.gameWin = true;
return;
}
//monsters got to the ship
public void gameLose(){
this.gameLose = true;
}
public boolean getGameWin(){
return this.gameWin;
}
public boolean getGameLose(){
return this.gameLose;
}
} | AndrewMcShane/TreasureQuestSchoolProject | src/OceanMap.java |
249,116 | import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
public class OceanTest {
private Ocean testOcean;
@BeforeEach
public void setUp() {
testOcean = new Ocean();
}
@Test
public void testPlaceAllShipsRandomly() {
testOcean = new Ocean();
testOcean.placeAllShipsRandomly();
int shipsCount = 0;
for (int i = 0; i < Ocean.OCEAN_SIZE; i++) {
for (int j = 0; j < Ocean.OCEAN_SIZE; j++) {
if (!(testOcean.getShipArray()[i][j] instanceof EmptySea)) {
shipsCount++;
}
}
}
assertEquals(20, shipsCount); // 20 ship blocks in total (= 4*1 + 3*2 + 2*3 + 1*4)
}
@Test
public void testIsOccupied0() {
// when no ships are places, all blocks are empty sea
for (int row = 0; row < 10; ++row) {
for (int col = 0; col < 10; ++ col) {
assertFalse(testOcean.isOccupied(row, col));
}
}
}
@Test
public void testIsOccupied1() {
// create a submarine and place it at (0, 0)
Ship ship = new Submarine();
ship.placeShipAt(5, 5, ship.isHorizontal(), this.testOcean);
assertTrue(testOcean.isOccupied(5, 5));
}
@Test
public void testIsOccupied2() {
Ship ship = new Cruiser();
ship.setHorizontal(true);
ship.placeShipAt(0, 0, ship.isHorizontal(), this.testOcean);
assertTrue(testOcean.isOccupied(0, 2));
}
@Test
public void testIsGameOver() {
assertFalse(testOcean.isGameOver());
}
@Test
public void testShootAt0() {
Ship ship = new Submarine();
ship.placeShipAt(0, 0, ship.isHorizontal(), this.testOcean);
testOcean.shootAt(0 ,0);
assertTrue(ship.isSunk());
}
@Test
public void testShootAt1() {
Ship ship = new Cruiser();
ship.setHorizontal(true);
ship.placeShipAt(0, 0, ship.isHorizontal(), this.testOcean);
testOcean.shootAt(0 ,0);
testOcean.shootAt(0 ,2);
boolean[] expected_hit = new boolean[]{true, false, true};
assertArrayEquals(expected_hit, ship.getHit());
}
@Test
public void testGetFinalScore0() {
testOcean.placeAllShipsRandomly();
while (!testOcean.isGameOver()) {
for (int row = 0; row < 10; ++row) {
for (int col = 0; col < 10; ++col) {
testOcean.shootAt(row, col);
}
}
}
int finalScore = testOcean.getFinalScore();
assertTrue(20 <= finalScore && finalScore <= 100);
}
@Test
public void testGetFinalScore1() {
testOcean.placeAllShipsRandomly();
while (!testOcean.isGameOver()) {
for (int row = 0; row < 10; ++row) {
for (int col = 0; col < 10; ++col) {
testOcean.shootAt(row, col);
}
}
}
int finalScore = testOcean.getFinalScore();
assertTrue(20 <= finalScore && finalScore <= 100);
}
@Test
public void testGetFinalScore2() {
testOcean.placeAllShipsRandomly();
while (!testOcean.isGameOver()) {
for (int row = 0; row < 10; ++row) {
for (int col = 0; col < 10; ++col) {
testOcean.shootAt(row, col);
}
}
}
int finalScore = testOcean.getFinalScore();
assertTrue(20 <= finalScore && finalScore <= 100);
}
@Test
public void testGetShipArray0() {
Ship ship = new Battleship();
ship.setHorizontal(true);
ship.placeShipAt(0, 0, ship.isHorizontal(), this.testOcean);
Ship[][] shipArray = testOcean.getShipArray();
assertTrue(shipArray[0][0] instanceof Battleship);
assertTrue(shipArray[0][1] instanceof Battleship);
assertTrue(shipArray[0][2] instanceof Battleship);
assertTrue(shipArray[0][3] instanceof Battleship);
assertTrue(shipArray[0][4] instanceof EmptySea);
assertTrue(shipArray[1][1] instanceof EmptySea);
}
@Test
public void testGetShipArray1() {
Ship ship = new Battleship();
ship.setHorizontal(false);
ship.placeShipAt(0, 0, ship.isHorizontal(), this.testOcean);
Ship[][] shipArray = testOcean.getShipArray();
assertTrue(shipArray[0][0] instanceof Battleship);
assertTrue(shipArray[1][0] instanceof Battleship);
assertTrue(shipArray[2][0] instanceof Battleship);
assertTrue(shipArray[3][0] instanceof Battleship);
assertTrue(shipArray[4][0] instanceof EmptySea);
assertTrue(shipArray[1][1] instanceof EmptySea);
}
@Test
public void testGetShotsFired0() {
int expected_shots = 100;
for (int i = 0; i < expected_shots; ++i) {
testOcean.shootAt(0, 0);
}
assertEquals(expected_shots, testOcean.getShotsFired());
}
@Test
public void testGetShotsFired1() {
int expected_shots = 18;
for (int i = 0; i < expected_shots; ++i) {
testOcean.shootAt(0, 0);
}
assertEquals(expected_shots, testOcean.getShotsFired());
}
@Test
public void testGetHitCount0() {
Ship ship = new Battleship();
ship.placeShipAt(0, 0, ship.isHorizontal(), testOcean);
int expected_hit = 100;
for (int i = 0; i < expected_hit; ++i) {
testOcean.shootAt(0, 0);
}
assertEquals(expected_hit, testOcean.getHitCount());
}
@Test
public void testGetHitCount1() {
Ship ship = new Submarine();
ship.placeShipAt(0, 0, ship.isHorizontal(), testOcean);
int shotsFired = 100;
int expected_hit = 1;
for (int i = 0; i < shotsFired; ++i) {
testOcean.shootAt(0, 0);
}
assertEquals(expected_hit, testOcean.getHitCount());
}
@Test
public void testGetShipSunk0() {
Ship ship0 = new Submarine();
ship0.placeShipAt(0, 0, ship0.isHorizontal(), testOcean);
Ship ship1 = new Submarine();
ship1.placeShipAt(1, 1, ship1.isHorizontal(), testOcean);
Ship ship2 = new Submarine();
ship2.placeShipAt(2, 2, ship2.isHorizontal(), testOcean);
testOcean.shootAt(0, 0);
testOcean.shootAt(1, 1);
testOcean.shootAt(2, 2);
int expected_sunk = 3;
assertEquals(expected_sunk, testOcean.getShipsSunk());
}
@Test
public void testGetShipSunk1() {
Ship ship = new Cruiser();
ship.setHorizontal(true);
ship.placeShipAt(0, 0, ship.isHorizontal(), testOcean);
testOcean.shootAt(0, 0);
testOcean.shootAt(0, 1);
testOcean.shootAt(0, 2);
int expected_sunk = 1;
assertEquals(expected_sunk, testOcean.getShipsSunk());
}
}
| tanhaow/Battleship | src/OceanTest.java |
249,117 | 404: Not Found | Zenny00/COSC330_Battleship | Model/Player.java |
249,118 | import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
public class Player {
private String name;
private Ocean ocean;
private View view;
private HashMap<String, Integer> possibleShips;
{
possibleShips = new HashMap<>();
possibleShips.put("Carrier", 5);
possibleShips.put("Battleship", 4);
possibleShips.put("Cruiser", 3);
possibleShips.put("Submarine", 3);
possibleShips.put("Destroyer", 2);
}
public Player(String numOfUser){
askForName(numOfUser);
ocean = new Ocean();
view = new View();
askForShips(); // <--- odkomentować do właściwej gry!!!
}
public boolean hasLost(){
return ocean.hasLost();
}
public boolean shoot(int[] coordinates){
return ocean.isShot(coordinates[0],coordinates[1]);
}
public boolean isSunk(int[] coordinates){
return ocean.isSunk(coordinates[0], coordinates[1]);
}
private void askForName(String numOfUser) {
view = new View();
view.clearScreen();
this.name = view.inputFromUser(String.format("Please insert name of the %s user", numOfUser));
while (numOfUser.length() < 1) {
view.printText("Your name should consist of at least 1 character");
this.name = view.inputFromUser(String.format("Please insert name of the %s user", numOfUser));
}
}
private void askForShips() {
while (possibleShips.size() > 0) {
view.clearScreen();
view.printTitle(String.format("%s - time to place your ships!", name));
view.printOcean(ocean, false);
view.printPossibleShips(possibleShips);
String shipName = getShipName();
int shipLength = possibleShips.get(shipName);
boolean isHorizontal = getIsShipHorizontal();
int[] coordinates = getShipCoordinates();
boolean isAdded = ocean.addShip(coordinates[0], coordinates[1], isHorizontal, shipLength);
if (isAdded) {
possibleShips.remove(shipName);
}
}
}
private String getShipName() {
String shipName = view.inputFromUser("Please type in the name of the ship you choose");
shipName = shipName.substring(0, 1).toUpperCase() + shipName.substring(1).toLowerCase();
while (!possibleShips.containsKey(shipName)){
view.printText("This name is not on the list of permitted ships");
shipName = view.inputFromUser("Please type in the name of the ship you choose");
shipName = shipName.substring(0, 1).toUpperCase() + shipName.substring(1).toLowerCase();
}
return shipName;
}
private boolean getIsShipHorizontal() {
String order = "Please type H if you want your ship to be HORIZONTAL or V if VERTICAL";
String position = view.inputFromUser(order).toUpperCase();
while (!position.equals("H") && !position.equals("V")) {
view.printText("Wrong input.");
position = view.inputFromUser(order).toUpperCase();
}
boolean isHorizontal = (position.equals("H")) ? true : false;
return isHorizontal;
}
private int[] getShipCoordinates() {
String order = "What is the starting point of your ship? Type it in '1A' format";
String coordinates = view.inputFromUser(order).toUpperCase();
String[] possibleNumbers = new String[] {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"};
List<String> possibleNumbersList = Arrays.asList(possibleNumbers);
String[] possibleLetters = new String[] {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
List<String> possibleLettersList = Arrays.asList(possibleLetters);
String firstSign = (coordinates.length() > 2) ? coordinates.substring(0,2) : coordinates.substring(0,1);
String secondSign = (coordinates.length() > 2) ? coordinates.substring(2) : coordinates.substring(1);
while (!possibleLettersList.contains(secondSign) || !possibleNumbersList.contains(firstSign)
|| (coordinates.length() > 2 && !coordinates.substring(0,2).equals("10")))
{
coordinates = view.inputFromUser(order).toUpperCase();
firstSign = (coordinates.length() > 2) ? coordinates.substring(0,2) : coordinates.substring(0,1);
secondSign = (coordinates.length() > 2) ? coordinates.substring(2) : coordinates.substring(1);
}
int[] finalCoordinates = translateFromStringToCoordinates(coordinates);
return finalCoordinates;
}
private int[] translateFromStringToCoordinates(String coordinatesAsString){
String[] alfabet = new String[] {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J"};
int lenghtArrayOfAlfabet = alfabet.length;
int X_INDEX = 1;
int Y_INDEX = 0;
int[] coordinatesAsInt = new int[] {1, 2};
String xAsString = (coordinatesAsString.length() > 2) ? coordinatesAsString.substring(0,2) : coordinatesAsString.substring(0,1);
String yAsString = (coordinatesAsString.length() > 2) ? coordinatesAsString.substring(2) : coordinatesAsString.substring(1);
coordinatesAsInt[X_INDEX] = Integer.parseInt(xAsString) - 1;
for(int index = 0; index < lenghtArrayOfAlfabet; index++){
if(yAsString.equals(alfabet[index])){
coordinatesAsInt[Y_INDEX] = index;
}
}
return coordinatesAsInt;
}
public Ocean getOcean() {
return ocean;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
| CodecoolGlobal/battle-ship-in-the-oo-way-karolinamichal | Player.java |
249,119 | /* Given: An array of strings where L indicates land and W indicates water,
and a coordinate marking a starting point in the middle of the ocean.
Challenge: Find and mark the ocean in the map by changing appropriate Ws to Os.
An ocean coordinate is defined to be the initial coordinate if a W, and
any coordinate directly adjacent to any other ocean coordinate.
*/
// airbnb, see 200. Number of Islands
class Solution {
public void findOcean(String[] map, int row, int col) {
char[][] grid = new char[map.length][];
for (int i = 0; i < map.length; i++) {
grid[i] = map[i].toCharArray();
}
dfsMarking(grid, row, col);
for (int i = 0; i < map.length; i++) {
map[i] = new String(grid[i]);
}
}
private void dfsMarking(char[][] grid, int i, int j) {
if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length) {
return;
}
if (grid[i][j] == 'W') {
grid[i][j] = 'O';
dfsMarking(grid, i - 1, j);
dfsMarking(grid, i + 1, j);
dfsMarking(grid, i, j - 1);
dfsMarking(grid, i, j + 1);
}
}
public static void main(String[] args) {
Solution s = new Solution();
String[] map = { "WWWLLLW", "WWLLLWW", "WLLLLWW" };
s.findOcean(map, 0, 1);
for (String row : map)
System.out.println(row);
}
} | trytry3/LeetCode | Finding Ocean.java |
249,120 | import java.io.*;
public class Main {
static int R, C, M;
static int[][] ocean, shark;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
String[] in = br.readLine().split(" ");
R = Integer.parseInt(in[0]);
C = Integer.parseInt(in[1]);
M = Integer.parseInt(in[2]);
shark = new int[M + 1][5]; // row, column, speed, direction, size
for(int sharkId=1; sharkId<=M; sharkId++) {
in = br.readLine().split(" ");
for(int i=0; i<5; i++)
shark[sharkId][i] = Integer.parseInt(in[i]);
}
int point = 0;
ocean = new int[R + 1][C + 1];
int fisherman = 1;
for(int sharkId=1; sharkId<=M; sharkId++) {
int r = shark[sharkId][Shark.ROW.index()], c = shark[sharkId][Shark.COL.index()];
ocean[r][c] = sharkId;
}
while(fisherman <= C && M > 0) {
point += catchShark(fisherman);
moveShark();
fisherman++;
}
bw.write(point + "\n");
bw.flush();
bw.close();
}
public static int catchShark(int fisherman) {
for(int row=1; row<=R; row++) {
if(ocean[row][fisherman] != 0) {
int sharkId = ocean[row][fisherman];
int size = shark[sharkId][Shark.SIZE.index()];
ocean[row][fisherman] = 0;
shark[sharkId][Shark.SIZE.index()] = -1; // catch shark
return size;
}
}
return 0;
}
public static void moveShark() {
int[] dx = {0, -1, 1, 0, 0}; // none, up, down, right, left
int[] dy = {0, 0, 0, 1, -1};
for(int sharkId=1; sharkId<=M; sharkId++) {
int size = shark[sharkId][Shark.SIZE.index()];
if(size < 0)
continue;
int row = shark[sharkId][Shark.ROW.index()];
int col = shark[sharkId][Shark.COL.index()];
int speed = shark[sharkId][Shark.SPEED.index()];
int dir = shark[sharkId][Shark.DIR.index()];
if(ocean[row][col] == sharkId)
ocean[row][col] = 0;
int time = speed;
switch (dir) { // optimize time
case 1: case 2:
time = speed % (2 * (R - 1)); break;
case 3: case 4:
time = speed % (2 * (C - 1)); break;
}
int x = row, y = col;
while(time > 0) {
int nx = x + dx[dir], ny = y + dy[dir];
if(1 <= nx && nx <= R && 1 <= ny && ny <= C) {
x = nx;
y = ny;
time--;
} else {
switch (dir) {
case 1: dir = 2; break;
case 2: dir = 1; break;
case 3: dir = 4; break;
case 4: dir = 3; break;
}
}
}
if(ocean[x][y] == 0) { // empty cell, move
ocean[x][y] = sharkId;
shark[sharkId][Shark.ROW.index()] = x;
shark[sharkId][Shark.COL.index()] = y;
shark[sharkId][Shark.DIR.index()] = dir;
}
else { // non-empty cell
if(sharkId < ocean[x][y]) { // if shark@ocean[x][y] hasn't moved yet, move
ocean[x][y] = sharkId;
shark[sharkId][Shark.ROW.index()] = x;
shark[sharkId][Shark.COL.index()] = y;
shark[sharkId][Shark.DIR.index()] = dir;
} else if(shark[ocean[x][y]][Shark.SIZE.index()] > size) { // if shark@ocean[x][y] has moved and bigger, make size -1
shark[sharkId][Shark.SIZE.index()] = -1;
} else if(shark[ocean[x][y]][Shark.SIZE.index()] < size) { // if shark@ocean[x][y] has moved and smaller, move and eat
shark[ocean[x][y]][Shark.SIZE.index()] = -1;
ocean[x][y] = sharkId;
shark[sharkId][Shark.ROW.index()] = x;
shark[sharkId][Shark.COL.index()] = y;
shark[sharkId][Shark.DIR.index()] = dir;
}
}
}
}
}
enum Shark {
ROW {int index() { return 0; }},
COL {int index() { return 1; }},
SPEED {int index() { return 2; }},
DIR {int index() { return 3; }},
SIZE {int index() { return 4; }};
abstract int index();
} | jehunyoo/Baekjoon-Online-Judge | 17143.java |
249,122 | import javax.swing.JPanel;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Image;
import javax.imageio.ImageIO;
import java.awt.Toolkit;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Random;
import java.io.BufferedReader;
import java.io.FileReader;
public class Boss extends Sprite implements Runnable{
private final static int LEFT_BOUNDARY = 680;
private final static int RIGHT_BOUNDARY = 720;
private final static String BOSS_ICON = "../images/boss.png";
private static int drc = 0; //0 for left; 1 for right
public static boolean flag = true;
public final static int MAX_HP = 500;
private int hp;
private ArrayList<Missile> missiles;
public HashMap<String, Integer> listOfWords;
public ArrayList<String> listOfKeys;
private Diver diver;
private Ocean ocean;
public Boss(int xPos, int yPos, Diver diver, Ocean ocean){
super(xPos,yPos, Boss.BOSS_ICON);
this.ocean = ocean;
this.missiles = new ArrayList<Missile>();
this.hp = Boss.MAX_HP;
this.diver = diver;
this.loadWordsFile("words_g8_letter.txt"); // loads text file
}
public Diver getDiver(){
return this.diver;
}
private void loadWordsFile(String filename){
this.listOfWords = new HashMap<String, Integer>();
try{
String[] tokens;
String line;
BufferedReader reader = new BufferedReader(new FileReader(filename));
while((line = reader.readLine()) != null){
tokens = line.split(" ");
listOfWords.put(tokens[0], Integer.parseInt(tokens[1]));
}
this.listOfKeys = new ArrayList<String>(this.listOfWords.keySet());
} catch(Exception e){ e.getMessage(); }
}
public void addMissiles(){
Random r = new Random();
int rand = r.nextInt(2) + 3;
for(int i = 0; i < rand; i++){
int index = r.nextInt(this.listOfKeys.size());
String word = this.listOfKeys.get(index); // gets a random word
int score = this.listOfWords.get(word); // gets the score associated
this.missiles.add(new Missile(word.toUpperCase(), score, Boss.LEFT_BOUNDARY - Missile.WIDTH, 65 * i + 120, this)); // sets the x position to the left boundary of the boss
}
}
public ArrayList<Missile> getMissiles(){
return this.missiles;
}
public synchronized int getHp(){
return this.hp;
}
public void setHp(int damage){
this.hp -= damage; // damages the boss
}
public void autoFlee(){ // movement of the boss (left or right)
if(this.drc == 0) this.decXPos(3);
else this.incXPos(3);
}
public void move(){
if(this.getXPos() <= Boss.LEFT_BOUNDARY){
this.incXPos(3);
this.drc = 1;
}
else if(this.getXPos() >= Boss.RIGHT_BOUNDARY){
this.decXPos(3);
this.drc = 0;
}
else this.autoFlee();
}
public void run(){
while(this.hp > 0 && this.diver.isAlive() == true){ // while hp of the boss is 0 and diver is still alive
this.move();
if(this.missiles.size() == 0 && this.ocean.getListOfEnemies().size() == 0 && this.getXPos() >= Boss.LEFT_BOUNDARY && this.getXPos() <= Boss.RIGHT_BOUNDARY)this.addMissiles();
this.repaint(); // if the missiles are already typed or passed leftmost part, add missile
try{
Thread.sleep(100);
} catch(Exception e){}
}
try{
Thread.sleep(1000);
} catch(Exception e){}
if(this.hp <= 0) Boss.flag = false;
this.repaint();
}
@Override
public void paintComponent(Graphics g){
if(this.hp > 0){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(this.getImage(), this.getXPos(), this.getYPos(), null);
Toolkit.getDefaultToolkit().sync(); // makes animation smooth
}
}
}
| lolzz77/Typer-Shark | src/Boss.java |
249,123 | /**
* Ocean.java
* @author: Ruzan Sasuri rps7183@g.rit.edu
* @author: Akash Venkatachalam av2833@g.rit.edu
* @author: Ghodratollah Aalipour ga5481@g.rit.edu
* Id: $ Ocean.java v1.0, 2016/11/07$
* Revision: First Revision
*/
public class Ocean
{
protected int maxRow;
protected int maxColumn;
protected char board[][];
/**
* The constructor assigns the value for MAX_ROW and MAX_COLUMN
* @param r number of rows
* @param c number of columns
*/
public Ocean(int r,int c)
{
maxRow = r + 2;
maxColumn = c + 2;
board = new char[maxRow][maxColumn];
for(int i = 0; i < board.length; i++)
{
board[i][0] = 'B';
board[i][board[i].length - 1] = 'B';
}
for(int i = 1; i < board[0].length - 1; i++)
{
board[0][i] = 'B';
board[board.length - 1][i] = 'B';
}
for(int i = 1; i < board.length - 1; i++)
{
for(int j = 1; j < board[i].length - 1; j++)
{
board[i][j] = '~';
}
}
}
/**
* Returns back our Ocean as an array
* @return
*/
public char[][] getBoard()
{
return board;
}
/**
* Getter method for maximum row
* @return MAX_ROW
*/
public int getRow()
{
return maxRow;
}
/**
* Getter method for maximum column
* @return MAX_ROW
*/
public int getColumn()
{
return maxColumn;
}
/**
* The next method just prints out our object as Ocean when called
* @return
*/
public String toString()
{
return "Ocean";
}
/*
public static void main(String args[])
{
Fleet f = new Fleet(10,10);
f.emptyBoard();
System.out.println(f.fillFunc(1,1,2,'V'));
System.out.println(f.fillFunc(5,6,3,'H'));
System.out.println(f.fillFunc(1,6,4,'H'));
System.out.println(f.fillFunc(10,1,5,'H'));
char outcome = f.hit(5,6,'Z');
f.print();
System.out.println();
Ocean c = new Ocean(10,10);
c.emptyBoard();
c.hit(5,6,outcome);
c.print();
}*/
}
| ruzansasuri/battleship | src/Ocean.java |
249,124 | package glaces;
import geometrie.Point;
import java.util.Random;
import glaces.Iceberg2D;
public class Ocean {
private int width;
private int height;
private Iceberg2D[] icebergs;
/**
* Constructeur avec parametres
* @param width largeur de l'ocean
* @param height hauteur de l'ocean
* @param icebergs liste des icebergs
*/
public Ocean(int width, int height, Iceberg2D[] icebergs) {
this.width = width;
this.height = height;
this.icebergs = icebergs;
}
/**
* Constructeur sans parametres
* Genere un ocean de 300x300 avec 2 icebergs
* Les icebergs sont de taille aleatoire
*/
public Ocean() {
this.width = 600;
this.height = 600;
this.icebergs = new Iceberg2D[10];
int largeurIceberg, hauteurIceberg, xIceberg, yIceberg;
for (int i = 0; i < this.icebergs.length ; i++)
{
largeurIceberg = new Random().nextInt(50) + 20; // entre 20 et 70
hauteurIceberg = new Random().nextInt(50) + 20;
xIceberg = new Random().nextInt(this.width - largeurIceberg);
yIceberg = new Random().nextInt(this.height - hauteurIceberg);
this.icebergs[i] = new Iceberg2D(new Point(xIceberg, yIceberg), new Point(xIceberg + largeurIceberg, yIceberg + hauteurIceberg));
}
}
/**
*
* @param coeffFondre : coefficient de fonte entre ]0,1]
*/
public void fondreOcean(double coeffFondre) {
for (Iceberg2D Iceberg : icebergs) {
Iceberg.fondre(coeffFondre);
}
}
/**
* recuperer la liste des icebergs
* @return liste des icebergs
*/
public Iceberg2D[] getIcebergs() {
return this.icebergs;
}
/**
* recuperer un iceberg
* @param i : indice de l'iceberg
* @return iceberg
*/
public Iceberg2D getIceberg(int i){
return this.icebergs[i];
}
/**
* recuper la largeur de l'ocean
* @return
*/
public int getWidth() {
return this.width;
}
/**
* recuper la hauteur de l'ocean
* @return
*/
public int getHeight() {
return this.height;
}
/**
* fonction toString
* @return string
*/
public String toString() {
String str = "Ocean [ width = " + this.width + ", height = " + this.height + " ]\n";
for (Iceberg2D Iceberg : icebergs) {
str += Iceberg.toString() + "\n";
}
return str;
}
} | MMMatth/artic-game-java | glaces/Ocean.java |
249,125 | import static org.junit.Assert.*;
import org.junit.Test;
public class OceanTest {
Ocean o = new Ocean();
@Test
public void testPrintOcean() {
o.printOcean();
assertTrue("Imprimio todo", true);
}
}
| sleyter94/SDx1 | src/OceanTest.java |
249,127 | import java.util.Scanner;
public class Player {
private String name;
private BattleshipGrid grid;
private Ocean ocean;
private Scanner scan = new Scanner(System.in);
public Player(){
name = null;
}
public void startGame(){
System.out.println("started game");
ocean = new Ocean();
grid = new BattleshipGrid(ocean);
initializeGrid();
if(name == null){
System.out.println("input name");
name = scan.nextLine();
}
}
public String playerName(){
return name;
}
public Position shoot(){
System.out.println("enter pos to shoot");
Position pos = PositionChecker.checkPosition(scan.nextLine());
while(pos.colIndex()==-1){
System.out.println("invalid, try again");
pos = PositionChecker.checkPosition(scan.nextLine());
}
ocean.shootAt(pos);
grid.shotAt(pos, ocean.hit(pos), ocean.boatInitial(pos));
return pos;
}
public void updateGrid(Position pos, boolean hit, char initial){
grid.shotAt(pos, hit, initial);
}
public BattleshipGrid getGrid(){
return grid;
}
public void initializeGrid(){
ocean = new Ocean();
grid = new BattleshipGrid(ocean);
ocean.placeAllBoats();
}
public void updatePlayer(Position pos, boolean hit, char initial, String boatName, boolean sunk, boolean gameOver, boolean tooManyTurns, int turns){
System.out.println(grid);
String isHit = (hit) ? ("hit") : ("miss");
System.out.println("Turn #" + turns +": Your shot at " + pos +" was a " + isHit + ".");
if(sunk){
System.out.println("You sunk the " + boatName + "!");
}
if(gameOver){
System.out.println("Game over, you took " + turns + " turns to win");
}
}
}
| imacrazyguy412/Battleship | src/Player.java |
249,128 | // Khomiakov Kevin
// Xianpeng Chen
// HW 9
import java.util.ArrayList;
import tester.*;
import javalib.impworld.*;
import java.awt.Color;
import javalib.worldimages.*;
import java.util.Iterator;
import java.util.Random;
//to represent a cell
class Cell {
double height;
int x;
int y;
Cell left, top, right, bottom;
// to check if it is flooded
boolean isFlooded;
static final int CELL_SIZE = ForbiddenIslandWorld.WORLD_SIZE / ForbiddenIslandWorld.ISLAND_SIZE;
Cell(double height, int x, int y) {
this.height = height;
this.x = x;
this.y = y;
}
void helpLeft(Cell left) {
this.left = left;
}
void helpRight(Cell right) {
this.right = right;
}
void helpTop(Cell top) {
this.top = top;
}
void helpBot(Cell bot) {
this.bottom = bot;
}
// to draw a cell
WorldImage drawCell() {
int c1 = Math.min(255, (int) (this.height * (255 / (ForbiddenIslandWorld.ISLAND_SIZE / 2))));
Color color = new Color(c1, 200, c1);
return new RectangleImage(CELL_SIZE, CELL_SIZE, OutlineMode.SOLID, color);
}
}
//to represent an ocean cell
class OceanCell extends Cell {
OceanCell(int x, int y) {
super(0, x, y);
this.isFlooded = true;
}
// to draw a cell
WorldImage drawCell() {
return new RectangleImage(CELL_SIZE, CELL_SIZE, OutlineMode.SOLID, new Color(0, 0, 255));
}
}
//to represent IList
interface IList<T> extends Iterable<T> {
// to transform it to a cons
Cons<T> asCons();
// to transform it to an empty
Empty<T> asEmpty();
// to check if it is empty or not
boolean isEmpty();
// to check if it is cons or not
boolean isCons();
}
// to represent an List of Iterator
class IListIterator<T> implements Iterator<T> {
int next;
IList<T> items;
IListIterator(IList<T> items) {
this.items = items;
}
// to output a next value
public T next() {
if (!this.hasNext()) {
throw new RuntimeException("There is no next");
}
else {
Cons<T> item1 = this.items.asCons();
T newitem = item1.first;
this.items = item1.rest;
return newitem;
}
}
// to check if it has a next item
public boolean hasNext() {
return this.items.isCons();
}
// to remove a value
public void remove() {
throw new UnsupportedOperationException("Something");
}
}
// to represent an empty list
class Empty<T> implements IList<T> {
public Empty<T> asEmpty() {
return this;
}
public Cons<T> asCons() {
throw new RuntimeException("it is a cons");
}
public boolean isEmpty() {
return true;
}
public boolean isCons() {
return false;
}
public Iterator<T> iterator() {
return new IListIterator<T>(this);
}
}
// to represent a cons List
class Cons<T> implements IList<T> {
T first;
IList<T> rest;
Cons(T first, IList<T> rest) {
this.first = first;
this.rest = rest;
}
public Empty<T> asEmpty() {
throw new RuntimeException("it is an empty");
}
public Cons<T> asCons() {
return this;
}
public boolean isEmpty() {
return false;
}
public boolean isCons() {
return true;
}
public Iterator<T> iterator() {
return new IListIterator<T>(this);
}
}
// to represent A ForbiddenIslandWorld
class ForbiddenIslandWorld extends World {
IList<Cell> board;
int waterHeight;
static final int ISLAND_SIZE = 64;
static final int WORLD_SIZE = ISLAND_SIZE * 10;
ForbiddenIslandWorld() {
this.board = this.makeIList(this.transformArraytoCell(this.makeMountain()));
}
IList<Cell> makeIList(ArrayList<ArrayList<Cell>> list) {
IList<Cell> result = new Empty<Cell>();
for (int i = 0; i < list.size(); i++) {
for (int j = 0; j < list.size(); j++) {
Cell component = list.get(i).get(j);
result = new Cons<Cell>(component, result);
}
}
return result;
}
ArrayList<ArrayList<Cell>> transformArraytoCell(ArrayList<ArrayList<Double>> list) {
ArrayList<ArrayList<Cell>> cList = new ArrayList<ArrayList<Cell>>();
for (int i = 0; i < list.size(); i++) {
ArrayList<Cell> row = new ArrayList<Cell>();
for (int j = 0; j < list.size(); j++) {
double height = list.get(i).get(j);
Cell c;
if (height > 0) {
c = new Cell(height, j, i);
}
else {
c = new OceanCell(j, i);
}
row.add(c);
}
cList.add(row);
}
for (int y = 0; y < cList.size(); y++) {
for (int x = 0; x < cList.size(); x++) {
ArrayList<Cell> row = cList.get(y);
Cell c = row.get(x);
if (y == 0) {
c.helpTop(c);
c.helpBot(cList.get(y + 1).get(x));
}
else if (y == cList.size() - 1) {
c.helpBot(c);
c.helpTop(cList.get(y - 1).get(x));
}
else {
Cell top = cList.get(y - 1).get(x);
Cell bot = cList.get(y + 1).get(x);
c.helpTop(top);
c.helpBot(bot);
}
if (x == 0) {
c.helpLeft(c);
c.helpRight(cList.get(y).get(x + 1));
}
else if (x == cList.size() - 1) {
c.helpRight(c);
c.helpLeft(cList.get(y).get(x - 1));
}
else {
Cell left = cList.get(y).get(x - 1);
Cell right = cList.get(y).get(x + 1);
c.helpLeft(left);
c.helpRight(right);
}
}
}
return cList;
}
ArrayList<ArrayList<Double>> makeMountain() {
ArrayList<ArrayList<Double>> newlist = new ArrayList<ArrayList<Double>>();
int h = ISLAND_SIZE / 2;
for (int y = 0; y <= ISLAND_SIZE; y++) {
ArrayList<Double> row = new ArrayList<Double>();
for (int x = 0; x <= ISLAND_SIZE; x++) {
double newX = Math.abs(h - x);
double newY = Math.abs(h - y);
double height = h - (newX + newY);
if (height < 0) {
height = 0;
}
row.add(height);
}
newlist.add(row);
}
return newlist;
}
ArrayList<ArrayList<Double>> makeRandomMountain() {
ArrayList<ArrayList<Double>> newlist = new ArrayList<ArrayList<Double>>();
int h = ISLAND_SIZE / 2;
Random r = new Random();
for (int i = 0; i <= ISLAND_SIZE; i++) {
ArrayList<Double> row = new ArrayList<Double>();
for (int j = 0; j <= ISLAND_SIZE; j++) {
double newX = Math.abs(h - j);
double newY = Math.abs(h - i);
double regHeight = h - (newX + newY);
double randHeight;
if (regHeight > 0) {
randHeight = 1 + r.nextInt(h);
}
else {
randHeight = 0;
}
row.add(randHeight);
}
newlist.add(row);
}
return newlist;
}
// to draw cells
public WorldScene drawCells() {
WorldScene w = new WorldScene(WORLD_SIZE, WORLD_SIZE);
for (Cell c : this.board) {
w.placeImageXY(c.drawCell(), Cell.CELL_SIZE * c.x, Cell.CELL_SIZE * c.y);
}
return w;
}
// to render
public WorldScene makeScene() {
return this.drawCells();
}
// to represent an onkeyevent
public void onKeyEvent(String ke) {
if (ke.equals("m")) {
this.board = this.makeIList(this.transformArraytoCell(this.makeMountain()));
}
else if (ke.equals("r")) {
this.board = this.makeIList(this.transformArraytoCell(this.makeRandomMountain()));
}
else {
}
}
}
// examples and tests
class ExamplesForbiddenIsland {
ForbiddenIslandWorld w1;
IList<String> emptylist;
Iterator<String> emptylistIt;
IList<String> list1;
IList<String> list2;
void initData() {
w1 = new ForbiddenIslandWorld();
emptylist = new Empty<String>();
emptylistIt = emptylist.iterator();
list1 = new Cons<String>("something", new Empty<String>());
list2 = new Cons<String>("something2", list1);
}
void testAsEmpty(Tester t) {
initData();
t.checkExpect(emptylist.asEmpty(), emptylist);
t.checkException(new RuntimeException("it is an empty"), list1, "asEmpty");
}
void testAsCons(Tester t) {
initData();
t.checkExpect(list1.asCons(), list1);
t.checkException(new RuntimeException("it is a cons"), emptylist, "asCons");
}
void testIsEmpty(Tester t) {
initData();
t.checkExpect(emptylist.isEmpty(), true);
t.checkExpect(list2.isEmpty(), false);
}
void testIsCons(Tester t) {
initData();
t.checkExpect(emptylist.isCons(), false);
t.checkExpect(list2.isCons(), true);
}
void testHasNext(Tester t) {
initData();
t.checkExpect(list1.iterator().hasNext(), true);
t.checkExpect(list2.iterator().hasNext(), true);
t.checkExpect(emptylist.iterator().hasNext(), false);
}
void testNext(Tester t) {
initData();
t.checkExpect(list2.iterator().next(), "something2");
t.checkExpect(list1.iterator().next(), "something");
t.checkException(new RuntimeException("There is no next"), emptylistIt, "next");
}
void testRemove(Tester t) {
initData();
t.checkException(new UnsupportedOperationException("Something"), emptylistIt, "remove");
}
void testMakeMountain(Tester t) {
initData();
t.checkExpect(w1.makeMountain().get(0).get(0), 0.0);
t.checkExpect(w1.makeMountain().get(32).get(32), 32.0);
t.checkExpect(w1.makeMountain().get(32).get(31), 31.0);
t.checkExpect(w1.makeMountain().get(31).get(32), 31.0);
}
void testMakeRandomMountain(Tester t) {
initData();
t.checkNumRange(w1.makeRandomMountain().get(32).get(32), 1, 32);
t.checkExpect(w1.makeRandomMountain().get(0).get(0), 0.0);
}
void testOnKeyEvent(Tester t) {
initData();
w1.onKeyEvent("m");
w1.onKeyEvent("r");
t.checkExpect(w1.board.iterator().next().height, 0.0);
}
void testGame(Tester t) {
initData();
w1.bigBang(ForbiddenIslandWorld.WORLD_SIZE, ForbiddenIslandWorld.WORLD_SIZE, 0.1);
}
} | XianpengChen/CS2510 | week 02/src/aaa.java |
249,129 | import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
public class Fish extends Sprite implements Runnable, Enemy{
protected String word;
protected int score;
protected boolean isAlive;
protected int velocity;
protected int width;
protected int xCoeff; // where the words are positioned within the fish
protected int yCoeff;
protected Ocean ocean;
private final static String ALIVE_FISH = "../images/fish_alive.png";
private final static String ZAPPED_FISH = "../images/fish_zapped.png";
private final static String DEAD_FISH = "../images/fish_dead.png";
private static int INITIAL_VELOCITY = 3;
public final static int WIDTH = 107;
private final static int XCOEFF = 35;
private final static int YCOEFF = 75;
//Overloaded constructor
public Fish(String letter, int score, int xPos, int yPos, String filename, Ocean ocean){
super(xPos, yPos, filename); // Shark Constructor
this.word = letter.toUpperCase();
this.score = score;
this.isAlive = true;
this.velocity = Shark.INITIAL_VELOCITY;
this.width = Shark.WIDTH;
this.xCoeff = Shark.XCOEFF;
this.yCoeff = Shark.YCOEFF;
this.ocean = ocean;
}
public Fish(String letter, int score, int xPos, int yPos, Ocean ocean){
super(xPos, yPos, Fish.ALIVE_FISH); // Actual fish constructor
this.word = letter;
this.score = score;
this.isAlive = true;
this.velocity = Fish.INITIAL_VELOCITY;
this.width = Fish.WIDTH;
this.xCoeff = Fish.XCOEFF;
this.yCoeff = Fish.YCOEFF;
this.ocean = ocean;
}
protected String getWord(){
return this.word;
}
protected boolean getIsAlive(){
return this.isAlive;
}
protected void resetWord(){
this.word = "";
}
protected int getScore(){
return this.score;
}
protected void setIsAlive(boolean status){
this.isAlive = status;
}
protected void moveLeft(int velocity){
super.decXPos(velocity);
}
protected void moveUp(){
super.decYPos(4);
}
@Override
public void run(){
// Three cases that a fish will die: 1. reached the diver 2. electrocuted 3. user typed correctly
while(this.isAlive == true){ // will break if the fish is alive or the fish has already reached the diver
this.moveLeft(this.velocity);
this.repaint();
try{
Thread.sleep(100);
} catch(Exception e){}
}
this.resetWord();
GameFrame.currentWord = "";
if(this.ocean.getDiver().isAlive() == true && this.isAlive == false){
if(super.getXPos() + this.width > 0){
if(this instanceof Shark) super.loadImage(Shark.ZAPPED_SHARK);
else if(this instanceof Fish) super.loadImage(Fish.ZAPPED_FISH);
this.repaint();
try{
Thread.sleep(200); // take some time to display image
} catch(Exception e){}
if(this instanceof Shark) super.loadImage(Shark.DEAD_SHARK);
else if(this instanceof Fish) super.loadImage(Fish.DEAD_FISH);
this.repaint();
while(super.getYPos() > 0){ // going up after killed
try{
Thread.sleep(100); // faster to go up
} catch(Exception e){}
this.moveUp();
this.repaint();
}
}
}
}
@Override // repaint is called
public void paintComponent(Graphics g){
if((this.isAlive == true || super.getYPos() > 0) && this.getXPos() + this.width > 0){ // if its xpos and ypos is still at the screen, paint
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
Font font = new Font("arial", Font.BOLD, 15);
FontMetrics fm = g.getFontMetrics(font);
int font_width = fm.stringWidth(GameFrame.currentWord);
g.setFont(font); // sets font
if(this.getWord().startsWith(GameFrame.currentWord) && GameFrame.currentWord != ""){ // reset the word typed by the user (accepted)
g.setColor(new Color(178,34,34));
g2d.drawString(GameFrame.currentWord, this.getXPos() + this.xCoeff, this.getYPos() + this.yCoeff); // common letters
g.setColor(Color.WHITE);
g2d.drawString(this.getWord().substring(GameFrame.currentWord.length()), this.getXPos() + font_width + this.xCoeff, this.getYPos() + this.yCoeff); // gets the remaining of the word
}
else{
g.setColor(Color.WHITE); // no common letters
g2d.drawString(this.getWord(), this.getXPos() + this.xCoeff, this.getYPos() + this.yCoeff);
}
}
}
}
/* Notes: Create final variables to the Shark and Fish, so that words will center
*/
| lolzz77/Typer-Shark | src/Fish.java |
249,132 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.StringTokenizer;
// 97,640kb / 776ms
public class Main {
static int N;
static int M;
static int[][] ocean;
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
ocean = new int[N][M];
for (int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < M; j++) {
ocean[i][j] = Integer.parseInt(st.nextToken());
}
}
br.close();
int years = 0;
int 빙산개수 = 1;
while (빙산개수 == 1) {
빙산을녹여라();
years++;
빙산개수 = 빙산이몇개고빙산말이다();
}
System.out.println(빙산개수 == 0 ? 0 : years);
}
static int[] dx = {1, -1, 0, 0};
static int[] dy = {0, 0, 1, -1};
static void 빙산을녹여라() {
boolean[][] processed = new boolean[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (ocean[i][j] != 0 || processed[i][j]) {
continue;
}
for (int d = 0; d < 4; d++) {
int nX = i + dx[d];
int nY = j + dy[d];
if (isRangeInvalid(nX, nY) || ocean[nX][nY] == 0) {
continue;
}
processed[nX][nY] = true;
ocean[nX][nY]--;
}
}
}
}
static int 빙산이몇개고빙산말이다() {
int count = 0;
boolean[][] visited = new boolean[N][M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
if (!visited[i][j] && ocean[i][j] != 0) {
bfs(i, j, visited);
count++;
}
}
}
return count;
}
static void bfs(int x, int y, boolean[][] visited) {
Deque<int[]> queue = new ArrayDeque<>();
visited[x][y] = true;
queue.offer(new int[]{x, y});
while (!queue.isEmpty()) {
int[] current = queue.poll();
for (int d = 0; d < 4; d++) {
int nX = current[0] + dx[d];
int nY = current[1] + dy[d];
if (isRangeInvalid(nX, nY) || visited[nX][nY] || ocean[nX][nY] == 0) {
continue;
}
visited[nX][nY] = true;
queue.offer(new int[]{nX, nY});
}
}
}
static boolean isRangeInvalid(int x, int y) {
return x < 0 || x >= N || y < 0 || y >= M;
}
}
| ssafy-cote/Hyun_Sanghyeok | 5주차/빙산.java |
249,133 | /*******************************************************************************
* @author Reika Kalseki
*
* Copyright 2017
*
* All rights reserved.
* Distribution of the software in any form is only allowed with
* explicit, prior permission from the owner.
******************************************************************************/
package Reika.ChromatiCraft;
import net.minecraft.util.StatCollector;
public class ChromaNames {
private static final String[] blockNames = {
};
public static final String[] fluidNames = {
"fluid.chroma", "fluid.endere", "fluid.potioncrystal", "fluid.luma", "fluid.lumen"//, "fluid.lifewater"
};
public static final String[] clusterNames = {
"crystal.redgroup", "crystal.greengroup", "crystal.orangegroup", "crystal.whitegroup",
"crystal.bunch0", "crystal.bunch1", "crystal.bunch2", "crystal.bunch3",
"crystal.cluster0", "crystal.cluster1", "crystal.core", "crystal.star", "crystal.multi"
};
public static final String[] craftingNames = {
"chromacraft.void", "chromacraft.lens", "chromacraft.focus", "chromacraft.mirror", "chromacraft.rawcrystal",
"chromacraft.energycore", "chromacraft.crystaldust", "chromacraft.transformcore", "chromacraft.elementunit",
"chromacraft.iridcrystal", "chromacraft.iridchunk", "chromacraft.ingot", "chromacraft.chassis0", "chromacraft.chassis1",
"chromacraft.chassis2", "chromacraft.chassis3", "chromacraft.ingot2", "chromacraft.ingot3", "chromacraft.ingot4", "chromacraft.ingot5",
"chromacraft.ingot6", "chromacraft.ingot7", "chromacraft.ingot8", "chromacraft.hivoid", "chromacraft.hitransformcore",
"chromacraft.hienergycore", "chromacraft.teledust", "chromacraft.icydust", "chromacraft.energydust", "chromacraft.etherberries",
"chromacraft.voiddust", "chromacraft.livingessence", "chromacraft.lumencore", "chromacraft.glowchunk", "chromacraft.experiencegem"
};
public static final String[] tieredNames = {
"chromacraft.chromadust", "chromacraft.auradust", "chromacraft.puredust", "chromacraft.focusdust", "chromacraft.elementdust",
"chromacraft.beacondust", "chromacraft.bindingcrystal", "chromacraft.resodust", "chromacraft.enderdust", "chromacraft.waterdust",
"chromacraft.firaxite", "chromacraft.lumadust", "chromacraft.echocrystal", "chromacraft.cavern", "chromacraft.burrow",
"chromacraft.ocean", "chromacraft.fireessence", "chromacraft.thermiticcrystal", "chromacraft.endcrystal", "chromacraft.spacedust",
"chromacraft.desert", "chromacraft.glowbeans", "chromacraft.boostroot", "chromacraft.lumengem", "chromacraft.avolite",
"chromacraft.snowstruct", "chromacraft.bedrockloot", "chromacraft.bedrockloot2"
};
public static final String[] dimGenNames = {
"chromaitem.dimgen.miasma", "chromaitem.dimgen.floatstone", "chromaitem.dimgen.aqua", "chromaitem.dimgen.lifewater", "chromaitem.dimgen.tubes",
"chromaitem.dimgen.geode", "chromaitem.dimgen.crysleaf", "chromaitem.dimgen.oceanstone", "chromaitem.dimgen.cliffshard", "chromaitem.dimgen.glowcave",
};
public static final String[] storageNames = {
"Nula", "Daya", "Divi", "Sami", "Vier", "Lima", "Aru"
};
public static final String[] miscNames = {
"chromamisc.silktouch", "chromamisc.speed", "chromamisc.efficiency", "chromamisc.stonematch", "chromamisc.groundmatch",
"chromamisc.orematch", "chromamisc.saplingmatch", "chromamisc.mobdropsmatch", "chromamisc.seedmatch", "chromamisc.flowermatch"
};
public static final String[] modInteractNames = {
"chromamod.crystalwand", "chromamod.firaxcap", "chromamod.watercap", "chromamod.endercap", "chromamod.finalcap", "chromamod.voidmonster"
};
public static final String[] coloredModInteractNames = {
"chromamod.comb",
};
private static String getName(String[] names, int i) {
return StatCollector.translateToLocal(names[i]);
}
}
| ReikaKalseki/ChromatiCraft | ChromaNames.java |
249,134 | // sky + ground
float xmotion = 8.8;
float ymotion = 2.2;
int reset = 0;
int perlin_amount = 80;
float[] ppx = new float[800 * 800];
float[] ppy = new float[800 * 800];
// https://iquilezles.org/www/articles/palettes/palettes.htm
float pal(float t, float a, float b, float c, float d) {
return a + b*cos( 6.28318*(c*t+d) );
}
void shapel(float x1, float y1, float x2, float y2, float dirx, float diry) {
float dx = x2 - x1;
float dy = y2 - y1;
float xx1 = x1;
float xx2 = x2;
if (x1 > x2) {
xx1 = x2;
xx2 = x1;
}
//noStroke();
strokeWeight(1);
for (float x = xx1; x < xx2; x += 1) {
float norm_dst = abs(x - xx2) / abs(xx2);
float anorm_dst = 1.0 - abs(0.5 - norm_dst) * 2;
float y = y1 + dy * (x - x1) / dx;
float ynorm = (y + (ymotion * 1.5)) / (float)height;
float anorm_y = 1.0 - abs(0.5 - ynorm) * 9;
float anorm_y2 = 1.0 - abs(0.5 - ynorm) * 8;
float n = (0.5-noise(x / (abs(x1 - x2)) + xmotion / 140 * anorm_y2, y / (abs(y1 - y2)) + ymotion / 240 * anorm_y2)) * 2 * anorm_y2;
float pa = 0.95;
float pb = 0.5;
float pc = 0.95;
float pdr = 0.05;
float pdg = 0.15;
float pdb = 0.2;
float rf = pal(1-abs(anorm_y / 20 + n), pa, pb, pc, pdr) * 255;
float gf = pal(1-abs(anorm_y / 20 + n), pa, pb, pc, pdg) * 255;
float bf = pal(1-abs(anorm_y / 20 + n), pa, pb, pc, pdb) * 255;
fill(rf, gf, bf, 12 + 4 * n);
stroke(rf / 1.425, gf / 1.425, bf / 1.425, 12 + 4 * n);
float s = 1 + 8 * anorm_dst;
if (dirx < 0 && diry < 0) {
ellipse(x - n * 32 - xmotion * 4 * ynorm, y - n * 120 * anorm_y2 - ymotion * 6 * ynorm, s * abs(n), s * abs(n));
} else if (dirx > 0 && diry > 0) {
ellipse(x + n * 32 + xmotion * 4 * ynorm, y + n * 120 * anorm_y2 + ymotion * 6 * ynorm, s * abs(n), s * abs(n));
} else if (dirx < 0 && diry > 0) {
ellipse(x - n * 32 - xmotion * 4 * ynorm, y + n * 120 * anorm_y2 + ymotion * 6 * ynorm, s * abs(n), s * abs(n));
} else if (dirx > 0 && diry < 0) {
ellipse(x + n * 32 + xmotion * 4 * ynorm, y - n * 120 * anorm_y2 - ymotion * 6 * ynorm, s * abs(n), s * abs(n));
}
//stroke(rf, gf, bf, 24 * abs(n));
//line(x - n * 180 - xmotion * 4, y - n * 180 + ymotion * 4, x + n * 180 - xmotion * 4, y + n * 180 + ymotion * 4);
}
stroke(0, 0, 255, 1);
}
void draw_func() {
noStroke();
rectMode(CENTER);
ellipseMode(CENTER);
float x1 = -100;
float y1 = 0;
float x2 = width + 100;
float y2 = 0.1;
stroke(0, 0, 255, 1);
strokeWeight(1);
//line(x1, y1, x2, y2);
shapel(x1, y1, x2, y2, 1, 1);
x1 = -100;
y1 = height;
x2 = width + 100;
y2 = height-0.1;
//line(x1, y1, x2, y2);
//shapel(x1, y1, x2, y2, -1, -1);
/*
x1 = 0;
y1 = height - height /1.99;
x2 = width;
y2 = height - height /2;
//line(x1, y1, x2, y2);
shapel(x1, y1, x2, y2, 1, -1);
x1 = 0;
y1 = height /1.99;
x2 = width;
y2 = height /2;
//line(x1, y1, x2, y2);
shapel(x1, y1, x2, y2, 1, -1);
*/
xmotion -= 0.01;
ymotion += 0.1;
}
void setup() {
size(800, 800);
background(0);
//colorMode(HSB, 360, 256, 256);
noiseDetail(6,0.65);
frameRate(60);
noFill();
noStroke();
rectMode(CENTER);
ellipseMode(CENTER);
stroke(0, 0, 255, 255);
strokeWeight(2);
strokeCap(ROUND);
noFill();
int nx = random(width / 2);
int ny = random(height / 2);
int lx = nx + random(width - nx);
//line(0, height - 192, width, height - 192);
//line(0, height - 192 / 1.15, width, height - 192 / 1.15);
//line(0, height - 192 / 1.3, width, height - 192 / 1.3);
//line(2 * 92, height + (2 - 1.45 * 512), width / 2, height + (2 - 1.45 * 512));
//line(3 * 84, height - 512, width / 2 - 3 * 84, height - 512);
//bezier(3.1 * 84, height - 550, 400, 0, 0, 0, 0, height - 2 * 550);
// bezier(2.6 * 84, height - 512, 400, 0, 100, 0, -200, height - 2 * 512);
// bezier(2 * 84, height - 512, 400, 0, 100, 0, -200, height - 2 * 512);
//bezier(1.4 * 84, height - 512, 400, 0, 100, 0, -200, height - 2 * 512);
//line(4 * 92, height - 1.25 * 512, width / 2 - 4 * 92, height - 1.25 * 512);
//rect(width / 2, height / 5, width / 5.5, width / 7);
//ellipse(width / 2, height / 5, width / 4, width / 7);
//line(2 * 92, height - 180, 64 + 2 * 148, height + (2 - 2 * 512));
//line(-92, height - 180, 64 + 48, height + (2 - 1 * 512));
for (int i = 0; i < 3; i += 1) {
//line(i * 92, height - 180, 64 + i * 148, height + (2 - i * 512));
//line(64 + i * 92, 0, 64 + i * 92, (128 + i * 32));
//line(64 + i * 92, 0, 256 + i * 92, (128 + i * 32));
//line(width / 3 - i * 128, height - 64, width / 3 - i * 128, height / 2 + height / 5);
}
//stroke(0, 0, 255, 92);
//line(width / 2, height - 210, width / 2, height - 192);
/*
for (int i = 0; i < 8; i += 1) {
ellipse(random(width / 8), random(height / 2, height / 1.6), 1, 1);
}*/
strokeWeight(2);
//line(300, 64, 300, height / 6);
//triangle(nx + random(width - nx), ny + random(height - ny), nx + random(width - nx), ny + random(height - ny), nx + random(width - nx), ny + random(height - ny));
//ellipse(width / 2, height / 2, height / 2, height / 2);
//rect(width / 3, height / 2, width / 5, height / 2);
//rect(width - width / 3, height / 2, width / 5, height / 2);
//rect(nx + random(width - nx), ny + random(height - ny), nx, ny);
//bezier(random(width / 2), random(height), random(width / 2), random(height), random(width / 2), random(height), random(width / 2), random(height));
//strokeWeight(1 + random(8));
//bezier(random(width / 2), random(height), random(width / 2), random(height), random(width / 2), random(height), random(width / 2), random(height));
rectMode(CORNER);
//smooth();
}
void mouseClicked() {
background(0);
reset = frameCount;
perlin_amount = random(40, 80);
}
void draw() {
draw_func();
} | grz0zrg/Computer-Graphics | opexport/431_ocean_pjs.js |
249,135 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* The arena where Pokemon run around. When they run into each other, they engage in battle
*
* PokeWorld control the flow state of the game. The PokeBattle arena checks Pokemon using
* OfficerJenny, runs animations, images, and sounds, and begins battles
*
* -----------------------------------------------------------------------------------------------------------------------------
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ FIELDS @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* PUBLIC FIELDS
* ------------------------------
* - none
*
* PRIVATE FIELDS
* ------------------------------
* - pokemonActive : The list of Pokemon that are active on the screen
*
* - WIDTH : The width of this World
* - HEIGHT : The height of this World
*
* - startMusic : Determines whether to start playing music or not
* - PALETTE, CELADON, CERULEAN, CINNABAR, LAVENDAR, OCEAN, VERMILLION : The different background music mp3 paths
* - SONG_LIST : The list of background music mp3s
* - bgMusic : The background music GreenfootSound
* - random : A Random object for randomizing
*
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ METHODS @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* PUBLIC METHODS
* ------------------------------
* - act() : Checks if any Pokemon have intersected. If they have, begin a PokeBattle betwee
* the two Pokemon, which sets a new world for the PokeBattle.java class
*
* - getActivePokemon() : Gets a list of the active Pokemon in this world
*
* - addPokemon( PokemonActor pokemon ) : Add this Pokemon to the activePokemon list
*
* - removeActivePokemon( PokemonActor pokemon ) : Remove this Pokemon from the activePokemon list
*
* PRIVATE METHODS
* ------------------------------
* - getRandomBGMusic() : Gets a random background song from the SONG_LIST
*
* - addOfficerJenny() : Adds Officer Jenny to the arena, who checks to make sure that active Pokemon are
* following all rules, standards, and regulations for the Pokemon's code and
* the Pokemon's fields. Pokemon that fail these rules, standards, or regulations
* will be disqualified
*
* - beginBattle( Pair pokemonPair ) : Begins a battle between the two Pokemon and sets the world to a new PokeBattle world
*
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ CONSTRUCTORS @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* - PokeArena() : Create a new PokeArena with two starting Pokemon in the arena
* - PokeArena( PokemonActor pokemon ) : Create a new PokeArena with the given Pokemon starting in the arena
*
* @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
* -----------------------------------------------------------------------------------------------------------------------------
*
* @author Peter Olson
* @version 1/17/22
* @see Pokedex.java
* @see Pokemon.java
* @see OfficerJenny.java
* @see Pikachu.java
* @see PokeBattle.java
* @see PokeWorld.java
*/
public class PokeArena extends PokeWorld {
private ArrayList<Actor> pokemonActive;
private final int WIDTH = 970;
private final int HEIGHT = 545;
private boolean startMusic = false;
private final String PALETTE = "./sounds/palette_town_theme.mp3";
private final String CELADON = "./sounds/celadon_city_theme.mp3";
private final String CERULEAN = "./sounds/cerulean_city_theme.mp3";
private final String CINNABAR = "./sounds/cinnabar_islands_theme.mp3";
private final String LAVENDAR = "./sounds/lavendar_town_theme.mp3";
private final String OCEAN = "./sounds/ocean_theme.mp3";
private final String VERMILLION = "./sounds/vermillion_city_theme.mp3";
private final String[] SONG_LIST = { PALETTE, CELADON, CERULEAN, CINNABAR, LAVENDAR, OCEAN, VERMILLION };
private GreenfootSound bgMusic;
private Random random = new Random();
/**
* Creates a new PokeArena with two Pokemon added to the world. These Pokemon are
* also added to the active Pokemon list
*
* @see addObject( Actor actor, int x, int y )
*/
public PokeArena() {
// Create a new world with 970x545 cells with a cell size of 1x1 pixels.
super(970, 545, 1);
Pikachu pika = null;
try {
pika = new Pikachu( 1 );
} catch( Pikachu.InvalidMoveTotalException e ) {
e.printStackTrace();
}
addObject( pika, WIDTH/2, HEIGHT/2 );
Pikachu pika2 = null;
try {
pika2 = new Pikachu( 2 );
} catch( Pikachu.InvalidMoveTotalException e ) {
e.printStackTrace();
}
addObject( pika2, 200, 200 );
pokemonActive = new ArrayList<Actor>();
pokemonActive.add( pika );
pokemonActive.add( pika2 );
//start playing background music. Comment this line out if you do not want to play any music!
startMusic = true;
}
/**
* Create a new PokeArena with one Pokemon spawned in, the victor of the last battle
*
* Note: Later versions should allow for the next combatent to enter through keystroke or
* simultaneously with the victorious Pokemon
*
* @see addObject( Actor actor, int x, int y )
*/
public PokeArena( PokemonActor pokemon ) {
super( 970, 545, 1 );
addObject( pokemon, WIDTH/2, HEIGHT/2 );
pokemonActive = new ArrayList<Actor>();
pokemonActive.add( pokemon );
//start playing background music. Comment this line out if you do not want to play any music!
startMusic = true;
}
/**
* Runs repeatedly, checking if Pokemon have intersected each other, which starts a battle, and if
* any Pokemon have run off the edge of the screen, which removes that Pokemon
*
* @see getRandomBGMusic()
* @see GreenfootSound.play()
* @see GreenfootSound.isPlaying()
* @see PokemonActor.isTouchingPokemon( Class cls )
* @see PokemonActor.getOneIntersectingPokemon( Class cls )
* @see beginBattle( Pair battlePair )
* @see removeObject( Actor actor )
*/
public void act() {
if( startMusic ) {
bgMusic = new GreenfootSound( getRandomBGMusic() );
bgMusic.play();
startMusic = false;
}
if( bgMusic != null && !bgMusic.isPlaying() ) {
bgMusic = new GreenfootSound( getRandomBGMusic() );
bgMusic.play();
}
if( Greenfoot.isKeyDown("space") )
addOfficerJenny();
for( Actor actor: pokemonActive ) {
if( ((PokemonActor)actor).isTouchingPokemon( PokemonActor.class ) ) {
Actor battlePokemon = ((PokemonActor)actor).getOneIntersectingPokemon( PokemonActor.class );
if( battlePokemon != null ) {
pokemonActive.clear();
beginBattle( new Pair( (PokemonActor)actor, (PokemonActor)battlePokemon ) );
break;
}
}
int actorX = actor.getX();
int actorY = actor.getY();
if( actorX > WIDTH || actorX < 0 || actorY > HEIGHT || actorY < 0 ) removeObject( actor );
}
}
/**
* Play a random background song from the SONG_LIST
*
* @return String The String path for this bg mp3 song
*/
private String getRandomBGMusic() {
return SONG_LIST[ random.nextInt( SONG_LIST.length ) ];
}
/**
* Adds an OfficerJenny to the Arena at a fixed coordinate
*
* This needs to be done not in the PokeArena constructor because the world needs to be
* instantiated before OfficerJenny starts inspecting Pokemon
*
* @see act()
*/
private void addOfficerJenny() {
OfficerJenny oj = new OfficerJenny();
addObject( oj, WIDTH/2 + 50, HEIGHT/2 );
}
/**
* Start a Pokemon battle using the pair of intersecting Pokemon
*
* A new battle creates new entities using the images of the Pokemon and a new world
* to create the battle scene. From there, sprites are handled by the PokeBattle
*
* @param pokemonPair This is the Pair of Pokemon that are entering into the battle
* @see act()
* @see removeObjects( List<Actor> actorList )
* @see Greenfoot.setWorld( World w )
*/
private void beginBattle( Pair pokemonPair ) {
bgMusic.stop();
removeObjects( pokemonActive );
Greenfoot.setWorld( new PokeBattle( pokemonPair, this ) );
}
/**
* Gets the list of active pokemon and returns them
*
* @return ArrayList<Actor> The list of active pokemon
*/
public ArrayList<Actor> getActivePokemon() {
return this.pokemonActive;
}
/**
* Adds a Pokemon to the active pokemon list
*
* @param pokemon The pokemon to be added to the list
*/
public void addPokemon( PokemonActor pokemon ) {
this.pokemonActive.add( pokemon );
}
/**
* Removes the given Pokemon from the list of active pokemon in this world
*
* @param pokemon The pokemon to be removed from the list
* @see OfficerJenny.disqualifyPokemon( PokemonActor pokemon, World world )
*/
public boolean removeActivePokemon( PokemonActor pokemon ) {
return this.pokemonActive.remove( pokemon );
}
}
| Peter-Olson/pokemon-game-greenfoot | PokeArena.java |
249,136 | public class Ocean {
Square[][] field;
public Ocean(Square[][] field){
this.field = field;
}
public void markSquare(int x, int y){
Square location = field[y][x];
location.makeHit();
}
public boolean wasItShot(int x, int y){
Square location = field[y][x];
return location.isHit() || location.isMiss()|| location.isSunk();
//return location.getState().equals("hit") || location.getState().equals("miss") || location.getState().equals("neighbor") || location.getState().equals("sunk");
}
public String stateOfSquare(int x, int y){
Square location = field[y][x];
return location.getState();
}
} | DavidCichy/battleshipsJava | Ocean.java |
249,137 | import java.util.Vector;
public class Grid {
private int width;
private int height;
private final String[][] ocean;
private static final char[] boatsCharacters = { '#', '@', '%', '$', '§' };
/**
* Constructor for the Grid class
* @param width of the grid
* @param height of the grid
*/
public Grid(int width, int height) {
this.width = width;
this.height = height;
if (this.width <= 0 || this.height <= 0) {
System.out.println(ConsoleColors.colorText("red", "Width and height must be positive, 10 be default"));
this.width = 10;
this.height = 10;
}
this.ocean = new String[width][height];
waterFill();
}
/**
* Fills the ocean array with waves
*/
private void waterFill() {
for (int i = 0; i < this.width; i++)
for (int j = 0; j < this.height; j++)
this.ocean[i][j] = "~";
}
/**
* Prints the grid in the console
*/
public void print() {
System.out.println(" " + " A B C D E F G H I J K L M N O P Q R S T U V W X Y Z".substring(0, this.width * 3));
for (int i = 0; i < this.height; i++) {
System.out.print(((i + 1) / 10 > 0 ? "" : " ") + (i + 1) + " ");
for (int j = 0; j < this.width; j++) {
System.out.print(" " + ConsoleColors.ANSI_RESET + (ocean[j][i].equals("~") ? ConsoleColors.ANSI_BLUE : ocean[j][i].equals("*") || ocean[j][i].equals("Ø") ? ConsoleColors.ANSI_RED : ConsoleColors.ANSI_YELLOW) + ocean[j][i] + " ");
}
System.out.println(ConsoleColors.ANSI_RESET);
}
System.out.println();
}
/**
* Calculate where are the boats in the grid and write it to lines of the grid
* @param boats Boat <code>Vector</code> containing the 5 boats
*/
public void calculateBoats(Vector<Boat> boats) {
// For each boat
for (int i = 0; i < boats.size(); i++) {
// Get coordinates of the boat
Vector<Float> boatPositions = boats.get(i).getPositions();
// For each coordinate
for (Float boatPosition : boatPositions) {
// Modify the corresponding case
this.ocean[(int) Math.floor(boatPosition) - 1][Math.round(boatPosition % 1 * 100) - 1] = String.valueOf(boatsCharacters[i]);
}
}
}
/**
* Change the grid to display shots
* @param position The position where the shot is
* @param hit If the shot hit a boat or not
*/
public void shoot (float position, boolean hit) {
this.ocean[(int) Math.floor(position) - 1][Math.round(position % 1 * 100) - 1] = String.valueOf(hit ? '*' : 'Ø');
}
}
| K0LALA/BattleShips | src/Grid.java |
249,138 | import java.util.Scanner; // Import the Scanner class
import java.util.concurrent.TimeUnit;
import java.util.HashMap;
import java.util.ArrayList; // import the ArrayList class
import java.util.Arrays; // import the ArrayList class
import java.util.List;
public class Main {
public static int R;
public static int C;
private static final int DELAY = 2;
private static void _print_column_indices(boolean with_indices){
if (with_indices){
System.out.print(" ");
for (int c = 0; c < C; c++)
System.out.print(c);
System.out.println();
System.out.print(" ");
for (int c = 0; c < C; c++)
System.out.print("_");
System.out.println();
}
}
private static void print_board(SubmarineFleet fleet, boolean with_indices, List<Integer> attack_history){
int current_index;
String hash_key;
Submarine current_submarine;
boolean in_attack_history;
_print_column_indices(with_indices);
for (int r=0; r<R; r++) {
if(with_indices){
System.out.print(r+"|");
}
for (int c = 0; c < C; c++) {
current_index = cordinates.to_index(r, c);
//check if this cordinate was attacked
in_attack_history = false;
for(int old_index : attack_history)
if(current_index == old_index)
in_attack_history = true;
if (!in_attack_history){
System.out.print(colors.ANSI_CYAN + "0" + colors.ANSI_RESET);
}else{
//check for submarine
hash_key = String.valueOf(current_index);
current_submarine = fleet.submarines.get(hash_key);
if (current_submarine == null) { // No submarine
System.out.print(colors.ANSI_CYAN + "x" + colors.ANSI_RESET);
}else{
System.out.print(colors.ANSI_YELLOW + "S" + colors.ANSI_RESET);
}
}
}
System.out.println();
}
System.out.println();
}
private static Integer[] get_random_attack_order(int M, int N){
//init attack arr with the indices
Integer [] attacks = new Integer[N*M];
for (int i=0; i<attacks.length; i++)
attacks[i] = i;
//t he attack order is random
int random;
int temp;
for (int i=0; i<attacks.length; i++){
random = (int )(Math.random() * attacks.length);
//swap
temp = attacks[i];
attacks[i] = attacks[random];
attacks[random] = temp;
}
return attacks;
}
private static cordinates get_attack_cordinates(Scanner scanner, int R, int C){
System.out.println("please select cordinates");
System.out.println(" Enter row (0 to " + (R-1)+")");
int r = scanner.nextInt(); // Read user input
while (r<0 || r>=R){
System.out.println("please enter valid row");
r = scanner.nextInt(); // Read user input
}
System.out.println(" Enter column (0 to " + (C-1)+")");
int c = scanner.nextInt(); // Read user input
while (c<0 || c>=C){
System.out.println("please enter valid column");
c = scanner.nextInt(); // Read user input
}
cordinates cordinate = new cordinates(r, c);
System.out.println("player attacked " + cordinate.repr());
return cordinate;
}
private static void get_ocean_size(Scanner scanner){
System.out.println("please select ocean size");
System.out.println(" Enter #rows (4 or more)");
int r = scanner.nextInt(); // Read user input
while (r<4){
System.out.println("please enter valid #rows");
r = scanner.nextInt(); // Read user input
}
System.out.println(" Enter #columns (4 or more)");
int c = scanner.nextInt(); // Read user input
while (c<4){
System.out.println("please enter valid #columns");
c = scanner.nextInt(); // Read user input
}
Main.R = r;
Main.C = c;
}
private static void computer_turn(SubmarineFleet player_fleet, Integer [] computer_attacks, int round)throws InterruptedException{
System.out.println(colors.ANSI_RED + "==computer_turn==" + colors.ANSI_RESET);
TimeUnit.SECONDS.sleep(DELAY);
int attack_location = computer_attacks[round];
List<Integer> attack_history = Arrays.asList(Arrays.copyOfRange(computer_attacks, 0, round + 1));
System.out.println("computer attacked " + cordinates.repr(attack_location));
TimeUnit.SECONDS.sleep(DELAY);
player_fleet.were_attacked(attack_location);
print_board(player_fleet, false, attack_history);
}
private static void player_turn(Scanner scanner, SubmarineFleet computer_fleet, List<Integer> player_attack_history)throws InterruptedException{
System.out.println(colors.ANSI_BLUE + "==player_turn==" + colors.ANSI_RESET);
TimeUnit.SECONDS.sleep(DELAY);
print_board(computer_fleet, true, player_attack_history);
int attack_location = get_attack_cordinates(scanner, R, C).get_index();
player_attack_history.add(attack_location);
computer_fleet.were_attacked(attack_location);
print_board(computer_fleet, false, player_attack_history);
}
public static void main(String[] args)throws InterruptedException {
Scanner scanner = new Scanner(System.in); // Create a Scanner object
get_ocean_size(scanner);
Integer [] computer_attacks = get_random_attack_order(R, C); // the attacks the computer will do
List<Integer> player_attack_history = new ArrayList<>();
SubmarineFleet player_fleet = new SubmarineFleet();
SubmarineFleet computer_fleet = new SubmarineFleet();
// game-loop
int round =0;
while(true){
System.out.println(colors.ANSI_YELLOW + "\n====== Round " + (round+1) +" ======" + colors.ANSI_RESET);
TimeUnit.SECONDS.sleep(DELAY);
computer_turn(player_fleet, computer_attacks, round);
if (player_fleet.functioning_submarine_amount == 0){
System.out.println(colors.ANSI_YELLOW + "\n\nComputer won!!!"+colors.ANSI_RESET);
System.exit(0);
}
player_turn(scanner, computer_fleet, player_attack_history);
if (computer_fleet.functioning_submarine_amount == 0){
System.out.println(colors.ANSI_YELLOW + "\n\nplayer won!!!"+colors.ANSI_RESET);
System.exit(0);
}
round+=1;
}
}
}
| rhaifa/submarines---java | src/Main.java |
249,139 | package Comparater;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Oceans {
public static void main(String[] args) {
Comparator<String> oceans = new SeedsComparaterImpl();
List<String> oceanList = new ArrayList<>();
System.out.println("Asending order list");
oceanList.add("Pacific Ocean");
oceanList.add("Atlantic Ocean");
oceanList.add("Indian Ocean");
oceanList.add("Southern Ocean");
oceanList.add("Arctic Ocean");
oceanList.add("Antarctic Ocean");
oceanList.add("North Atlantic Ocean");
oceanList.add("South Atlantic Ocean");
oceanList.add("North Pacific Ocean");
oceanList.add("South Pacific Ocean");
Collections.sort(oceanList);
for (String i :oceanList)
{
System.out.println(i);
}
System.out.println("***************************");
System.out.println("Desending order list");
Collections.sort(oceanList,oceans);
for (String i :oceanList)
{
System.out.println(i);
}
}
}
| HitheshAndhaniB/core-java | Oceans.java |
249,140 | import java.util.ArrayList;
class BattleShip {
private Ocean ocean1 = new Ocean();
private Player player1 = new Player(ocean1);
private Ocean ocean2 = new Ocean();
private Player player2 = new Player(ocean2);
public void display(ArrayList <ArrayList<Square>> board){
int indexOfRow = 1;
String topLetters =" A B C D E F G H I J ";
System.out.println(topLetters);
System.out.println();
for(ArrayList<Square> row : board){
if(indexOfRow <10){
System.out.print(indexOfRow + " ");
}else{
System.out.print(indexOfRow + " ");
}
for(Square square : row){
System.out.print(square.toString());
}
indexOfRow++;
System.out.println();
}
}
Integer player = 1;
public static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
public void game(){
System.out.println("Creator of ships for player 1.");
player1.addShipToUser(ocean1);
System.out.println("Creator of ships for player 2.");
player2.addShipToUser(ocean2);
while(true){
System.out.println("Player 1 shot: ");
player1.userShot();
ocean2.isHit(player1.getUserShot(), player2.getListOfUserShips());
display(ocean2.getBoard());
player1.checkIfWin(player2.getListOfUserShips());
System.out.println("Player 2 shot: ");
player2.userShot();
ocean1.isHit(player2.getUserShot(), player1.getListOfUserShips());
display(ocean1.getBoard());
player2.checkIfWin(player1.getListOfUserShips());
}
}
public static void main(String[] args) {
BattleShip newGame = new BattleShip();
newGame.game();
}
} | CodecoolGlobal/battle-ship-in-the-oo-way-statki-w-oop | BattleShip.java |
249,141 | import java.util.ArrayList;
public class ShipBuilder{
private ArrayList<Ship> ships = new ArrayList<Ship>();
private OceanGrid ocean;
public ShipBuilder(OceanGrid ocean){
//repeat making of ship 5 times(1 for each ship)
for (ShipType name : ShipType.values()){
ArrayList<Coordinate> coordinates = addCoords(name.getLength());
Ship ship = new Ship(name, name.getLength(), coordinates);
ships.add(ship);
}
}
public ArrayList<Coordinate> addCoords(int length){
}
}
| seank8/BattleShip | src/ShipBuilder.java |
249,142 | import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
// Class created to store information about an individual ocean or country. Fields correspond to variables or
// data of interest for the program.
public class Entry {
private static Map<String, Entry> entryMap = new HashMap<>();
private String name;
private String url;
private String lowestPoint;
private int area;
private String coordinates;
private String flagFeatures;
private ArrayList<String> borderCountries;
private String region;
private float oceanArea;
private float coastline;
private float population65;
private float sexRatio;
private float electricity;
private ArrayList<String> plugTypes;
public Entry(String name, String url) {
this.name = name;
this.url = url;
entryMap.put(name,this);
}
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public String getUrl() {return url;}
public void setUrl(String url) {this.url = url;}
public String getLowestPoint() {return lowestPoint;}
public void setLowestPoint(String lowestPoint) {this.lowestPoint = lowestPoint;}
public int getArea() {return area;}
public void setArea(int area) {this.area = area;}
public String getCoordinates() {return coordinates;}
public void setCoordinates(String coordinates) {this.coordinates = coordinates;}
public void setFlagFeature(String features) { this.flagFeatures = features; }
public String getFlagFeature() { return flagFeatures; }
public void setBorderCountries(ArrayList<String> borderCountries) {this.borderCountries = borderCountries;}
public ArrayList<String> getBorderCountries() {return borderCountries;}
public void setRegion(String region) {this.region = region;}
public String getRegion() {return region;}
public float getOceanArea() {return oceanArea;}
public void setOceanArea(float area) {this.oceanArea = area;}
public float getCoastline() {return coastline;}
public void setCoastline(float coastline) {this.coastline = coastline;}
public float getPopulation65() {return population65;}
public void setPopulation65(float pop) {this.population65 = pop;}
public float getSexRatio() {return sexRatio;}
public void setSexRatio(float ratio) {this.sexRatio = ratio;}
public ArrayList<String> getPlugTypes (){return plugTypes;}
public void setPlugTypes(ArrayList<String> plugs) {this.plugTypes = plugs;}
public float getElectricity() {return electricity;}
public void setElectricity(float electricity) {this.electricity = electricity;}
public static Entry getEntry(String name) {
return entryMap.get(name);
}
}
| joeywei2718/NETS150HW3 | src/Entry.java |
249,143 | package practice1;
//import gnu.dtools.ritopt.IntOption;
//import gnu.dtools.ritopt.BooleanOption;
//import gnu.dtools.ritopt.StringOption;
//import gnu.dtools.ritopt.Options;
//import gnu.dtools.ritopt.Option;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.net.*;
import java.io.PrintWriter;
import java.io.BufferedWriter;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class BattleShip
{
BufferedReader readFrom;
PrintWriter writeTo;
ServerSocket aServerSocket;
String ocean;
String hostName;
int port;
boolean first;
boolean second;
String WIDTH = "width";
String HEIGHT = "height";
String WATER = "w";
int WATER_VALUE = -1;
int WATER_HIT_VALUE = -2;
int HIT_VALUE = -3;
String lineDelimiter = "#";
int[][] battleField = null; // This is the field shown to the player
int[][] originalBattleField = null; // will be initialized once
String battleFieldString = null; // will be initialized once
int battleFieldWidth = 0;
int battleFieldHeight = 0;
Scanner battleFieldParser = null;
char hit = 'x';
String fileName = null;
//FOR REFLECTIONS_EX
// private BattleShip() { //private constructors are not exposed in reflections
// System.out.println("HELLO");
// }
//
// public BattleShip(int a) {
// System.out.println("HELLO: "+a);
// }
void parseArgs(String[] args ) {
this.ocean = "b1.txt";
this.hostName = "localhost";
this.first = true;
this.second = false;
// IntOption portO = new IntOption(0);
// StringOption oceanO = new StringOption("");
// StringOption hostNameO = new StringOption("");
// BooleanOption firstO = new BooleanOption(false);
// BooleanOption secondO = new BooleanOption(false);
//
// Options options = new Options("BattleShip");
// options.register("port", portO);
// options.register("ocean", oceanO);
// options.register("hostName", hostNameO);
// options.register("first", firstO);
// options.register("second", secondO);
//
// options.process(args);
//
// port = portO.getValue();
// ocean = oceanO.getValue();
// hostName = hostNameO.getValue();
// first = firstO.getValue();
// second = secondO.getValue();
}
private void removeAllPartsOfBoat(int column,int row) {
int boatId = originalBattleField[column][row];
for ( int rows = 0; rows < battleFieldHeight; rows ++ ) {
for ( int columns = 0; columns < battleFieldWidth; columns ++ ) {
if ( originalBattleField[columns][rows] == boatId )
battleField[columns][rows] = HIT_VALUE;
}
}
}
private void printBattleField(int[][] battleField) {
System.out.println();
for ( int rows = 0; rows < battleFieldHeight; rows ++ ) {
for ( int columns = 0; columns < battleFieldWidth; columns ++ ) {
if ( battleField[columns][rows] == WATER_VALUE )
System.out.print( "w" + " " );
else
System.out.print( battleField[columns][rows] + " " );
}
System.out.println();
}
System.out.println();
}
private void printBattleFieldForPlayer(int[][] battleField) {
System.out.println();
System.out.println("x indicates a hit.");
System.out.println("w indicates a miss, but you know now there is water.");
System.out.println(". indicates boat oder water.\n");
System.out.print( " " );
for ( int columns = 0; columns < battleFieldWidth; columns ++ ) {
System.out.print( " " + columns );
}
System.out.println(" ---> columns");
for ( int rows = 0; rows < battleFieldHeight; rows ++ ) {
System.out.print(rows + ": " );
for ( int columns = 0; columns < battleFieldWidth; columns ++ ) {
if ( battleField[columns][rows] == WATER_HIT_VALUE )
System.out.print( " " + "w" );
else if ( battleField[columns][rows] == HIT_VALUE )
System.out.print( " " + "x" );
else
System.out.print( " " + "." );
}
System.out.println();
}
System.out.println();
}
private boolean isThereAboatLeft() {
boolean rValue = false;
for ( int rows = 0; ! rValue && rows < battleFieldHeight; rows ++ ) {
for ( int columns = 0; ! rValue && columns < battleFieldWidth; columns ++ ) {
if ( battleField[columns][rows] >= 0 )
rValue = true;
}
}
return rValue;
}
private boolean allWater() {
for ( int column = 0; column < battleFieldWidth; column ++ ) {
for ( int row = 0; row < battleFieldWidth; row ++ ) {
if ( battleField[column][row] != WATER_VALUE )
return false;
}
}
return true;
}
private void readHeightWidth() {
for (int index = 0; index < 2; index ++ ) {
if ( battleFieldParser.hasNextLine() ) {
String[] oneDimension = battleFieldParser.nextLine().split("\\s+");
if ( oneDimension[0].equals(WIDTH) )
battleFieldWidth = Integer.parseInt(oneDimension[1]);
else
battleFieldHeight = Integer.parseInt(oneDimension[1]);
}
}
}
private void createBattleField() {
battleField = new int[battleFieldWidth][battleFieldHeight];
originalBattleField = new int[battleFieldWidth][battleFieldHeight];
for ( int columns = 0; columns < battleFieldWidth; columns ++ ) {
for ( int rows = 0; rows < battleFieldHeight; rows ++ ) {
battleField[columns][rows] = WATER_VALUE;
originalBattleField[columns][rows] = WATER_VALUE;
}
}
}
private void updateBattleField() {
for ( int columns = 0; columns < battleFieldWidth; columns ++ ) {
for ( int rows = 0; rows < battleFieldHeight; rows ++ ) {
if ( originalBattleField[columns][rows] >= 0 )
battleField[columns][rows] = 0;
}
}
}
private void readBattleFieldScenario() {
for ( int index = 0; index < battleFieldHeight; index ++ ) {
if ( battleFieldParser.hasNextLine() ) {
String[] oneRow = battleFieldParser.nextLine().split("\\s+");
for ( int xPosition = 1; xPosition < battleFieldWidth + 1; xPosition ++ ) {
if (! oneRow[xPosition].equals(WATER) ) {
String id = oneRow[xPosition].substring(1, oneRow[xPosition].length() );
originalBattleField[xPosition-1][index] = Integer.parseInt(id);
}
}
}
}
}
private void readBattleFieldFile(String fileName) { // new
if ( fileName.equals("exit")) {
System.exit(0);
}
int column = 0;
try {
battleFieldString = "";
battleFieldParser = new Scanner(new File(fileName));
while ( battleFieldParser.hasNextLine() ) {
battleFieldString += battleFieldParser.nextLine() + lineDelimiter ;
}
} catch (FileNotFoundException e) {
System.out.println("Can't find that file! Try Again.");
}
}
// new
private void readBattleFieldFromString(String theBattleFieldInStringForm) {
int column = 0;
theBattleFieldInStringForm = theBattleFieldInStringForm.replaceAll(lineDelimiter, "\n");
battleFieldParser = new Scanner(theBattleFieldInStringForm);
readHeightWidth();
createBattleField();
readBattleFieldScenario();
updateBattleField();
}
private int readOneIntValue(Scanner readUserInput, String text) {
System.out.print(text);
if ( readUserInput.hasNextInt() )
return readUserInput.nextInt();
else {
System.out.println("Can't read next integer - RIP");
System.exit(1);
}
return -1;
}
private boolean checkRange(int minValue, int value, int maxValue, String errorMessage) {
if ( ( minValue <= value) && ( value < maxValue ) ) {
return true;
} else {
System.out.println("Error: " + errorMessage );
return false;
}
}
private void readTheOceans() { // new
if ( first ) {
sendData(battleFieldString);
String theOtherOnes = readData();
readBattleFieldFromString(theOtherOnes);
} else {
String theOtherOnes = readData();
readBattleFieldFromString(theOtherOnes);
sendData(battleFieldString);
}
}
private void play() {
readTheOceans(); // new
Scanner readUserInput = new Scanner( System.in);
int row = 0;
int column = 0;
int soManyTries = 0;
while ( isThereAboatLeft() ) {
soManyTries++;
printBattleFieldForPlayer(battleField);
column = readOneIntValue(readUserInput,
"column coordinate (0 <= column < " + battleFieldWidth + "): ");
row = readOneIntValue(readUserInput,
"row coordinate (0 <= row < " + battleFieldHeight + "): ");
if ( checkRange(0, column, battleFieldWidth, "Column out of range. " + column) &&
checkRange(0, row, battleFieldHeight, "Row out of range. " + row ) )
if ( originalBattleField[column][row] == WATER_VALUE ) {
battleField[column][row] = WATER_HIT_VALUE;
} else {
System.out.println("HIT");
removeAllPartsOfBoat(column,row);
}
printBattleFieldForPlayer(battleField);
}
printBattleFieldForPlayer(battleField);
}
private void sendData(String theData) { // new
System.out.println("sendData: ");
try {
writeTo.println(theData);
} catch ( Exception e ) {
e.printStackTrace();
}
}
private String readData() { // new
System.out.println("readData: ");
String rValue = "";
try {
rValue = readFrom.readLine();
} catch ( Exception e ) {
e.printStackTrace();
}
return rValue;
}
private void setUpIO() { // new
if ( first ) {
try {
aServerSocket = new ServerSocket(0); // 0 would be a other way
System.out.println(aServerSocket.getLocalPort());
Socket theReadFromSocket = aServerSocket.accept();
readFrom = new BufferedReader( new InputStreamReader( theReadFromSocket.getInputStream()));
writeTo = new PrintWriter(theReadFromSocket.getOutputStream (), true);
} catch ( Exception e ) {
e.printStackTrace();
}
} else {
try {
Socket theReadFromSocket = new Socket(hostName, port);
writeTo = new PrintWriter (theReadFromSocket.getOutputStream (), true);
readFrom = new BufferedReader( new InputStreamReader( theReadFromSocket.getInputStream()));
} catch ( Exception e ) {
e.printStackTrace();
}
}
}
private void playTheGame(String[] args) {
parseArgs(args);
readBattleFieldFile(ocean); // new
setUpIO();
play();
}
public static void main(String[] args) {
new BattleShip().playTheGame(args);
}
} | lahari07/Battleship-2player | BattleShip.java |
249,144 | import java.util.List;
import java.util.Arrays;
import java.util.Scanner;
import java.util.InputMismatchException;
public class Engine {
private static Scanner scanner = new Scanner(System.in);
private static Sunk sunk = new Sunk();
private static int turnCounter = 0;
public void runGame() {
int option = 1;
boolean isRunning = true;
boolean isCheatOn = false;
String difficulty = "easy";
while (option != 0 && isRunning == true) {
try {
printMenu();
option = scanner.nextInt();
switch (option) {
case 1:
difficulty = choseDifficultySetting("Enemy");
fightPvC(isCheatOn, difficulty);
isRunning = false;
break;
case 2:
fightPvP();
isRunning = false;
break;
case 3:
String difficulty1 = choseDifficultySetting("Enemy 1");
String difficulty2 = choseDifficultySetting("Enemy 2");
fightCvC(difficulty1, difficulty2);
isRunning = false;
break;
case 4:
isCheatOn = true;
difficulty = choseDifficultySetting("Enemy");
fightPvC(isCheatOn, difficulty);
isRunning = false;
break;
// case 5:
// difficulty = "medium";
// fightPvC(isCheatOn, difficulty);
// isRunning = false;
// break;
// case 6:
// difficulty = "hard";
// fightPvC(isCheatOn, difficulty);
// isRunning = false;
// break;
case 0:
System.out.println("Bye bye");
break;
default:
;
}
}
catch (InputMismatchException e) {scanner.next();}
}
}
private static void printMenu() {
String options[] = {"Single player", "Multiplayer", "Simulation", "Single player - cheat mode"};
System.out.print("\033[H\033[2J");
System.out.flush();
System.out.println("WELCOME TO BATTLESHIP GAME\n");
System.out.println("MENU:");
for (int i = 1; i <= options.length; i++)
System.out.println(" " + i + ". " + options[i - 1]);
System.out.println(" 0. Exit game.");
}
private static void printDifficulties(String targetName) {
String options[] = {"Easy", "Medium", "Hard"};
System.out.print("\033[H\033[2J");
System.out.flush();
System.out.println("Set difficulty for " + targetName);
for (int i = 1; i <= options.length; i++)
System.out.println(" " + i + ". " + options[i - 1]);
}
private static void fightPvC(boolean isCheatOn, String difficulty) {
Ocean player1Ocean = getPlayerOcean();
Ocean enemyOcean = getEnemyOcean();
if (isCheatOn == false) {
enemyOcean.hideBoard();
}
GameBoard boardPVC = new GameBoard(player1Ocean, enemyOcean);
DisplayBoard displayBoardPVC = new DisplayBoard(boardPVC.toString());
clearScreen();
displayBoardPVC.displayBoard();
//Add fight
int playerId = 1;
int enemyId = 2;
Player player1 = new Player(player1Ocean, playerId);
Enemy enemy1 = new Enemy(enemyOcean, enemyId);
if (difficulty == "medium") {
enemy1 = new EnemyMedium(enemyOcean, enemyId);
} else if (difficulty == "hard") {
enemy1 = new EnemyHard(enemyOcean, enemyId);
}
gameLoopPvC(player1, enemy1, displayBoardPVC, boardPVC, difficulty);
if (player1.getIsDefeated() == true) {
System.out.println("YOU LOST IN " + turnCounter + " TURNS");
} else if (enemy1.getIsDefeated() == true) {
System.out.println("YOU WON IN " + turnCounter + " TURNS");
}
}
private static String choseDifficultySetting (String targetName) {
int option = 1;
boolean isRunning = true;
String difficulty = null;
while (isRunning == true) {
try {
printDifficulties(targetName);
option = scanner.nextInt();
switch (option) {
case 1:
difficulty = "easy";
isRunning = false;
break;
case 2:
difficulty = "medium";
isRunning = false;
break;
case 3:
difficulty = "hard";
isRunning = false;
break;
}
}
catch (InputMismatchException e) {scanner.next();}
}
return difficulty;
}
private static void gameLoopPvC(Player player1, Enemy enemy1, DisplayBoard displayBoardPVC, GameBoard boardPVC, String difficulty) {
Ocean player1Ocean = player1.getPlayerOcean();
Ocean enemyOcean = enemy1.getPlayerOcean();
while(player1.getIsDefeated() == false && enemy1.getIsDefeated() == false) {
if(turnCounter % 2 == 0){
player1.playerTurn(enemyOcean);
sunk.checkIfSunk(enemyOcean);
clearScreen();
displayBoardPVC = new DisplayBoard(boardPVC.toString());
displayBoardPVC.displayBoard();
waitUntilEnter();
} else {
clearScreen();
enemy1.enemyTurn(player1Ocean, difficulty);
sunk.checkIfSunk(player1Ocean);
displayBoardPVC = new DisplayBoard(boardPVC.toString());
displayBoardPVC.displayBoard();
}
player1.checkIfDefeated();
enemy1.checkIfDefeated();
turnCounter++;
}
}
private static void gameLoopCvC(Enemy enemy1, Enemy enemy2, DisplayBoard displayBoardCVC, GameBoard boardCVC, String difficulty1, String difficulty2) {
Ocean enemy1Ocean = enemy1.getPlayerOcean();
Ocean enemy2Ocean = enemy2.getPlayerOcean();
while(enemy1.getIsDefeated() == false && enemy2.getIsDefeated() == false) {
if(turnCounter % 2 == 0){
clearScreen();
enemy1.enemyTurn(enemy2Ocean, difficulty1);
sunk.checkIfSunk(enemy2Ocean);
displayBoardCVC = new DisplayBoard(boardCVC.toString());
displayBoardCVC.displayBoard();
waitUntilEnter();
} else {
clearScreen();
enemy2.enemyTurn(enemy1Ocean, difficulty2);
sunk.checkIfSunk(enemy1Ocean);
displayBoardCVC = new DisplayBoard(boardCVC.toString());
displayBoardCVC.displayBoard();
}
enemy1.checkIfDefeated();
enemy2.checkIfDefeated();
turnCounter++;
}
}
private static void gameLoopPvP(Player player1,Player player2, DisplayBoard displayBoard1PVP, GameBoard board1PVP,
DisplayBoard displayBoard2PVP, GameBoard board2PVP) {
Ocean player1Ocean = player1.getPlayerOcean();
Ocean player2Ocean = player2.getPlayerOcean();
while(player1.getIsDefeated() == false && player2.getIsDefeated() == false) {
if(turnCounter % 2 == 0){
player1.playerTurn(player2Ocean);
sunk.checkIfSunk(player2Ocean);
displayBoard1PVP = new DisplayBoard(board1PVP.toString());
displayBoard1PVP.displayBoard();
waitUntilEnter();
} else {
player2.playerTurn(player1Ocean);
sunk.checkIfSunk(player1Ocean);
displayBoard2PVP = new DisplayBoard(board2PVP.toString());
displayBoard2PVP.displayBoard();
waitUntilEnter();
}
player1.checkIfDefeated();
player2.checkIfDefeated();
turnCounter++;
}
}
private static void fightPvP() {
System.out.println("Player 1 set ship positions");
waitUntilEnter();
Ocean player1Ocean = getPlayerOcean();
List<Ship> hiddenPlayer1Ships = crateShips();
clearScreen();
System.out.println(("Player 2 set ship positions"));
waitUntilEnter();
Ocean player2Ocean = getPlayerOcean();
List<Ship> hiddenPlayer2Ships = crateShips();
clearScreen();
Ocean hiddenPlayer1Ocean = player1Ocean.deepCopyOcean(hiddenPlayer1Ships, player1Ocean.getShips());
Ocean hiddenPlayer2Ocean = player2Ocean.deepCopyOcean(hiddenPlayer2Ships, player2Ocean.getShips());
GameBoard board1PVP = new GameBoard(player1Ocean, hiddenPlayer2Ocean);
GameBoard board2PVP = new GameBoard(player2Ocean, hiddenPlayer1Ocean);
DisplayBoard displayBoard1PVP = new DisplayBoard(board1PVP.toString());
DisplayBoard displayBoard2PVP = new DisplayBoard(board2PVP.toString());
// dont display because you can see other player
// displayBoard1PVP.displayBoard();
// displayBoard2PVP.displayBoard();
//fight
int playerId = 1;
int player2Id = 2;
Player player1 = new Player(player1Ocean, playerId);
Player player2 = new Enemy(player2Ocean, player2Id);
gameLoopPvP(player1, player2, displayBoard1PVP, board1PVP, displayBoard2PVP, board2PVP);
if (player1.getIsDefeated() == true) {
System.out.println("PLAYER 1 WON IN " + turnCounter + " TURNS");
} else if (player2.getIsDefeated() == true) {
System.out.println("PLAYER 2 WON IN " + turnCounter + " TURNS");
}
}
private static void fightCvC(String difficulty1, String difficulty2) {
Ocean enemy1Ocean = getEnemyOcean();
Ocean enemy2Ocean = getEnemyOcean();
GameBoard boardCVC = new GameBoard(enemy1Ocean, enemy2Ocean);
DisplayBoard displayBoardCVC = new DisplayBoard(boardCVC.toString());
clearScreen();
displayBoardCVC.displayBoard();
//Add fight
int enemy1Id = 1;
int enemy2Id = 2;
Enemy enemy1 = new Enemy(enemy1Ocean, enemy1Id);
if (difficulty1 == "medium") {
enemy1 = new EnemyMedium(enemy1Ocean, enemy1Id);
} else if (difficulty1 == "hard") {
enemy1 = new EnemyHard(enemy1Ocean, enemy1Id);
}
Enemy enemy2 = new Enemy(enemy2Ocean, enemy2Id);
if (difficulty2 == "medium") {
enemy2 = new EnemyMedium(enemy2Ocean, enemy2Id);
} else if (difficulty2 == "hard") {
enemy2 = new EnemyHard(enemy2Ocean, enemy2Id);
}
gameLoopCvC(enemy1, enemy2, displayBoardCVC, boardCVC, difficulty1, difficulty2);
if (enemy1.getIsDefeated() == true) {
System.out.println("PLAYER 1 WON IN " + turnCounter + " TURNS");
} else if (enemy2.getIsDefeated() == true) {
System.out.println("PLAYER 2 WON IN " + turnCounter + " TURNS");
}
}
private static Ocean getPlayerOcean() {
List<Ship> playerShips = crateShips();
Ocean playerOcean = new Ocean(playerShips);
playerOcean.putShipsOnBoard(playerShips, playerOcean);
return playerOcean;
}
private static Ocean getEnemyOcean() {
List<Ship> enemyShips = crateShips();
Ocean enemyOcean = new Ocean(enemyShips);
enemyOcean.generateEnemyOcean(enemyShips, enemyOcean);
return enemyOcean;
}
public static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
private static void waitUntilEnter() {
System.out.println("Press Enter to continue");
try {
System.in.read();
} catch (Exception e) {};
}
private static List<Ship> crateShips() {
Ship Carrier = new Ship("Carrier", 5, true, 0, 0);
Ship Battleship = new Ship("Battleship", 4, true, 0, 0);
Ship Cruiser = new Ship("Cruiser", 3, false, 0, 0);
Ship Submarine = new Ship("Submarine", 3, true, 0, 0);
Ship Destroyer = new Ship("Destroyer", 2, true, 0, 0);
List<Ship> ships = Arrays.asList(Carrier, Battleship, Cruiser, Submarine, Destroyer);
// List<Ship> ships = Arrays.asList(Submarine, Destroyer);
return ships;
}
}
| CodecoolGlobal/battle-ship-in-the-oo-way-battleship_lak | src/Engine.java |
249,145 | import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Player {
//close it
private Scanner scanner = new Scanner(System.in);
private Ocean playerOcean;
private int playerId;
private boolean isDefeated = false;
public Player(Ocean playerOcean, int playerId) {
this.playerOcean = playerOcean;
this.playerId = playerId;
}
public Ocean getPlayerOcean() {
return playerOcean;
}
public int getPlayerId() {
return playerId;
}
public boolean getIsDefeated() {
return isDefeated;
}
public void setIsDefeatedTrue() {
isDefeated = true;
}
public void playerTurn(Ocean enemyOcean) {
printMessage();
Coordinates chosenSqureCoordinates = getChoice(enemyOcean);
markChosenSquare(chosenSqureCoordinates, enemyOcean);
}
public void printMessage () {
System.out.println("It is now Player " + playerId + " turn");
}
public Coordinates getChoice (Ocean enemyOcean) {
List<String> letters = playerOcean.getLetters();
List<String> strNumbers = playerOcean.getStrNumbers();
System.out.println("Choose coordinates, which you would like to strike");
Square chosenSquare = new Square();
Coordinates chosenSqureCoordinates = new Coordinates(0, 0);
boolean isRunning = true;
while (isRunning == true) {
chosenSqureCoordinates = getCoordinatesFromPlayer(letters, strNumbers);
chosenSquare = enemyOcean.getSqare(chosenSqureCoordinates);
if(chosenSquare.getIsHit() == false) {
isRunning = false;
}
}
return chosenSqureCoordinates;
}
public Coordinates getCoordinatesFromPlayer (List<String> valuesListLetters, List<String> valuesListNumbers) {
boolean isRunning = true;
// Scanner scanner = new Scanner(System.in);
Coordinates square = new Coordinates(0, 0);
while (isRunning == true) {
String playerInput = scanner.nextLine().toUpperCase();
String letterCoordinate = null;
String numCoordinate = null;
try {
char letterCoordinateChar = playerInput.charAt(0);
letterCoordinate = String.valueOf(letterCoordinateChar);
} catch (Exception StringIndexOutOfBoundsException) {
continue;
}
try {
char numCoordinateChar = playerInput.charAt(1);
numCoordinate = String.valueOf(numCoordinateChar);
} catch (Exception StringIndexOutOfBoundsException) {
continue;
}
//check standard cases
if (checkInputLength(playerInput, 2) == true &&
valuesListLetters.contains(letterCoordinate) && valuesListNumbers.contains(numCoordinate)) {
square.setX(valuesListLetters.indexOf(letterCoordinate));
square.setY(valuesListNumbers.indexOf(numCoordinate));
isRunning = false;
}
//check case when input is a10 or f10 etc:
if (checkInputLength(playerInput, 3) == true &&
checkInputFor10thRow(playerInput) == true && valuesListLetters.contains(letterCoordinate)) {
numCoordinate = "10";
square.setX(valuesListLetters.indexOf(letterCoordinate));
square.setY(valuesListNumbers.indexOf(numCoordinate));
isRunning = false;
}
}
// scanner.close();
return square;
}
public boolean checkInputFor10thRow (String inputString) {
try {
if (inputString.charAt(1) == '1' && inputString.charAt(2) == '0') {
return true;
}
} catch (Exception StringIndexOutOfBoundsException) {
;
}
return false;
}
public boolean checkInputLength(String inputString, int lengthToCompare) {
if (inputString.length() == lengthToCompare) {
return true;
} else {
return false;
}
}
public void markChosenSquare (Coordinates chosenSqureCoordinates, Ocean targetOcean) {
Square chosenSquare = targetOcean.getSqare(chosenSqureCoordinates);
chosenSquare.hit();
}
public void checkIfDefeated () {
List<Ship> playerShips = playerOcean.getShips();
// first all ShipsSunk is set to true, then if exits ship which is not sunk, set it to false
boolean allShipsSunk = true;
for (int index = 0; index < playerShips.size(); index++) {
Ship nextShip = playerShips.get(index);
nextShip.updateIsSunk();
if (nextShip.getIsSunk() == false) {
allShipsSunk = false;
}
}
if (allShipsSunk == true) {
setIsDefeatedTrue();
}
}
}
| CodecoolGlobal/battle-ship-in-the-oo-way-battleship_lak | src/Player.java |
249,146 | public class Output {
private static final Output INSTANCE = new Output();
private final Grid targetGrid;
private final Grid oceanGrid;
private Output() {
this.targetGrid = Computer.getGrid();
this.oceanGrid = Player.getGrid();
}
public static Output getInstance() {
return INSTANCE;
}
public void print() {
System.out.println("===== TARGET GRID =====");
printGrid(this.targetGrid);
System.out.print("=======================\n-----------------------\n");
System.out.println("===== OCEAN GRID =====");
printGrid(this.oceanGrid);
System.out.println("=======================");
}
private void printGrid(Grid grid) {
String LETTERS = " A B C D E F G H I J ";
System.out.println(LETTERS);
String SEPARATOR = " +-+-+-+-+-+-+-+-+-+-+ ";
System.out.println(SEPARATOR);
for (int i=0;i<10;i++){
System.out.print(i);
for (int j=0;j<10;j++){
System.out.print("|"+grid.getGrid()[i][j]);
}
System.out.println("|"+i);
}
System.out.println(SEPARATOR);
System.out.println(LETTERS);
}
}
| tom7689/Ex.1 | src/Output.java |
249,149 | import javax.swing.*;
import javax.swing.border.Border;
import java.awt.*;
import java.util.*;
import java.util.List;
/**
* Created by Ruzan on 11/20/2016.
*/
public class OceanScreen extends JPanel
{
Controller c;
List<Rectangle> cells;
int xOffset,yOffset;
OceanListener ol;
public OceanScreen(Controller c, JLabel turn)
{
ol = new OceanListener(this, c, turn);
addMouseListener(ol);
Border raisedBevel = BorderFactory.createRaisedBevelBorder();
Border loweredBevel = BorderFactory.createLoweredBevelBorder();
Border compound = BorderFactory.createCompoundBorder
(raisedBevel, loweredBevel);
setBorder(compound);
this.c = c;
xOffset = 0;
yOffset = 0;
}
public void wake(boolean t)
{
ol.setAwake(t);
}
public void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
int height = getHeight();
int width = getWidth();
int cellWidth = width / Game.MAX_COLUMN;
int cellHeight = height / Game.MAX_ROW;
cells = new ArrayList<>(Game.MAX_COLUMN * Game.MAX_ROW);;
int xOffset = (width - (Game.MAX_COLUMN * cellWidth)) / 2;
int yOffset = (height - (Game.MAX_ROW * cellHeight)) / 2;
for (int row = 0; row < Game.MAX_ROW; row++) {
for (int col = 0; col < Game.MAX_COLUMN; col++) {
Rectangle cell = new Rectangle(
xOffset + (col * cellWidth),
yOffset + (row * cellHeight),
cellWidth,
cellHeight);
cells.add(cell);
}
}
char [][]board = c.getOBoard();
for(int i = 1; i < board.length - 1; i++)
{
for(int j = 1; j < board[i].length - 1; j++)
{
int index = j - 1 + ((i -1) * Game.MAX_COLUMN);
Rectangle cell = cells.get(index);
if(board[i][j] == 'H')
{
g2d.setColor(Color.RED);
}
else if(board[i][j] == 'M')
{
g2d.setColor(Color.GREEN);
}
else
{
g2d.setColor(Color.decode("#C2DFFF"));
}
g2d.fill(cell);
}
}
g2d.setColor(Color.DARK_GRAY);
for(Rectangle cell : cells)
{
g2d.draw(cell);
}
}
}
| ruzansasuri/battleship | src/OceanScreen.java |
249,150 |
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.*;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import static org.junit.jupiter.api.Assertions.*;
/**
* This is the test for ocean class.
* No comments here.
* @author Jason Su and Xiaoying Zhang
*/
public class OceanTest {
private Ocean ocean;
@BeforeEach
public void oceanSetup() {
ocean = new Ocean();
}
@Test
void buildShips() {
assertEquals("battleship" , ocean.buildShips()[0].getShipType());
assertEquals("cruiser" , ocean.buildShips()[1].getShipType());
assertEquals("cruiser" , ocean.buildShips()[2].getShipType());
assertEquals("destroyer" , ocean.buildShips()[3].getShipType());
assertEquals("destroyer" , ocean.buildShips()[5].getShipType());
assertEquals("destroyer" , ocean.buildShips()[4].getShipType());
assertEquals("submarine" , ocean.buildShips()[6].getShipType());
assertEquals("submarine" , ocean.buildShips()[7].getShipType());
assertEquals("submarine" , ocean.buildShips()[8].getShipType());
assertEquals("submarine" , ocean.buildShips()[9].getShipType());
}
@Test
void placeAllShipsRandomly() {
ocean.placeAllShipsRandomly();
Ship[][] ships = ocean.getShipArray();
int battleship = 0;
int cruiser = 0;
int destroyer = 0;
int submarine = 0;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
Ship currentShip = ships[i][j];
if (currentShip instanceof Battleship) {
battleship++;
} else if (currentShip instanceof Cruiser) {
cruiser++;
} else if (currentShip instanceof Destroyer) {
destroyer++;
} else if (currentShip instanceof Submarine) {
submarine++;
}
}
}
assertEquals(4, battleship); //1*4
assertEquals(6, cruiser); //2*3
assertEquals(6, destroyer); //3*2
assertEquals(4, submarine); //4*1
}
@Test
void testGameOver() {
ocean.placeAllShipsRandomly();
for(int i = 0; i < 10; i++){
ocean.shootAt(0, i);
}
assertFalse(ocean.isGameOver());
for(int i = 0; i< 10; i++){
for(int j = 0; j < 10; j++) {
ocean.shootAt(i, j);
}
}
assertTrue(ocean.isGameOver());
}
@Test
void testOccupy() {
Ship battleShip = new Battleship();
Ship cruiser = new Cruiser();
Ship destroyer = new Destroyer();
battleShip.placeShipAt(0,0,true,ocean);
cruiser.placeShipAt(5,5,false,ocean);
destroyer.placeShipAt(7, 9,false,ocean);
assertFalse(ocean.isOccupied(1,1));
assertTrue(ocean.isOccupied(0,0));
assertTrue(ocean.isOccupied(0,3));
assertFalse(ocean.isOccupied(5,4));
assertTrue(ocean.isOccupied(5,5));
assertTrue(ocean.isOccupied(7,5));
assertFalse(ocean.isOccupied(6,9));
assertTrue(ocean.isOccupied(7,9));
assertTrue(ocean.isOccupied(8,9));
}
@Test
void shootAt_H() {
Battleship b = new Battleship();
b.placeShipAt(5,5,false,ocean);
assertTrue(ocean.shootAt(5,5));
assertEquals(1, ocean.getHitCount());
assertEquals(1, ocean.getShotsFired());
assertTrue(ocean.shootAt(5,5));
assertEquals(2, ocean.getHitCount());
assertEquals(2, ocean.getShotsFired());
assertTrue(ocean.shootAt(5,5));
assertEquals(3, ocean.getHitCount());
assertEquals(3, ocean.getShotsFired());
assertTrue(ocean.shootAt(6,5));
assertEquals(4, ocean.getHitCount());
assertEquals(4, ocean.getShotsFired());
assertTrue(ocean.shootAt(7,5));
assertEquals(5, ocean.getHitCount());
assertEquals(5, ocean.getShotsFired());
assertTrue(ocean.shootAt(8,5));
assertEquals(6, ocean.getHitCount());
assertEquals(6, ocean.getShotsFired());
assertEquals(1, ocean.getShipsSunk());
assertFalse(ocean.shootAt(5,5));
assertEquals(6, ocean.getHitCount());
assertEquals(7, ocean.getShotsFired());
assertFalse(ocean.shootAt(5,4));
assertFalse(ocean.shootAt(4,6));
assertFalse(ocean.shootAt(4,5));
assertFalse(ocean.shootAt(5,5));
assertEquals(11, ocean.getShotsFired());
assertEquals(6, ocean.getHitCount());
}
@Test
void shootAt_V() {
Destroyer d = new Destroyer();
d.placeShipAt(5,5,false,ocean);
assertTrue(ocean.shootAt(5,5));
assertEquals(1, ocean.getHitCount());
assertEquals(1, ocean.getShotsFired());
assertTrue(ocean.shootAt(5,5));
assertEquals(2, ocean.getHitCount());
assertEquals(2, ocean.getShotsFired());
assertTrue(ocean.shootAt(6,5));
assertEquals(3, ocean.getHitCount());
assertEquals(3, ocean.getShotsFired());
assertFalse(ocean.shootAt(6,5));
assertEquals(3, ocean.getHitCount());
assertEquals(4, ocean.getShotsFired());
assertEquals(1, ocean.getShipsSunk());
assertFalse(ocean.shootAt(5,4));
assertFalse(ocean.shootAt(4,6));
assertFalse(ocean.shootAt(4,5));
assertFalse(ocean.shootAt(5,5));
}
@Test
void shootAt_All() {
ocean.placeAllShipsRandomly();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
ocean.shootAt(i, j);
}
}
assertEquals(20, ocean.getHitCount());
assertEquals(100, ocean.getShotsFired());
for (int i = 0; i < 10;i++) {
for (int j = 0; j < 10; j++) {
ocean.shootAt(i, j);
}
}
assertEquals(20, ocean.getHitCount());
assertEquals(200, ocean.getShotsFired());
assertEquals(10, ocean.getShipsSunk());
}
@Test
public void testPrint() {
PrintStream originalOut = System.out;
OutputStream outStream = new ByteArrayOutputStream();
PrintStream inStream = new PrintStream(outStream);
System.setOut(inStream);
Submarine s = new Submarine();
Destroyer d = new Destroyer();
s.placeShipAt(0,5,false,ocean);
d.placeShipAt(0,8,true,ocean);
ocean.shootAt(0,7);
ocean.shootAt(0,5);
ocean.shootAt(0,8);
ocean.shootAt(0,0);
ocean.print();
String print = outStream.toString();
int start = print.indexOf("0\t-");
String firstRow = print.substring(start,start+21);
System.out.println(print);
System.out.println(firstRow);
assertEquals("0\t-\t.\t.\t.\t.\tX\t.\t-\tS\t.", firstRow); //check row 1 meet
System.out.close();
System.setOut(originalOut);
}
}
| LizZhangxiaoying/BattleShipGame | src/OceanTest.java |
249,151 | import java.util.Scanner;
public class GameController {
private Ocean ocean1;
private String playerOneName;
private Ai computer1;
private Ocean ocean2;
private String playerTwoName;
private Ai computer2;
private String coordsPattern = "[a-jA-J][1-9][0]*";
private Scanner scan;
private View view;
private boolean isRunning = true;
private String winner;
public GameController(Ocean ocean1, String player1, Ocean ocean2, String player2) {
this.ocean1 = ocean1;
this.ocean2 = ocean2;
this.playerOneName = player1;
this.playerTwoName = player2;
if (player1.equals("easy") || player1.equals("medium")) {
this.computer1 = new Ai(player1);
}
if (player2.equals("easy") || player2.equals("medium") ) {
this.computer2 = new Ai(player2);
}
}
public GameController(Ocean ocean1, Ocean ocean2) {
this(ocean1, "Player 1", ocean2, "Player 2");
}
public void run() {
initialise();
while (this.isRunning) {
runTurn(ocean1, ocean2, true);
if (isRunning)
runTurn(ocean2, ocean1, false);
}
view.displayEndScreen(winner, ocean1.getMap(), ocean2.getMap());
scan.nextLine();
}
void initialise() {
scan = new Scanner(System.in);
view = new View();
}
void runTurn(Ocean oceanOwner, Ocean oceanOppo, boolean isP1Turn) {
boolean isTurnOver = false;
String input;
String playerName;
if (isP1Turn)
playerName = playerOneName;
else
playerName = playerTwoName;
if (!isAiTurn(isP1Turn) && (computer1 == null && computer2 == null)){
view.clearDisplay();
view.printMessage(playerName + ": Press enter to start your turn.");
scan.nextLine();
}
while (!isTurnOver) {
if (isSimulation() && isP1Turn) view.displaySimScreen(oceanOwner.getMap(), oceanOppo.getMap());
else if (isSimulation() && !isP1Turn) view.displaySimScreen(oceanOppo.getMap(), oceanOwner.getMap());
else view.displayGameScreen(oceanOwner.getMap(), oceanOppo.getMap());
input = getTarget(oceanOppo, isP1Turn);
if (isSimulation() && isP1Turn) view.displaySimScreen(oceanOwner.getMap(), oceanOppo.getMap());
else if (isSimulation() && !isP1Turn) view.displaySimScreen(oceanOppo.getMap(), oceanOwner.getMap());
if (!input.matches(this.coordsPattern)) {
view.messageStream.add("Please enter valid coordinates (example: B5).");
} else {
int[] coords = oceanOppo.getSquareLocation(input);
if (oceanOppo.getMap().get(coords[0]).get(coords[1]).getIsHit()){
view.messageStream.add("You've already hit this square!");
} else {
oceanOppo.getMap().get(coords[0]).get(coords[1]).markHit();
if (!oceanOppo.getMap().get(coords[0]).get(coords[1]).hasShip()){
isTurnOver = true;
view.messageStream.add(playerName + " has hit the " + input + " and it's a miss.");
} else {
oceanOppo.isShipSunk(input);
if (oceanOppo.getMap().get(coords[0]).get(coords[1]).getShip().getIsSunk()){
view.messageStream.add(playerName + " has sunk the " + oceanOppo.getMap().get(coords[0]).get(coords[1]).getShip().getShipName() + "!");
} else view.messageStream.add(playerName + " has hit the " + oceanOppo.getMap().get(coords[0]).get(coords[1]).getShip().getShipName() + "!");
}
}
}
if (oceanOppo.areAllSunk()){
isRunning = false;
winner = playerName;
isTurnOver = true;
}else if (isTurnOver){
if (!isAiTurn(isP1Turn)){
view.displayGameScreen(oceanOwner.getMap(), oceanOppo.getMap(), true);
scan.nextLine();
}
}
}
}
private String getTarget(Ocean targetOcean, boolean isP1Turn){
String target;
if (isP1Turn && computer1 != null){
target = computer1.getCoordinatesToShoot(targetOcean);
} else if (!isP1Turn && computer2 != null){
target = computer2.getCoordinatesToShoot(targetOcean);
}else target = scan.nextLine();
return target;
}
private boolean isAiTurn(boolean isP1Turn){
boolean result = false;
if ((isP1Turn && computer1 != null) || (!isP1Turn && computer2 != null)) result = true;
return result;
}
private boolean isSimulation(){
if (!(computer1 == null) && !(computer2 == null)) return true;
return false;
}
} | CodecoolGlobal/battle-ship-in-the-oo-way-war_games | GameController.java |
249,152 | package frc.robot;
public class RobotMap {
public static final double LENS_HEIGHT_INCHES = 8.5;
public static final double MOUNTING_ANGLE = 33;
public static final double kTurnP = 0;
public static final double kTurnI = 0;
public static final double kTurnD = 0;
public static final double kMaxTurnAccelerationDegPerSSquared = 0;
public static final double ARM_TOLERANCE = 2;
public static final double kMaxTurnRateDegPerS = 0;
public static final double kTurnToleranceDeg = 0;
public static final double kTurnRateToleranceDegPerS = 0;
public static final double ARM_SPEED = 0.2;
public static final int DESIRED_PICTURE_HEIGHT = 640;
public static final int DESIRED_PICTURE_WIDTH = 360;
public static final int DESIRED_FRAMES_PER_SECOND = 60;
public static final int RIGHT_REAR_DRIVE = 3;
public static final int LEFT_FRONT_DRIVE = 7;
public static final int RIGHT_FRONT_DRIVE = 4;
public static final int LEFT_REAR_DRIVE = 9;
public static final int RIGHT_SHOOTER = 1;
public static final int LEFT_SHOOTER = 5;
public static final int RIGHT_ARM = 6;
public static final int LEFT_ARM = 2;
public static final int INTAKE = 8;
public static final int DRIVER_CONTROLLER1 = 0;
public static final int DRIVER_CONTROLLER2 = 1;
public static final int CAMERA_PORT = 0;
public static final int LED_PORT = 0;
public static final int LEFT_STICK_Y = 1;
public static final int RIGHT_STICK_Y = 5;
public static final int LEFT_STICK_X = 0;
public static final int RIGHT_TRIGGER = 3;
public static final int LEFT_TRIGGER = 2;
public static final int RIGHT_STICK_X = 4;
public static final int RIGHT_BUMPER = 6;
public static final int LEFT_BUMPER = 5;
public static final int Y_BUTTON = 4;
public static final int X_BUTTON = 3;
public static final int A_BUTTON = 1;
public static final int B_BUTTON = 2;
public static final int LEFT_STICK_BUTTON = 9;
public static final int RIGHT_STICK_BUTTON = 10;
public static final int BACK_BUTTON = 7;
public static final int START_BUTTON = 8;
public static final int TANK_DRIVE_DRIVING = 1;
public static final int DOUBLE_TANK_DRIVING = 2;
public static final int VIDEO_GAME_DRIVING = 3;
public static final int DOUBLE_VIDEO_GAME_DRIVING = 4;
public static final double ARM_FLOOR = 0;
public static final double ARM_CEILING = 45;
public static final double RED_FLOOR = 0;
public static final double RED_CEILING = 0;
public static final double GREEN_FLOOR = 0;
public static final double GREEN_CEILING = 0;
public static final double BLUE_CEILING = 0;
public static final double BLUE_FLOOR = 0;
public static final double RAINBOW_PALETTE = -0.99;
public static final double RAINBOW_PARTY_PALETTE = -0.97;
public static final double RAINBOW_OCEAN_PALETTE = -0.95;
public static final double RAINBOW_LAVE_PALETTE = -0.93;
public static final double RAINBOW_FOREST_PALETTE = -0.91;
public static final double RAINBOW_GLITTER = -0.89;
public static final double CONFETTI = -0.87;
public static final double SHOT_RED = -0.85;
public static final double SHOT_BLUE = -0.83;
public static final double SHOT_WHITE = -0.81;
public static final double SINELON_RAINBOW = -0.79;
public static final double SINELON_PARTY = -0.77;
public static final double SINELON_OCEAN = -0.75;
public static final double SINELON_LAVA = -0.73;
public static final double SINELON_FOREST = -0.71;
public static final double BEATS_RAINBOW = -0.69;
public static final double BEATS_PARTY = -0.67;
public static final double BEATS_OCEAN = -0.65;
public static final double BEATS_LAVA = -0.63;
public static final double BEATS_FOREST = -0.61;
public static final double FIRE_MEDIUM = -0.59;
public static final double FIRE_LARGE = -0.57;
public static final double TWINKLES_RAINBOW = -0.55;
public static final double TWINKLES_PARTY = -0.53;
public static final double TWINKLES_OCEAN = -0.51;
public static final double TWINKLES_LAVA = -0.49;
public static final double TWINKLES_FOREST = -0.47;
public static final double WAVES_RAINBOW = -0.45;
public static final double WAVES_PARTY = -0.43;
public static final double WAVES_OCEAN = -0.41;
public static final double WAVES_LAVA = -0.39;
public static final double WAVES_FOREST = -0.37;
public static final double LARSON_RED = -0.35;
public static final double LARSON_GRAY = -0.33;
public static final double CHASE_RED = -0.31;
public static final double CHASE_BLUE = -0.29;
public static final double CHASE_GRAY = -0.27;
public static final double HEARTBEAT_RED = -0.25;
public static final double HEARTBEAT_BLUE = -0.23;
public static final double HEARTBEAT_WHITE = -0.21;
public static final double HEARTBEAT_GRAY = -0.19;
public static final double BREATH_RED = -0.17;
public static final double BREATH_BLUE = -0.15;
public static final double BREATH_GRAY = -0.13;
public static final double STROBE_RED = -0.11;
public static final double STROBE_BLUE = -0.09;
public static final double STROBE_GOLD = -0.07;
public static final double STROBE_WHITE = -0.05;
public static final double COLOR1_BLEND_TO_BLACK = -0.03;
public static final double COLOR1_LARSON_SCANNER = -0.01;
public static final double COLOR1_LIGHT_CHASE = 0.01;
public static final double COLOR1_HEARTBEAT_SLOW = 0.03;
public static final double COLOR1_HEARTBEAT_MEDIUM = 0.05;
public static final double COLOR1_HEARTBEAT_FAST = 0.07;
public static final double COLOR1_BREATH_SLOW = 0.09;
public static final double COLOR1_BREATH_FAST = 0.11;
public static final double COLOR1_SHOT = 0.13;
public static final double COLOR1_STROBE = 0.15;
public static final double COLOR2_BLEND_TO_BLACK = 0.17;
public static final double COLOR2_LARSON_SCANNER = 0.19;
public static final double COLOR2_LIGHT_CHASE = 0.21;
public static final double COLOR2_HEARTBEAT_SLOW = 0.23;
public static final double COLOR2_HEARTBEAT_MEDIUM = 0.25;
public static final double COLOR2_HEARTBEAT_FAST = 0.27;
public static final double COLOR2_BREATH_SLOW = 0.29;
public static final double COLOR2_BREATH_FAST = 0.31;
public static final double COLOR2_SHOT = 0.33;
public static final double COLOR2_STROBE = 0.35;
public static final double SPARKLE_COLOR1_ON_COLOR2 = 0.37;
public static final double SPARKLE_COLOR2_ON_COLOR1 = 0.39;
public static final double GRADIENT_COLOR1_AND_COLOR2 = 0.41;
public static final double BPM_COLOR1_AND_COLOR2 = 0.43;
public static final double BLEND_COLOR1_TO_COLOR2 = 0.45;
public static final double BLEND_COLOR2_TO_COLOR1 = 0.47;
public static final double COLOR1_AND_COLOR2 = 0.49;
public static final double TWINKLES_COLOR1_AND_COLOR2 = 0.51;
public static final double WAVES_COLOR1_AND_COLOR2 = 0.53;
public static final double SINELON_COLOR1_AND_COLOR2 = 0.55;
public static final double HOT_PINK = 0.57;
public static final double DARK_RED = 0.59;
public static final double RED = 0.61;
public static final double RED_ORANGE = 0.63;
public static final double ORANGE = 0.65;
public static final double GOLD = 0.67;
public static final double YELLOW = 0.69;
public static final double LAWN_GREEN = 0.71;
public static final double LIME = 0.73;
public static final double DARK_GREEN = 0.75;
public static final double GREEN = 0.77;
public static final double BLUE_GREEN = 0.79;
public static final double AQUA = 0.81;
public static final double SKY_BLUE = 0.83;
public static final double DARK_BLUE = 0.85;
public static final double BLUE = 0.87;
public static final double BLUE_VIOLET = 0.89;
public static final double VIOLET = 0.91;
public static final double WHITE = 0.93;
public static final double GRAY = 0.95;
public static final double DARK_GRAY = 0.97;
public static final double BLACK = 0.99;
public static final Integer LEFT_AUTON = 1;
public static final Integer RIGHT_AUTON = 3;
}
| JDM2024/Competition-2024 | robot/RobotMap.java |
249,153 | package UI;
import Grid.Coordinates.Row;
import java.util.Iterator;
public class Display {
private static final String targetTitle = "===== TARGET GRID =====\n";
private static final String oceanTitle = "===== OCEAN GRID =====\n";
private static final String letters = " A B C D E F G H I J \n";
private static final String symbols = "+-+-+-+-+-+-+-+-+-+-+-+\n";
private static final String line = "-----------------------\n";
private static final String equals = "=======================\n";
private final int totalLengthOfField;
public Display() {
this.totalLengthOfField = Row.values().length;
}
public void display(Iterator<String> oceanGrid, Iterator<String> targetGrid, String message) {
//next line of Code because the IDE doesn't clear the Terminal
clearScreen();
displayGrid(targetGrid, targetTitle);
System.out.print(line);
displayGrid(oceanGrid, oceanTitle);
System.out.println(message);
}
private void displayGrid(Iterator<String> gridIterator, String title){
int lengthOfField = 0;
int row = 0;
String field = "";
System.out.print(title+letters+symbols);
while(gridIterator.hasNext()){
if(lengthOfField == 0){
field = field.concat(Integer.toString(row)+"|");
}
field =field.concat(gridIterator.next()+"|");
lengthOfField++;
if(lengthOfField== (totalLengthOfField)){
field = field.concat(Integer.toString(row) +"\n");
lengthOfField = 0;
row++;
}
}
System.out.print(field);
System.out.print(symbols+letters+equals);
}
private static void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
} | ChlineSaurus/SoftCon_Assignment_01 | src/UI/Display.java |
249,155 | public class Constantes {
// Adresses du fichier xml et de la dtd
public final static String pathToDeviceFile = "/home/caucagne1/workspace/PLDreseaux10/GHomeProxy/src/capteurs.xml";
public final static String dtdFile = "capteurs.dtd";
public final static int TAILLE_TRAME_ENOCEAN = 28;
// Adresse de la base des capteurs
public final static String IP_BASE = "134.214.105.28";
public final static int PORT_BASE = 5000;
// Adresse du serveur GHome
public final static String IP_GHOME = "134.214.59.214";
public final static int PORT_GHOME = 443;
// Pour le serveur simulé
public final static int PORT_SERV_ENVOI = 8000;
// Type de trame (envoyée au serveur)
public final static char TYPE_STATUS = 'S';
public final static char TYPE_DONNEES = 'D';
// Type de trame (envoyée par serveur)
public final static char TYPE_LANCEMENT = 'L';
public final static char TYPE_FIN = 'F';
public final static char TYPE_ORDRE = 'O';
public final static char TYPE_UPDATE_VILLE = 'V';
// Type de trame status
public final static char TYPE_AJOUT = 'A';
public final static char TYPE_RETRAIT = 'R'; // Capteur plus détecté
// Type capteur logique
public final static char TYPE_L_LUMINOSITE = 'L';
public final static char TYPE_L_TEMPERATURE = 'T';
public final static char TYPE_L_HUMIDITE = 'H';
public final static char TYPE_L_PRESENCE = 'P';
public final static char TYPE_L_CONTACT = 'C'; // Contact fenêtre ou porte fermée
public final static char TYPE_L_INTERRUPTEUR = 'I';
public final static char TYPE_L_ACTIONNEUR = 'E';
public final static char TYPE_L_METEO_TEMP = 'U';
public final static char TYPE_L_METEO_HUM = 'V';
// Type physique des capteurs
public final static String TYPE_P_INTERRUPTEUR_4 = "05-02-01";
public final static String TYPE_P_PRISE = "prise"; // actionneur
public final static String TYPE_P_PRESENCE = "07-08-01"; // light, temp & occupancy
public final static String TYPE_P_CONTACT = "06-00-01";
public final static String TYPE_P_TEMPERATURE = "07-02-05";
public final static String TYPE_P_METEO = "meteo";
// Correspondance Index dans le tableau de caractères / byte EnOcean
public final static int INDEX_SYNC_BYTE_1_1 = 0;
public final static int INDEX_SYNC_BYTE_1_2 = 1;
public final static int INDEX_SYNC_BYTE_2_1 = 2;
public final static int INDEX_SYNC_BYTE_2_2 = 3;
public final static int HSEQ_LENGTH_1 = 4;
public final static int HSEQ_LENGTH_2 = 5;
public final static int ORG_1 = 6;
public final static int ORG_2 = 7;
public final static int DATA_BYTE_3_1 = 8;
public final static int DATA_BYTE_3_2 = 9;
public final static int DATA_BYTE_2_1 = 10;
public final static int DATA_BYTE_2_2 = 11;
public final static int DATA_BYTE_1_1 = 12;
public final static int DATA_BYTE_1_2 = 13;
public final static int DATA_BYTE_0_1 = 14;
public final static int DATA_BYTE_0_2 = 15;
public final static int ID_BYTE_3_1 = 16;
public final static int ID_BYTE_3_2 = 17;
public final static int ID_BYTE_2_1 = 18;
public final static int ID_BYTE_2_2 = 19;
public final static int ID_BYTE_1_1 = 20;
public final static int ID_BYTE_1_2 = 21;
public final static int ID_BYTE_0_1 = 22;
public final static int ID_BYTE_0_2 = 23;
public final static int STATUS_1 = 24;
public final static int STATUS_2 = 25;
public final static int CHECKSUM_1 = 26;
public final static int CHECKSUM_2 = 27;
// Temps au bout duquel l'alerte enlèvement est déclenchée (ou la météo
// envoyée)
public final static int DELAI_DECLENCHEMENT_TIMER = 60000;
//public final static int DELAI_DECLENCHEMENT_TIMER = 9000000;
// Code postal de la ville dont on regarde la meteo (variable globale plutôt
// que constante)
public static int VILLE = 69008;
}
| Opteamal-GHome/GHome-Proxy | Constantes.java |
249,158 | import java.util.ArrayList;
import exceptions.BoatOutOfBoundsException;
import exceptions.BoatOverlappingException;
public class Ocean {
private ArrayList<Boat> boats;
public Ocean(){
boats = new ArrayList<Boat>();
}
public void placeBoat(String boatName, String direction, Position pos) throws BoatOutOfBoundsException, BoatOverlappingException {
Boat testBoat = new Boat(boatName, pos, direction);
//check for overlapping boats
for(Boat b : boats){
//vertical check
if(direction.equals("Vertical")){
for(int i = 0; i<testBoat.size()+1; i++){
if(b.onBoat(new Position(pos.rowIndex()+1 + i, pos.colIndex()+ 1))){
System.out.println(new Position(pos.rowIndex()+1 + i, pos.colIndex() + 1));
throw(new BoatOverlappingException());
}
/*if(b.onBoat(new Position(pos.rowIndex()+1, pos.colIndex() + i + 1))){
System.out.println(new Position(pos.colIndex()+1, pos.rowIndex() + i + 1));
throw(new BoatOverlappingException());
}
*/
}
}
if(direction.equals("Horizontal")){
for(int i = 0; i<testBoat.size(); i++){
if(b.onBoat(new Position(pos.rowIndex()+1, pos.colIndex() + i + 1))){
System.out.println(new Position(pos.colIndex()+1, pos.rowIndex() + i + 1));
throw(new BoatOverlappingException());
}
/*if(b.onBoat(new Position(pos.colIndex()+1, pos.rowIndex() + i + 1))){
System.out.println(new Position(pos.colIndex()+1, pos.rowIndex() + i + 1));
throw(new BoatOverlappingException());
}
*/
}
}
}
//check for boats out of bounds
if(direction.equals("Vertical") && pos.rowIndex() + testBoat.size() >= 10){
throw(new BoatOutOfBoundsException());
} else if(direction.equals("Horizontal") && pos.colIndex() + testBoat.size() >= 10){
throw(new BoatOutOfBoundsException());
}
System.out.println("We Placed it");
boats.add(testBoat);
//throw(new Exception());
}
//loop through boats and use onBoat with pos on each boat, return boat method if true
public void shootAt(Position pos){
for(Boat b : boats){
b.hit(pos);
}
}
public boolean hit(Position pos){
for(Boat b : boats){
if(b.isHit(pos)){
return true;
}
}
return false;
}
public char boatInitial(Position pos){
for(Boat b : boats){
if(b.onBoat(pos)){
return b.abbreviation().toCharArray()[0];
}
}
return '-';
}
public Boat getBoat(Position pos){
for(Boat b : boats){
if(b.onBoat(pos)){
return b;
}
}
return null;
}
public String boatName(Position pos){
for(Boat b : boats){
if(b.onBoat(pos)){
return b.name();
}
}
return "-";
}
public boolean sunk(Position pos){
for(Boat b : boats){
if(b.onBoat(pos)){
return b.sunk();
}
}
return false;
}
public boolean allSunk(){
for(Boat b : boats){
if(!b.sunk()){
return false;
}
}
return true;
}
public void placeAllBoats(){
boolean didItPlace = false;
String orientation;
orientation = (Math.random()>.5) ? "Vertical" : "Horizontal";
String[] boats = {"Aircraft Carrier", "Battleship", "Cruiser", "Submarine", "Destroyer"};
for(int i = 0; i <5; i++){
didItPlace = false;
while(!didItPlace){
orientation = (Math.random()>.5) ? "Vertical" : "Horizontal";
try{
placeBoat(boats[i], orientation, new Position((int)(Math.random()*10 +1), (int)(Math.random()*10 +1)));
didItPlace = true;
} catch(BoatOutOfBoundsException b) {
System.out.println("we outa bounds");
} catch(BoatOverlappingException o) {
System.out.println("we overlappin");
}
}
}
}
public String toString(){
String out = "";
/*
for(Boat b : boats){
out += "name: " + b.name() + "\nabbreviation: " + b.abbreviation() + "\ndirection: " + b.direction() + "\nposition: " + b.position();
out += "\n\n";
}
*/
out += " 1 2 3 4 5 6 7 8 9 10\n";
for(char r = 'a'; r<='j'; r++){
out += Character.toUpperCase(r) + " ";
for(int c = 1; c<=10; c++){
out += this.boatInitial(PositionChecker.checkPosition(r + "-" + c )) + " ";
}
out += "\n";
}
return out;
}
}
| imacrazyguy412/Battleship | src/Ocean.java |
249,159 | import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int[][] sharks; // 상어의 정보 / [0]->생사여부, [1]->x, [2]->y, [3]->속력, [4]->이동방향, [5]->크기
static int dx[] = { 0, -1, 1, 0, 0 }; // 위 아래 오른쪽 왼쪽 순서, 0번째는 사용x
static int dy[] = { 0, 0, 0, 1, -1 };
static int[][] ocean; // 바다에 상어 저장
static int[][] tmpOcean; // 상어 움직일 때 임시로 만들어둔 바다
static int R, C, M;
static int sizeSum; // 답
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
R = Integer.parseInt(st.nextToken());
C = Integer.parseInt(st.nextToken());
M = Integer.parseInt(st.nextToken());
sharks = new int[M + 1][6];
ocean = new int[R][C];
sizeSum = 0;
for (int i = 1; i <= M; i++) { //상어 정보 입력, i가 상어의 고유 번호가 될 것임
st = new StringTokenizer(br.readLine());
sharks[i][0] = 1; //생사여부 처음은 1
sharks[i][1] = Integer.parseInt(st.nextToken()) - 1; //x인덱스 0부터 시작해서 -1 해줌
sharks[i][2] = Integer.parseInt(st.nextToken()) - 1; //y인덱스 0부터 시작해서 -1 해줌
sharks[i][3] = Integer.parseInt(st.nextToken());
sharks[i][4] = Integer.parseInt(st.nextToken());
sharks[i][5] = Integer.parseInt(st.nextToken());
}
for (int i = 1; i <= M; i++) {
ocean[sharks[i][1]][sharks[i][2]] = i;
}
///////////////////////////////////////////////////// 여기까지 초기화///////
// 실행
for (int i = 0; i < C; i++) { //낚시꾼이 0부터 C-1까지 이동
catchShark(i); //낚시 먼저
tmpOcean = new int[R][C]; // 상어 이동 겹치지 않도록 임시 저장할 바다 선어
for (int j = 1; j <= M; j++) { // sharks돌면서
if (sharks[j][0] == 1) // 살아있는 상어만 움직인다
moveShark(j);
}
for (int j = 1; j <= M; j++) { //다 움직인 후 살아있는 상어 찾아서 ocean에 저장해준다
if (sharks[j][0] == 1) {
ocean[sharks[j][1]][sharks[j][2]] = j;
}
}
}
System.out.println(sizeSum);
}
static void catchShark(int y) { //상어잡기
for (int i = 0; i < R; i++) {
if (ocean[i][y] != 0) { //바다가 0이 아닐 경우 상어임
int shark = ocean[i][y];
ocean[i][y] = 0; //상어 자리 0으로
sharks[shark][0] = 0; //상어 죽었다고 표시
sizeSum += sharks[shark][5]; //상어 무게 정답에 추가
break;
}
}
}
static void moveShark(int shark) { // 인자로 받는 shark는 상어의 고유 번호
int x = sharks[shark][1];
int y = sharks[shark][2];
int speed = sharks[shark][3];
int dir = sharks[shark][4];
ocean[x][y] = 0; //움직일거니까 현재 위치는 바다에서 지워준다
int length = (dir == 1 || dir == 2) ? R : C; //dir 이 1이나 2이면 위아래로 움직이므로 폭은 R이 될것, 3 4의 경우 폭은 C
int remain = speed % ((length - 1) * 2); //iter만큼 돌고 남은 만큼은 직접 움직여주어야 함
for (int i = 0; i < remain; i++) { //직접 이동
x += dx[dir];
y += dy[dir];
if (OOB(x, y)) {
dir = changeDir(dir);
x = x + dx[dir] * 2;
y = y + dy[dir] * 2;
}
}
// 상어 정보 업데이트
sharks[shark][1] = x;
sharks[shark][2] = y;
sharks[shark][4] = dir;
//임시 바다에 저장
if (tmpOcean[x][y] != 0) { //임시 바다에 이미 움직인 상어가 있으면
int anotherShark = tmpOcean[x][y];
eatShark(shark, anotherShark, x, y); //둘중 하나 먹어야 함
} else {
tmpOcean[x][y] = shark; //임시바다가 0인 경우는 상어 없으므로 상어 저장
}
}
static void eatShark(int shark1, int shark2, int x, int y) { //상어의 고유번호 2개 전달받고, 만난 위치도 전달받음
int shark1Size = sharks[shark1][5];
int shark2Size = sharks[shark2][5];
if (shark1Size > shark2Size) { //크기 비교 후 먹힐놈 선택
tmpOcean[x][y] = shark1; //임시 바다에 저장해주고
sharks[shark2][0] = 0; //먹힌 상어는 사망표시
} else {
tmpOcean[x][y] = shark2;
sharks[shark1][0] = 0;
}
}
static boolean OOB(int x, int y) { //바다 밖으로 나갔는지 판단하는 함수
if (x < 0 || y < 0 || x >= R || y >= C)
return true;
else
return false;
}
static int changeDir(int dir) { //반대 방향으로 바꿔주는 함수
if (dir == 1)
return 2;
else if (dir == 2)
return 1;
else if (dir == 3)
return 4;
else if (dir == 4)
return 3;
return 0;
}
} | BBSSJJ/BOJ | 17143.java |
249,163 | public class Ocean{
private int weight;
private int height;
public int getWeight() {
return this.weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public int getHeight() {
return this.height;
}
public void setHeight(int height) {
this.height = height;
}
public int oceanSize(){
return weight*height;
}
} | CodecoolGlobal/battle-ship-in-the-oo-way-java-battleship | Ocean.java |
249,166 | package utils;
import java.awt.Color;
/**
* Contains all our selected colors for various things.
*/
public class Colors {
public static Color OCEAN = new Color(117,196,247);
public static Color HIGHWAY = new Color(230,94,49);
public static Color LARGE_ROAD = new Color(217,209,0);
public static Color SMALL_ROAD = new Color(119,215,81);
public static Color ROUTE = new Color(123,116,163);
public static Color PATH = new Color(144,238,144);
} | itu-bswu/KF04 | utils/Colors.java |
249,168 | import java.util.ArrayList;
import java.util.List;
public class OceanGrid extends Grid{
private List<String> sunkShips = new ArrayList<String>();
public OceanGrid(){
super();
}
@Override
public void printGrid(){
System.out.println("Ocean Grid:");
String rowName = "";
printDivider();
printHeader();
printDivider();
for(int row = 0; row < 10 ; row++){
switch(row){
case 0 :
rowName = "| A |";
break;
case 1 :
rowName = "| B |";
break;
case 2 :
rowName = "| C |";
break;
case 3 :
rowName = "| D |";
break;
case 4 :
rowName = "| E |";
break;
case 5 :
rowName = "| F |";
break;
case 6 :
rowName = "| G |";
break;
case 7 :
rowName = "| H |";
break;
case 8 :
rowName = "| I |";
break;
case 9 :
rowName = "| J |";
break;
}
System.out.print(rowName);
for(int column = 0; column < 10; column++){
if(cells[row][column].getState() == CellState.OCCUPIED){
System.out.print(" S |");
}else if(cells[row][column].getState() == CellState.HIT){
System.out.print(" X |");
}else if(cells[row][column].getState() == CellState.MISS){
System.out.print(" O |");
}else{
System.out.print(" |");
}
}
System.out.println();
printDivider();
}
}
public ShotResult receiveShot(Shot shot) {
Cell cell = getCell(shot);
//get corrdinates from shot row/column
CellState cs = getCellState(shot);
//make descion
if(cs == CellState.EMPTY){
setCellState(shot, CellState.MISS);
return ShotResult.MISS;
}else{
Ship ship = cell.getShip();
ship.registerHit();
cell.setState(CellState.HIT);
if(ship.isSunk() == true){
sunkShips.add(ship.getName());
return ShotResult.SUNK;
} else{
return ShotResult.HIT;
}
}
}
protected void setShipCells(Ship ship){
for (Coordinate coordinate : ship.coordinates) {
setCellState(coordinate, CellState.OCCUPIED);
Cell cell = getCell(coordinate);
cell.setShip(ship);
}
}
public List<String> getSunkShips(){
return sunkShips;
}
}
| seank8/TeamBattleShip | src/OceanGrid.Java |
249,169 | import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.Timer;
import java.awt.event.KeyEvent;
//Checklist/Goals for game;
/*
*Amoeba that gets bigger as it eats smaller amoebas
*dies if it touches/ tries to eat a bigger amoeba
*computer amoebas floating across screen, all edible
*amoeba grows as it eats more
*computer amoebas spawn automatically
*collision detection so we kno if amoebas intersect or not (for eating)
*different speed and sized amoebas
*
*
*plan for spawning
*spawn all at once, but have most of them not moving till later
*
*
*what i learned, or at least think i learned
* super.paint(g): erases previous painting??
*/
/////////////////////////////////////////////////////////
/*
* This Ocean class is where the most of the game computations take place. I named it Ocean because it's like the game
* takes place in this class.
*/
public class Ocean extends JPanel implements ActionListener {
private static Timer timer;
private Player player; //the human controlled amoeba
private OtherCreaturesInThePond[] otherCreatures; //an array of Objects that are the computer amoebas
private int population = 1500;
private int ttt = 0; //add one each time timer fires...for actions slower than original timer speed
private int spawnCount=0; // this is here because the whole array of computer amoebas is created at once, but I dont want them all to start moving onto the screen at once..
private static int stage = 1; // stage 1 intro; stage 2 and 3 instructions; stage 4 game; stage 5 game over
private boolean endcry = false; // if true prints "NOO" onto the screen, happens when the amoeba gets eaten
private int eatCount = 0; //count of how many amoebas the player has eaten
private int finalSize = 1;
Double rand = Math.random(); // this is to display a different Game Over message each time
//////////////THE CONSTRUCTOR///////////////
public Ocean(){
addKeyListener(new TAdapter()); //the key Listener was put in its own private class
setFocusable(true); //pretty sure this makes it so the computer "sees" the keyboard input, because without it, there's no movement.
setBackground(Color.cyan);
setDoubleBuffered(true);
player = new Player();
otherCreatures = new OtherCreaturesInThePond[population];
timer = new Timer(4, this); //timer fires every 8 milliseconds, 8/1000 sec
spawnAllCreatures();
//timer.start();
repaint();
}
public static void stagePlusOne(){ // this happens when SPACE is pressed
//these stages are the intro and tutorial
if(stage == 1 ||stage == 2||stage == 3){
stage++;
}
//stage 4 is when the game is playing
if(stage == 4){
timer.start();
}
//this is the game over
if(stage == 5){
stage = 1;
timer.stop();
}
}
private int yo = 1; //for the "nooo" at end of game
//////////////PAINTING////////////////////
public void paint(Graphics g){
if(stage == 1){ // intro
player.revive();
super.paint(g);
eatCount = 0; // why is this in paint method?
setBackground(Color.magenta);
Font introFontBig = new Font("Impact" , Font.BOLD, 70);
Font introFontSmall = new Font("Arial" , Font.BOLD, 20);
g.setFont(introFontBig);
g.setColor(Color.green);
g.drawString("Square Amoeba 2013", 150, 300);
g.setColor(Color.black);
g.setFont(introFontSmall);
g.drawString("Welcome To", 400, 210);
g.drawString("by Ethan Lo", 700,350);
g.drawString("--press space to continue--", 330, 420);
repaint();
//System.out.println("1");
}
if(stage == 2){ //tutorial
super.paint(g);
setBackground(Color.cyan);
Font tutFont = new Font("Arial", Font.PLAIN, 20);
g.setFont(tutFont);
g.drawString("This is you", 240, 120);
g.setColor(Color.white);
g.fillRect(250, 150, 80, 80);
g.setColor(Color.yellow); // make an egg amoeba :O
g.fillOval(250+20, 150+20, 40, 40);
g.setColor(Color.black);
g.drawString("Your goal in life is to become the biggest amoeba in the pond", 190, 320);
g.drawString("--press space to continue--", 340, 520);
repaint();
//System.out.println("2");
}
if(stage == 3){
super.paint(g);
Font tutFont = new Font("Arial", Font.PLAIN, 20);
g.setFont(tutFont);
g.drawString("These are your friends", 250, 120);
g.setColor(Color.green);
g.fillRect(250, 150, 40, 40);
g.fillRect(300, 170, 30, 30);
g.fillRect(230, 180, 50, 50);
g.setColor(Color.YELLOW);
g.fillOval(250+10, 150+10, 20, 20);
g.fillOval(300+(30/4), 170+(30/4),10, 10);
g.fillOval(230+(50/4), 180+(50/4), 25, 25);
g.setColor(Color.black);
g.drawString("You get bigger when you eat on of them", 250, 280);
g.drawString("But beware, a bigger amoeba always eats a smaller amoeba!", 200, 350);
g.drawString("This is the end of the tutorial", 250, 420);
g.drawString("--press space to PLAY--", 340, 520);
repaint();
//System.out.println("3");
}
if(stage == 4){// game
//System.out.println("4");
super.paint(g);
setBackground(Color.cyan);
if(player.getAlive() == true){
drawPlayer(g);
}
drawOthers(g);
g.setColor(Color.black);
g.drawString("Aboebas eaten: " + eatCount, 870, 550);
g.drawString("Size : " + player.getSide()*player.getSide(), 870, 535);
if(player.getSide() > 250){
g.setColor(Color.black);
g.drawString("Congrats, you are now the biggest amoeba in the pond", 300, 550);
}
}
if(stage == 6){
Font NOOOO = new Font("Arial", Font.BOLD, 120);
g.setFont(NOOOO);
g.drawString("NOOOOOOO", 200, 280);
yo ++;
if(yo == 5){
try {
Thread.sleep(200);
} catch (InterruptedException ie) {
//Handle exception
}
stage = 5;
repaint();
}
}
if(stage == 5){//game over!!!
yo = 1;
super.paint(g);
timer.start();
if(ttt == 1000){
ttt = -350;
}
Font endFontBig = new Font("Impact" , Font.BOLD, 100);
Font endFontSmall = new Font("Arial", Font.PLAIN, 25);
Font endFontMed = new Font("Arial", Font.BOLD, 30);
g.setFont(endFontBig);
g.drawString("GAME OVER" , ttt, 250);
g.setFont(endFontSmall);
if(rand <.3){
g.drawString("Looks like you got eaten!!", 350, 350);
}
else if(rand > .6){
g.drawString("It's an amoeba eat amoeba world out there man", 350, 350);
}
else if(rand < .6 && rand > .5){
g.drawString("There are always bigger amoebaa in the pond", 350, 350);
}
else{
g.drawString("Looks like you bit off more than you could swallow!", 350, 350);
}
g.drawString("FINAL SCORE",400, 400);
g.drawString("--press space to restart--", 340, 520);
g.setColor(Color.blue);
g.setFont(endFontMed);
g.drawString("Aboebas eaten: " + eatCount, 250, 450);
g.drawString("Size : " + finalSize, 540, 450);
repaint();
g.dispose();
judgementDay();
// System.out.println("5");
}
Toolkit.getDefaultToolkit().sync(); // Someone said this makes the game smoother..I don't know what it does, seems to make no differnece?
g.dispose();//I think this saves memory, but I'm not sure.
}
public void drawPlayer(Graphics g){
g.setColor(Color.white);
g.fillRect(player.getX(), player.getY(), player.getSide(), player.getSide());
g.setColor(Color.yellow); // make an egg amoeba
g.fillOval(player.getX()+(player.getSide()/4), player.getY()+(player.getSide()/4), player.getSide()/2, player.getSide()/2);
}
public void drawOthers(Graphics g){
for(int x = 0; x<population; x++){
g.setColor(Color.green);
g.fillRect(otherCreatures[x].getX(),otherCreatures[x].getY(), otherCreatures[x].getSide(), otherCreatures[x].getSide());
g.setColor(Color.YELLOW);
g.fillOval(otherCreatures[x].getX()+(otherCreatures[x].getSide()/4), otherCreatures[x].getY()+(otherCreatures[x].getSide()/4), otherCreatures[x].getSide()/2,otherCreatures[x].getSide()/2);
}
}
///////////////////COMPUTER AMOEBA METHODS//////////////
public void spawnAllCreatures(){
//this fills the whole array with Amoebas
for(int x = 0; x<population; x++){
otherCreatures[x] = new OtherCreaturesInThePond();
}
}
public void actionPerformed(ActionEvent e){ // for timer
// System.out.println(player.getSide());
if(player.getAlive() == true){
checkBounds();
checkCollision();
player.move();
}
for(int x = 0; x<spawnCount; x= x+4){ // all the cells are "alive" but only the ones that are under the spawnCount are able to move
otherCreatures[x].move();
otherCreatures[x+1].move();
otherCreatures[x+2].move();
otherCreatures[x+3].move();
// we spawn 4 at a time
}
repaint();
spawnIncrease();
ttt++;
}
public void spawnIncrease(){
//I dont want to spawn everytime the timer fires, so i use ttt, a variable that increases with the timer count
if ((ttt*8)%100 == 0){ // which means every .1 second
spawnCount++;
}
}
///////////////////COLLISIONS and EATING/////////////////////////////
boolean firstContact = true; // you dont want to keep eating every pixel you move
public void checkCollision(){
Rectangle p = new Rectangle(player.getX(), player.getY(), player.getSide(), player.getSide()); //one bounding rectangle for the player
// make a new rectangle and check for each computer amoeba
for(int x = 0; x < population ; x++){
Rectangle c = new Rectangle(otherCreatures[x].getX(), otherCreatures[x].getY(), otherCreatures[x].getSide(), otherCreatures[x].getSide());
if (p.intersects(c)&& firstContact == true && player.getAlive() == true){
firstContact = false;
if(player.getSide()>=otherCreatures[x].getSide()){
iEat(x);
otherCreatures[x].kill();
}
if(player.getSide()<otherCreatures[x].getSide()){
finalSize= player.getSide()*player.getSide();
repaint();
player.kill();
stage = 6;
ttt = 0;
rand = Math.random();
}
}
firstContact = true;
}
}
public void iEat(int x){
eatCount++;
int newSize = 1;
newSize = (int)Math.sqrt((((player.getSide())*(player.getSide()))+((otherCreatures[x].getSide())*(otherCreatures[x].getSide()))));
player.setSide(newSize);
//this method makes it so that when u eat, ur not just adding the sides, ur actually adding the actual area.
}
public void checkBounds(){
if(player.getX()<0 && player.getDirection().equals("A")){
player.setDX(0);
}
if(player.getX()>993-player.getSide() && player.getDirection().equals("D")){
player.setDX(0);
}
if(player.getY()<0 && player.getDirection().equals("W")){
player.setDY(0);
}
if(player.getY()>572-player.getSide() && player.getDirection().equals("S")){
player.setDY(0);
}
if(player.getX()<-1){ // prevents the two key pressed --> escape bounds glitch
player.setX(0);
}
if(player.getX()>994-player.getSide()){
player.setX(992-player.getSide());
}
if(player.getY()<0){
player.setY(0);
}
if(player.getY()>573-player.getSide()){
player.setY(572-player.getSide());
}
}
private class TAdapter extends KeyAdapter { /// for keys
public void keyReleased(KeyEvent e){
player.keyReleased(e);
}
public void keyPressed(KeyEvent e){
player.keyPressed(e);
}
}
public void judgementDay(){// kills and restarts all amoebas
spawnCount = 0;
player = null;
for(int x = 0; x<population; x++){
otherCreatures[x] = null;
player = new Player();
for(x = 0; x<population; x++){
otherCreatures[x] = new OtherCreaturesInThePond();
}
}
}
}
| ethan9452/Amoeba_Game | src/Ocean.java |
249,170 | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3) braces deadcode
package MCP.mod_finiteliquids;
import java.util.Random;
import net.minecraft.src.*;
// Referenced classes of package net.minecraft.src:
// Block, Material, World, mod_NWater,
// EntityPlayer, Entity
public class NBlockSponge extends Block
{
protected NBlockSponge(int i)
{
super(i, Material.sponge);
blockIndexInTexture = 48;
setTickOnLoad(true);
setHardness(0.6F);
setStepSound(Block.soundGrassFootstep);
setBlockName("sponge");
}
@Override
public int tickRate()
{
return 200;
}
@Override
public void onNeighborBlockChange(World world, int i, int j, int k, int l)
{
if(world.getBlockMetadata(i, j, k) > 0)
{
world.scheduleBlockUpdate(i, j, k, blockID, tickRate());
}
}
@Override
public void updateTick(World world, int i, int j, int k, Random random)
{
int l = world.getBlockMetadata(i, j, k);
if((l > 0) & (!borderOcean(world, i, j, k)))
{
l--;
world.setBlockMetadataWithNotify(i, j, k, l);
if(l > 0)
{
world.scheduleBlockUpdate(i, j, k, blockID, tickRate());
}
}
}
public boolean borderOcean(World world, int i, int j, int k)
{
if(world.getBlockId(i + 1, j, k) == mod_NWater.nwater_ocean.blockID)
{
return true;
}
if(world.getBlockId(i - 1, j, k) == mod_NWater.nwater_ocean.blockID)
{
return true;
}
if(world.getBlockId(i, j, k + 1) == mod_NWater.nwater_ocean.blockID)
{
return true;
}
if(world.getBlockId(i, j, k - 1) == mod_NWater.nwater_ocean.blockID)
{
return true;
}
return world.getBlockId(i, j + 1, k) == mod_NWater.nwater_ocean.blockID;
}
@Override
public int getBlockTextureFromSideAndMetadata(int i, int j)
{
if(j > 14)
{
return mod_NWater.texx[16];
}
if(j > 0)
{
return mod_NWater.texx[15];
} else
{
return blockIndexInTexture;
}
}
@Override
protected int damageDropped(int i)
{
return i;
}
public static int func_21034_c(int i)
{
return ~i & 0xf;
}
public static int func_21035_d(int i)
{
return ~i & 0xf;
}
@Override
public void onEntityCollidedWithBlock(World world, int i, int j, int k, Entity entity)
{
if(world.multiplayerWorld)
{
return;
} else
{
return;
}
}
@Override
public boolean blockActivated(World world, int i, int j, int k, EntityPlayer entityplayer)
{
int l = world.getBlockMetadata(i, j, k);
if(l == 0)
{
return false;
}
Random random = new Random();
if(random.nextInt(4) == 0)
{
l--;
world.setBlockMetadata(i, j, k, l);
}
boolean flag = false;
if((!flag) & (world.getBlockId(i, j - 1, k) == 0))
{
world.setBlockAndMetadataWithNotify(i, j - 1, k, mod_NWater.nwater.blockID, 2);
flag = true;
}
if((!flag) & (world.getBlockId(i - 1, j, k) == 0))
{
world.setBlockAndMetadataWithNotify(i - 1, j, k, mod_NWater.nwater.blockID, 2);
flag = true;
}
if((!flag) & (world.getBlockId(i + 1, j, k) == 0))
{
world.setBlockAndMetadataWithNotify(i + 1, j, k, mod_NWater.nwater.blockID, 2);
flag = true;
}
if((!flag) & (world.getBlockId(i, j, k - 1) == 0))
{
world.setBlockAndMetadataWithNotify(i, j, k - 1, mod_NWater.nwater.blockID, 2);
flag = true;
}
if((!flag) & (world.getBlockId(i, j, k + 1) == 0))
{
world.setBlockAndMetadataWithNotify(i, j, k + 1, mod_NWater.nwater.blockID, 2);
flag = true;
}
if((!flag) & (world.getBlockId(i, j + 1, k) == 0))
{
world.setBlockAndMetadataWithNotify(i, j + 1, k, mod_NWater.nwater.blockID, 2);
flag = true;
}
return flag;
}
}
| N3X15/FiniteLiquids | NBlockSponge.java |
249,174 | import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
public class Ocean extends Tile
{
int clock = 0;
boolean costume0 = true;
public void act()
{
clock++;
if (clock==25) {
clock = 0;
toggleCostume();
}
}
private void toggleCostume() {
if (costume0) {
setImage("ocean-1.png");
} else {
setImage("ocean-0.png");
}
costume0 = !costume0;
}
public boolean isCollidable() {
return false;
}
}
| ariesninjadev/ElementalEscapade | Ocean.java |
249,175 | import java.util.Random;
//Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?
public class Problem8 {
public String theString = "7316717653133062491922511967442657474235534919493496983520312774506326239578318016984801869478851843858615607891129494954595017379583319528532088055111254069874715852386305071569329096329522744304355766896648950445244523161731856403098711121722383113622298934233803081353362766142828064444866452387493035890729629049156044077239071381051585930796086670172427121883998797908792274921901699720888093776657273330010533678812202354218097512545405947522435258490771167055601360483958644670632441572215539753697817977846174064955149290862569321978468622482839722413756570560574902614079729686524145351004748216637048440319989000889524345065854122758866688116427171479924442928230863465674813919123162824586178664583591245665294765456828489128831426076900422421902267105562632111110937054421750694165896040807198403850962455444362981230987879927244284909188845801561660979191338754992005240636899125607176060588611646710940507754100225698315520005593572972571636269561882670428252483600823257530420752963450";
public Problem8() {
}
public static String stringGen(int n) { //For any size string, string generator
String[] strGen = new String[n];
for(int i = 0; i < n; i++) {
strGen[i] = (Integer.toString(randInt(0,9)));
}
StringBuilder builder = new StringBuilder();
for(String s : strGen) {
builder.append(s);
}
return builder.toString();
}
public static int randInt(int min, int max) {
Random rand = new Random();
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}
public static int oceansThirteen(String str) {
//Read the String
//Changing starting position everytime at an increment of 1. So basically, read it and 12 ahead
//Can be done using nested loop
//Next store this value in a separate array
//Compare the values in the array and see which is the biggest, WOO!
return 0;
}
public static void main(String[] args) {
//System.out.println(stringGen(1000));
System.out.println();
}
}
| ggrizzly/ProjectEuler | Problem8.java |
249,176 | package com.dansd.FilterPImage;
import processing.core.*;
public class FilterPImage extends PImage {
private static final int HUE = 122;
private static final int SATURATION = 123;
private static final int BRIGHTNESS = 124;
public FilterPImage(PApplet applet, String imgPath){
super();
PImage img = applet.loadImage(imgPath);
this.width = img.width;
this.height = img.height;
this.parent = applet;
img.loadPixels();
this.pixels = img.pixels;
this.updatePixels();
}
protected FilterPImage(int width, int height) {
super(width, height);
}
protected FilterPImage(int width, int height, int format) {
super(width, height, format);
}
protected FilterPImage() {
super();
}
public void saturate(float factor){
this.modifyHSB(SATURATION, factor);
}
public void hue(float factor){
this.modifyHSB(HUE, factor);
}
public void brightness(float factor){
this.modifyHSB(BRIGHTNESS, factor);
}
private void modifyHSB(int mode, float factor) {
this.parent.colorMode(HSB);
this.loadPixels();
for(int i=0; i<this.pixels.length; i++){
int thisColor = parent.color(pixels[i]);
int newColor;
switch(mode){
case HUE:
newColor = parent.color(parent.hue(thisColor) * factor, parent.saturation(thisColor) , parent.brightness(thisColor));
break;
case SATURATION:
newColor = parent.color(parent.hue(thisColor), parent.saturation(thisColor) * factor , parent.brightness(thisColor));
break;
case BRIGHTNESS:
newColor = parent.color(parent.hue(thisColor), parent.saturation(thisColor) , parent.brightness(thisColor)*factor);
break;
default:
newColor = thisColor;
}
pixels[i] = newColor;
}
this.updatePixels();
this.parent.colorMode(RGB);
}
public void makeItMoreYellow() {
this.loadPixels();
for(int i=0; i<this.pixels.length; i++){
int thisColor = parent.color(pixels[i]);
int newColor = parent.color(parent.red(thisColor) * 1.5f, parent.green(thisColor) * 1.5f, parent.blue(thisColor));
pixels[i] = newColor;
}
this.updatePixels();
}
public void smurfify(){
this.loadPixels();
for(int i=0; i<this.pixels.length; i++){
int thisColor = parent.color(pixels[i]);
parent.colorMode(HSB);
pixels[i] = parent.color(150, parent.saturation(thisColor), parent.brightness(thisColor));
parent.colorMode(RGB);
}
this.updatePixels();
}
public void contrast(double value){
this.loadPixels();
double contrast = Math.pow((100 + value) / 100, 2);
for(int i=0; i<this.pixels.length; i++){
int R = (int )parent.red(pixels[i]);
int newr = (int)(((((R / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
int G = (int )parent.green(pixels[i]);
int newg = (int)(((((G / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
int B = (int )parent.blue(pixels[i]);
int newb = (int)(((((B / 255.0) - 0.5) * contrast) + 0.5) * 255.0);
pixels[i] = parent.color(newr, newg, newb);
}
this.updatePixels();
}
public void sepia(int depth){
this.loadPixels();
for(int i=0; i<this.pixels.length; i++){
int thisColor = parent.color(pixels[i]);
int grey = (int) ((parent.red(thisColor)+parent.green(thisColor)+parent.blue(thisColor))/3);
pixels[i] = parent.color(grey +depth*2 , parent.green(thisColor)+depth, parent.blue(thisColor)-depth);
}
this.updatePixels();
}
public void trainspotting(){
this.tint(255,127,0);
this.contrast(20);
}
public void ocean(){
this.tint(0,0,80);
this.saturate(0.5f);
}
// tint() at the moment doesn't really tint it (i.e. applies a translucent layer over the image),
// but averages each pixel in the image with the specified colour
public void tint(int r, int g, int b){
this.loadPixels();
for(int i=0; i<this.pixels.length; i++){
int thisColor = parent.color(pixels[i]);
int tintColor = parent.color(r,g,b);
int newColor = parent.color(
(parent.red(thisColor)+parent.red(tintColor))/2,
(parent.green(thisColor)+parent.green(tintColor))/2,
(parent.blue(thisColor)+parent.blue(tintColor))/2
);
pixels[i] = newColor;
}
this.updatePixels();
}
public void setFilterByName(int filterName){
switch(filterName){
case FilterPImage.THRES: this.filter(THRESHOLD);
case FilterPImage.MORE_YELLOW: this.makeItMoreYellow();
case FilterPImage.SMURFIFY: this.smurfify();
case FilterPImage.SATURATE: this.saturate(0.1f);
case FilterPImage.CONTRAST: this.contrast(50);
case FilterPImage.SEPIA: this.sepia(20);
case FilterPImage.INV: this.filter(INVERT);
case FilterPImage.TRAINSPOTTING: this.trainspotting();
case FilterPImage.OCEAN: this.ocean();
}
}
private static final int THRES = 12345;
private static final int MORE_YELLOW = 12346;
private static final int SMURFIFY = 12347;
private static final int SATURATE = 12348;
private static final int CONTRAST = 12349;
private static final int TRAINSPOTTING = 12350;
private static final int SEPIA = 12351;
private static final int INV = 12352;
private static final int OCEAN = 12353;
public static final int[] filters = {THRES,MORE_YELLOW,SMURFIFY,SATURATE,CONTRAST,SEPIA,INV,TRAINSPOTTING,OCEAN};
}
| fdansv/FilterPImage | FilterPImage.java |
249,178 | class Hypocean extends Pokemon{
public Hypocean(){
super(117,"Hypocean",Type.EAU,Type.SANS,55,65,95,85);
}
public Hypocean(String nom){
super(117,nom,Type.EAU,Type.SANS,55,65,95,85);
}
public String getEspece() {
return "Hypocean";
}
public int getNumero() {
return 117;
}
}
| louisprvst/Echec-Pokemon | Code/Hypocean.java |
249,179 | I just have to unlaod this so I quit thinking about it.
Have a single PoolManager that contains all ObjectPools.
A class that we wish to pool has New() functions which ask the global PoolManager service to give it one of (whatever.class).
If the pool manager doesn't have a pool fot htat class it makes one.
class ObjectPool extends Vector(){
Object nextFree(){
return remove(last());
}
release(object obj){
obj.onRelease();
add(obj);
}
}
class PoolManager {
static hashTable ocean;
static ObjectPool getpool(Class classofObjectDesired){
ObjectPool pool= ocean.get(classofObjectDesired.hashcode());
if(pool==null){
pool = new ObjectPool(); //probably just a vector.
ocean.put(classofObjectDesired.hashcode(),pool);
}
return pool;
}
static Object getMeOne(Class classofObjectDesired){
ObjectPool pool= ocean.getpool(classofObjectDesired.hashcode());
Object obj=pool.nextFree();
if(obj==null){
//here we can deal with detecting a run-away allocaiton.
obj=classofObjectDesired.Make(); //each poolable class must have a public Object static Make() function.
}
obj.onAcquired(); // a convenience, jhave a funcoitn that is called when object removed from pool
return obj;
}
static void released(Object released){
ObjectPool pool= ocean.getpool(release.getClass().hashcode());
pool.released(released);
}
}
========
interface isPoolable
onRelease()
onAcquired()
Andy.
512-791-3529
| 980f/java | OBJPOOL.JAV |
249,181 | import java.io.*;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class OceanAnti11 {
public static void main(String[] args) {
Kattio io = new Kattio(System.in, System.out);
ArrayList<Integer> arr = new ArrayList<>();
arr.add(0);
arr.add(2);
arr.add(3);
int cases = io.getInt();
for (int i = 0; i < cases; i++) {
int num = io.getInt();
if (arr.size()-1 < num) {
for (int j = arr.size()-1; j < num; j++) {
arr.add((arr.get(j-1) + arr.get(j)) % 1000000007);
}
}
io.println(arr.get(num));
}
io.close();
}
static class Kattio extends PrintWriter {
public Kattio(InputStream i) {
super(new BufferedOutputStream(System.out));
r = new BufferedReader(new InputStreamReader(i));
}
public Kattio(InputStream i, OutputStream o) {
super(new BufferedOutputStream(o));
r = new BufferedReader(new InputStreamReader(i));
}
public boolean hasMoreTokens() {
return peekToken() != null;
}
public int getInt() {
return Integer.parseInt(nextToken());
}
public double getDouble() {
return Double.parseDouble(nextToken());
}
public long getLong() {
return Long.parseLong(nextToken());
}
public String getWord() {
return nextToken();
}
private BufferedReader r;
private String line;
private StringTokenizer st;
private String token;
private String peekToken() {
if (token == null)
try {
while (st == null || !st.hasMoreTokens()) {
line = r.readLine();
if (line == null) return null;
st = new StringTokenizer(line);
}
token = st.nextToken();
} catch (IOException e) {
}
return token;
}
private String nextToken() {
String ans = peekToken();
token = null;
return ans;
}
}
}
| kennidenni/OpenKattis | OceanAnti11.java |
249,182 | public class Player {
private Ocean playerOcean;
private Fleet playerFleet;
private String playerName;
private boolean lost;
public Player(String playerName, Ocean playerOcean, Fleet playerFleet){
this.playerName = playerName;
this.playerOcean = playerOcean;
this.playerFleet = playerFleet;
this.lost = false;
}
public void shotAtLocation(int x, int y, Player opponent){
opponent.recieveHit(x, y);
}
public void recieveHit(int x, int y){
if(playerFleet.tryToHitLocation(x, y)){
this.updateState();
} else {playerOcean.markSquare(x, y);}
}
public void showBoard(Player opponent){
Display.showPlayerName(this.playerName, opponent.getName());
Display.showBoards(this.playerOcean, opponent.getOcean ());
}
private void updateState(){
this.lost = this.playerFleet.isDestroyed;
}
public boolean checkIfLost(){
return this.lost;
}
public Ocean getOcean(){
return this.playerOcean;
}
public String getName(){
return this.playerName;
}
} | DavidCichy/battleshipsJava | Player.java |
249,183 | // Assignment 9
// Yusuf Hasanat
// yusufh
// Cheng Jessica
// jcheng
import java.awt.Color;
import javalib.worldimages.OutlineMode;
import javalib.worldimages.RectangleImage;
import javalib.worldimages.WorldImage;
// Represents a single square of the game area
class Cell {
// represents absolute height of this cell, in feet
double height;
// In logical coordinates, with the origin at the top-left corner of the screen
int x;
int y;
// the four adjacent cells to this one
Cell left;
Cell top;
Cell right;
Cell bottom;
// reports whether this cell is flooded or not
boolean isFlooded;
Cell(double height, int x, int y) {
this.height = height;
this.x = x;
this.y = y;
this.isFlooded = false;
}
// draws a cell depending on water height
WorldImage drawCell(int waterHeight) {
double ratio = Math.abs((int) (this.height - waterHeight) * 5);
Color c;
if (this.isFlooded) {
c = new Color(0, 0, (int) Math.min(255, 255 - ratio));
}
else if (this.height <= waterHeight) {
c = new Color((int) Math.max(200, Math.abs(255 - ratio)),
(int) Math.min(200, Math.abs(200 - waterHeight)),
(int) Math.min(50, Math.abs(255 - waterHeight)));
}
else {
c = new Color((int) Math.min(255, ratio), (int) Math.min(255, 100 + ratio),
(int) Math.min(255, ratio));
}
return new RectangleImage(10, 10, OutlineMode.SOLID, c);
}
// determines if this cell is a coast cell
boolean isCoastCell() {
return this.left.isFlooded || this.right.isFlooded || this.top.isFlooded
|| this.bottom.isFlooded && !this.isFlooded;
}
// floods the cell
void flood(int waterHeight) {
if (this.height <= waterHeight && (this.top.isFlooded || this.bottom.isFlooded
|| this.left.isFlooded || this.right.isFlooded)) {
this.isFlooded = true;
}
}
// determines if the cell is touching the player
boolean isTouching(Player p) {
return this.x == p.x && this.y == p.y;
}
// determines if the cell is touching player2
boolean isTouching2(Player2 p) {
return this.x == p.x && this.y == p.y;
}
}
// Represents an Ocean cell
class OceanCell extends Cell {
OceanCell(double height, int x, int y) {
super(height, x, y);
this.height = 0.0;
this.isFlooded = true;
}
// draws the Ocean cell
WorldImage drawCell(int waterHeight) {
return new RectangleImage(10, 10, OutlineMode.SOLID, Color.BLUE);
}
} | jessica-cheng/ForbiddenIsland | Cell.java |
249,184 | package ocean;
public class Fish {
}
| Ablesius/java-exercises | src/ocean/Fish.java |
249,185 | import javax.swing.JPanel;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Random;
import java.awt.Color;
import java.awt.Toolkit;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.util.Iterator;
import java.awt.Font;
import javax.swing.JLabel;
import java.awt.Dimension;
import javax.swing.JButton;
public class Ocean extends JPanel implements Runnable{
public static TopPanel north;
private Image img;
private final static String BACKGROUND = "../images/background.png";
private Diver diver;
private Thread diverThread;
private EnergyTimer energyTimer;
private Thread energyTimerThread;
private Meter meter;
private Thread meterThread;
private ArrayList<Enemy> enemies;
private ArrayList<String> listOfKeys;
private HashMap<String, Integer> listOfWords;
private ArrayList<String> listOfKeys_3Letters;
private HashMap<String, Integer> listOfWords_3Letters;
private Boss boss;
private JButton back;
public Ocean(JButton back){
this.setBackground(Color.BLACK);
this.setLayout(null);
this.loadImage(Ocean.BACKGROUND);
this.loadWordsFile("words.txt");
this.enemies = new ArrayList<Enemy>();
this.back = back;
this.add(this.back);
}
public void resetOcean(){
this.meter = null;
this.boss = null;
this.diver = null;
this.energyTimer = null;
Ocean.north = null;
this.getListOfEnemies().clear();
}
public synchronized ArrayList<Enemy> getListOfEnemies(){
return this.enemies;
}
public EnergyTimer getEnergyTimer(){
return this.energyTimer;
}
private void loadWordsFile(String filename){
this.listOfWords = new HashMap<String, Integer>();
try{
String[] tokens;
String line;
BufferedReader reader = new BufferedReader(new FileReader(filename));
while((line = reader.readLine()) != null){
tokens = line.split(" ");
listOfWords.put(tokens[0], Integer.parseInt(tokens[1]));
}
this.listOfKeys = new ArrayList<String>(listOfWords.keySet());
} catch(Exception e){ e.getMessage(); }
this.listOfWords_3Letters = new HashMap<String, Integer>();
try{
String[] tokens;
String line;
BufferedReader reader = new BufferedReader(new FileReader("words_3_letter.txt"));
while((line = reader.readLine()) != null){
tokens = line.split(" ");
listOfWords_3Letters.put(tokens[0], Integer.parseInt(tokens[1]));
}
this.listOfKeys_3Letters = new ArrayList<String>(listOfWords_3Letters.keySet());
} catch(Exception e){ e.getMessage(); }
}
public synchronized void checkXPos(){ // checks the xPos of all the enemies
Fish fish;
Missile missile;
Jellyfish jellyfish;
Shark shark;
ArrayList<Enemy> toRemove = new ArrayList<Enemy>();
for(Enemy enemy : this.getListOfEnemies()){
if(enemy instanceof Jellyfish){
jellyfish = (Jellyfish) enemy;
if(jellyfish.getYPos() + Jellyfish.LENGTH <= 0){
jellyfish.setIsAlive(false); // fish is already not alive
toRemove.add(enemy); // if it is at the top of the frame, add it to the toRemove arraylist (this is to avoid concurrent modification exception)
if(jellyfish.getWord().startsWith(GameFrame.currentWord)) GameFrame.currentWord = "";
}
}
else if(enemy instanceof Shark){
shark = (Shark) enemy;
if(shark.getXPos() + Shark.WIDTH <= 0){
shark.setIsAlive(false);
this.diver.decLives();
toRemove.add(enemy);
if(shark.getWord().startsWith(GameFrame.currentWord)) GameFrame.currentWord = "";
}
}
else if(enemy instanceof Fish){
fish = (Fish) enemy;
if(fish.getXPos() + Fish.WIDTH <= 0){
fish.setIsAlive(false);
this.diver.decLives();
toRemove.add(enemy);
if(fish.getWord().startsWith(GameFrame.currentWord)) GameFrame.currentWord = "";
}
}
else if(enemy instanceof Missile){
missile = (Missile) enemy;
if(missile.getXPos() + Missile.WIDTH <= 0){
missile.setIsTyped(true);
this.diver.decLives(); // decrement the life of the diver once it passed through the diver
toRemove.add(enemy);
if(missile.getWord().startsWith(GameFrame.currentWord)) GameFrame.currentWord = "";
}
else if(missile.getXPos() + Missile.WIDTH >= this.boss.getXPos() && missile.getIsTyped() == true){
toRemove.add(enemy);
}
}
}
Ocean.north.repaint(); // make sure to update
this.getListOfEnemies().removeAll(toRemove); // remove all the enemies that passed through the borders
}
public synchronized void checkWordsTyped(char e){ // GameFrame.currentWord is a shared resource
Shark shark;
Fish fish;
Missile missile;
DisplayScore appear;
Thread appearThread;
String keyPress = Character.toString(e).toUpperCase();
for(Iterator<Enemy> iter = this.getListOfEnemies().iterator(); iter.hasNext();){
Enemy antagonist = iter.next();
if(antagonist instanceof Shark){
shark = (Shark) antagonist;
if(shark.getWord().startsWith(GameFrame.currentWord + keyPress)){ // if there is a word that matches the current word correctly typed by the user
GameFrame.currentWord += keyPress; // accept the key press
shark.incXPos(10); // push it rightwards
if(shark.getWord().equals(GameFrame.currentWord)){ // if already equals
this.diver.incScore(shark.getScore()); // score will be incremented
shark.setIsAlive(false); // shark will die
GameFrame.currentWord = ""; // reset the word
iter.remove(); // remove it to the arraylist
this.energyTimer.countUp();
appear = new DisplayScore(shark.getXPos(), shark.getYPos(), shark.getScore()); // the score will appear
appearThread = new Thread(appear);
this.add(appear);
appearThread.start();
}
}
}
else if(antagonist instanceof Fish){
fish = (Fish) antagonist;
if(fish.getWord().startsWith(GameFrame.currentWord + keyPress)){
GameFrame.currentWord += keyPress;
if(fish.getWord().equals(GameFrame.currentWord)){
this.diver.incScore(fish.getScore());
fish.setIsAlive(false);
iter.remove();
GameFrame.currentWord = "";
this.energyTimer.countUp();
appear = new DisplayScore(fish.getXPos(), fish.getYPos(), fish.getScore());
appearThread = new Thread(appear);
this.add(appear);
appearThread.start();
}
}
}
else if(antagonist instanceof Missile){
missile = (Missile) antagonist;
if(missile.getWord().startsWith(GameFrame.currentWord + keyPress)){
GameFrame.currentWord += keyPress;
if(missile.getWord().equals(GameFrame.currentWord)){
this.diver.incScore(missile.getScore());
missile.setIsTyped(true);
iter.remove();
GameFrame.currentWord = "";
this.energyTimer.countUp();
appear = new DisplayScore(missile.getXPos(), missile.getYPos(), missile.getScore());
appearThread = new Thread(appear);
this.add(appear);
appearThread.start();
}
}
}
}
}
private void spawnSharks(){
Random r = new Random();
int numOfSharks = r.nextInt(2) + 3; // maximum of 4 can be spawned at a time
for(int i = 0; i < numOfSharks; i++){
String randomWord = listOfKeys.get(r.nextInt(listOfKeys.size()));
this.getListOfEnemies().add((Enemy) new Shark(randomWord, this.listOfWords.get(randomWord), GameFrame.SCREEN_WIDTH, GameFrame.SCREEN_HEIGHT - (100 * (i + 2)), this));
}
}
private void spawnFishes(){
Random r = new Random();
int numOfFishes = r.nextInt(3) + 4;
for(int i = 0; i < numOfFishes; i++){
int letter = r.nextInt(26) + 65;
this.getListOfEnemies().add((Enemy) new Fish(Character.toString((char) letter), letter - 64, GameFrame.SCREEN_WIDTH, GameFrame.SCREEN_HEIGHT - (100 * (i + 2)), this));
}
}
private void spawnJellyfish(){
Random r = new Random();
int numOfJellyfish = r.nextInt(5) + 3;
for(int i = 0; i < numOfJellyfish; i++){
String rand = listOfKeys_3Letters.get(r.nextInt(listOfKeys_3Letters.size()));
this.getListOfEnemies().add((Enemy) new Jellyfish(rand, this.listOfWords_3Letters.get(rand), 100 * i + 360, GameFrame.SCREEN_HEIGHT, this));
}
}
private void spawnMissiles(){
Random r = new Random();
int noOfMissiles = this.boss.getMissiles().size(); // the actual missiles are created in the boss
for(int i = 0; i < noOfMissiles; i++){
Missile m = this.boss.getMissiles().get(i);
this.getListOfEnemies().add((Enemy)m);
}
this.boss.getMissiles().clear();
}
public Diver getDiver(){
return this.diver;
}
private void loadImage(String filename){
try{
this.img = Toolkit.getDefaultToolkit().getImage(filename);
} catch(Exception e){}
}
@Override
public void run(){
Random r = new Random();
Shark shark;
Fish fish;
Jellyfish jellyfish;
Thread sharkThread;
Thread fishThread;
Thread jellyFishThread;
int rand;
this.diver = new Diver("diver", 20, 0);
this.diverThread = new Thread(diver);
this.add(diver);
/* Energy Timer */
this.energyTimer = new EnergyTimer(diver);
this.energyTimerThread = new Thread(energyTimer);
this.add(energyTimer);
Ocean.north = new TopPanel(diver,1);
this.add(north);
/* Meter */
this.meter = new Meter(diver);
this.meterThread = new Thread(meter);
this.add(meter);
meterThread.start();
diverThread.start();
this.energyTimerThread.start();
int flag = 0;
int flag2 = 0;
while(this.diver.getDepth() != Diver.TOTAL_DEPTH && this.diver.isAlive() == true){
this.checkXPos();
rand = r.nextInt(3); // randomize spawn
if(this.diver.hasDescended() == true && this.enemies.size() == 0){
switch(rand){
case 0: this.spawnFishes(); break;
case 1: this.spawnSharks(); break;
case 2: if(flag2 == 0){
this.spawnJellyfish(); // jellyfish is only a bonus, appear only once
flag2 = 1;
}
break;
}
}
try{
Thread.sleep(500);
} catch(Exception e){}
if(this.diver.isAlive() == true){
for(Iterator<Enemy> iter = this.getListOfEnemies().iterator(); iter.hasNext();){ // then iterate throughout the arraylist
Enemy temp = iter.next();
if(temp instanceof Shark){
shark = (Shark) temp;
sharkThread = new Thread(shark);
this.add(shark);
sharkThread.start();
}
else if(temp instanceof Jellyfish){
jellyfish = (Jellyfish) temp;
jellyFishThread = new Thread(jellyfish);
this.add(jellyfish);
jellyFishThread.start();
}
else if(temp instanceof Fish){
fish = (Fish) temp;
fishThread = new Thread(fish);
this.add(fish);
fishThread.start();
}
}
}
try{
Thread.sleep(500);
} catch(Exception e){}
}
while(flag == 0){ // to ensure that before the boss come out, the ocean should be empty of enemies
this.checkXPos();
if(this.diver.getDepth() >= Diver.TOTAL_DEPTH && this.getListOfEnemies().isEmpty()){
flag = 1; // to break the loop
this.boss = new Boss(GameFrame.SCREEN_WIDTH, 130, this.diver, this);
this.boss.setPreferredSize(new Dimension(1280, 720));
Thread bossThread = new Thread(this.boss);
this.add(this.boss);
bossThread.start();
HPBar hb = new HPBar(this.boss); // instantiate the hp bar
this.add(hb);
try{
Thread.sleep(1000);
} catch(Exception e){}
while(this.boss.getHp() > 0 && this.diver.isAlive() == true){
this.checkXPos();
if(this.getListOfEnemies().size() == 0) this.spawnMissiles(); // if the missiles are already typed, spawn missiles
this.startMissileThreads();
try{
Thread.sleep(200);
} catch(Exception e){ e.getMessage(); }
}
}
}
}
private synchronized void startMissileThreads(){
for(Iterator<Enemy> iter = this.getListOfEnemies().iterator(); iter.hasNext();){
Enemy temp = iter.next();
if(temp instanceof Missile){
Missile m = (Missile) temp;
Thread missileThread = new Thread(m);
this.add(m);
missileThread.start();
}
}
}
@Override
public void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.drawImage(this.img, 0, 0,null);//display this image as a background
Font font = new Font("arial", Font.BOLD, 20);
g.setColor(Color.WHITE);
g.setFont(font);
Toolkit.getDefaultToolkit().sync();//makes animations smooth
}
}
| lolzz77/Typer-Shark | src/Ocean.java |
249,186 | public class Square {
private String state;
private int x;
private int y;
public Square(int x, int y){
this.state = "ocean";
this.x = y;
this.y = x;
}
public void makeShip(){
if (this.state.equals("ocean")){
this.state = "ship";
}
}
public int[] getXY(){
return new int[] {this.x, this.y};
}
public void makeNeighbor(){
if (this.state.equals("ocean")){
this.state = "neighbor";
}
}
public void makeHit(){
if (this.state.equals("ship")){
this.state = "hit";
} else if (this.state.equals("ocean") || this.state.equals("neighbor")) {
this.state = "miss";
}
}
public void makeSunk(){
if (this.state.equals("hit")){
this.state = "sunk";
}
}
public void makeMissFromNeighbor(){
this.state = "miss";
}
public boolean isNeigbor(){
return this.state.equals("neighbor");
}
public boolean isShip(){
return this.state.equals("ship");
}
public boolean isHit(){
return this.state.equals("hit");
}
public boolean isSunk(){
return this.state.equals("sunk");
}
public boolean isMiss(){
return this.state.equals("miss");
}
public boolean isOcean(){
return this.state.equals("ocean");
}
public String getState(){
return this.state;
}
public String showStatusToOwner() {
//(ship,hit,sank, ocean, miss, neighbor, )
if (this.isShip()){
return "■";
} else if (this.isHit()){
return "×";
} else if (this.isSunk()){
return "▒";
}else if (this.isMiss()){
return "Ø";
}
else {
return " ";
}
}
public String showStatusToOponent() {
if (this.isSunk()){
return "▒";
} else if (this.isHit()){
return "×";
}else if (this.isMiss()){
return "Ø";
}
else {
return " ";
}
}
} | DavidCichy/battleshipsJava | Square.java |
249,187 | import java.security.Policy.Parameters;
/**
* Represents the all data points scrapped from Kayak.com
*
* @author issacwon
*
*/
public class Flights {
private String carrier = null;
private String departureTime = null;
private String arrivalTime = null;
private String stops = null;
private String duration = null;
private String departureAirport = null;
private String arrivalAirport = null;
private String flightDetails = null;
private int flightPrice;
private int numberLayover;
private String flightNum;
private String bookingLink;
/**
* Represents one line from the csv file (once scrapped) that is passed on to
* dataReader class
*
* @param price
* @param numLayover
* @param flightDet
* @param flyNum
* @param link
*/
public Flights(int price, int numLayover, String flightDet, String flyNum, String link) {
this.flightPrice = price;
this.numberLayover = numLayover;
this.flightDetails = flightDet;
this.bookingLink = link;
this.flightNum = flyNum;
}
public Flights() {
}
public int getFlightPrice() {
return flightPrice;
}
public void setFlightPrice(int flightPrice) {
this.flightPrice = flightPrice;
}
public int getNumberLayover() {
return numberLayover;
}
public void setNumberLayover(int numberLayover) {
this.numberLayover = numberLayover;
}
public String getFlightNum() {
return flightNum;
}
public void setFlightNum(String flightNum) {
this.flightNum = flightNum;
}
public String getBookingLink() {
return bookingLink;
}
public void setBookingLink(String bookingLink) {
this.bookingLink = bookingLink;
}
public String getCarrier() {
return carrier;
}
public void setCarrier(String carrier) {
this.carrier = carrier;
}
public String getDepartureTime() {
return departureTime;
}
public void setDepartureTime(String departureTime) {
this.departureTime = departureTime;
}
public String getArrivalTime() {
return arrivalTime;
}
public void setArrivalTime(String arrivalTime) {
this.arrivalTime = arrivalTime;
}
public String getStops() {
return stops;
}
public void setStops(String stops) {
this.stops = stops;
}
public String getDuration() {
return duration;
}
public void setDuration(String duration) {
this.duration = duration;
}
public String getDepartureAirport() {
return departureAirport;
}
public void setDepartureAirport(String departureAirport) {
this.departureAirport = departureAirport;
}
public String getArrivalAirport() {
return arrivalAirport;
}
public void setArrivalAirport(String arrivalAirport) {
this.arrivalAirport = arrivalAirport;
}
public String getFlightDetails() {
return flightDetails;
}
public void setFlightDetails(String flightDetails) {
this.flightDetails = flightDetails;
}
/**
* Getter for Flights with "|" delimited format
*
* @return
*/
public String getFlights() {
String flightInfo = null;
flightInfo = carrier + ("|") + flightDetails + ("|") + departureTime + ("|") + arrivalTime + ("|") + stops
+ ("|") + duration + ("|") + departureAirport + ("|") + arrivalAirport;
return flightInfo;
}
}
| UPenn-CIT599/final-project-team8_flights | src/Flights.java |
249,191 | import java.awt.FontFormatException;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
public class Flights {
ArrayList <String> flights = new ArrayList <String> ();
public Flights() throws IOException {
FileReader readerHandle = new FileReader("Flights.csv");
BufferedReader BR = new BufferedReader(readerHandle);
String line = "";
while ((line = BR.readLine()) != null) {
flights.add(line);
}
}
// Returning List of Flights from CSV File
public ArrayList <String> getFlights() {
return flights;
}
// Getting List of Departure Cities
public ArrayList <String> getDepartCities(ArrayList <String> flights) {
ArrayList <String> departCities = new ArrayList <String> ();
for (int i = 0; i < flights.size(); i++) {
String [] lineArr = flights.get(i).split(",");
if (departCities.size() == 0) {
departCities.add(lineArr[7]);
} else {
int j = 0;
while (!departCities.get(j).equals(lineArr[7])) {
if (j == departCities.size() - 1) {
departCities.add(lineArr[7]);
break;
}
j++;
}
}
}
return departCities;
}
// Getting List of Arrival Cities
public ArrayList <String> getArrivalCities(ArrayList <String> flights) {
ArrayList <String> arrivalCities = new ArrayList <String> ();
for (int i = 0; i < flights.size(); i++) {
String [] lineArr = flights.get(i).split(",");
if (arrivalCities.size() == 0) {
arrivalCities.add(lineArr[9]);
} else {
int j = 0;
while (!arrivalCities.get(j).equals(lineArr[9])) {
if (j == arrivalCities.size() - 1) {
arrivalCities.add(lineArr[9]);
break;
}
j++;
}
}
}
return arrivalCities;
}
// Filtering Flights based on User Data
public ArrayList <String> filterFlights (ArrayList <String> userFlight) {
ArrayList <String> foundFlights = new ArrayList <String> ();
for (int i = 0; i < flights.size(); i++) {
String flight = flights.get(i);
String lineArr [] = flight.split(",");
String dbDepartCity = lineArr[7];
String dbArrivalCity = lineArr[9];
String dbDepartDate = lineArr[0];
if (userFlight.get(0).equals(dbDepartCity)) {
if (userFlight.get(1).equals(dbArrivalCity)) {
if (userFlight.get(2).equals(dbDepartDate)) {
foundFlights.add(flight);
} else {
continue;
}
} else {
continue;
}
} else {
continue;
}
}
ArrayList <String> foundFlightsBack = new ArrayList <String> ();
if (userFlight.size() == 4) {
for (int i = 0; i < flights.size(); i++) {
String flight = flights.get(i);
String lineArr [] = flight.split(",");
String dbDepartCity = lineArr[7];
String dbArrivalCity = lineArr[9];
String dbReturnDate = lineArr[0];
if (userFlight.get(0).equals(dbArrivalCity)) {
if (userFlight.get(1).equals(dbDepartCity)) {
if (userFlight.get(3).equals(dbReturnDate)) {
foundFlightsBack.add(flight);
} else {
continue;
}
} else {
continue;
}
} else {
continue;
}
}
}
int backFlightsCounter = 0;
if (foundFlights.size() == foundFlightsBack.size()) {
for (int i = 1; i <= foundFlights.size(); i += 2) {
foundFlights.add(i, foundFlightsBack.get(backFlightsCounter));
backFlightsCounter++;
}
}
return foundFlights;
}
}
| rohanian73/Brunel-Flight-Management-System | src/Flights.java |
249,192 | package DISNY;
import java.util.Arrays;
import java.util.Comparator;
public class Sort_Flights {
public Flight_Detail[] sortFlights(Flight_Detail[] flights) {
Arrays.sort(flights, new Comparator<Flight_Detail>(){
@Override
public int compare(Flight_Detail flight1, Flight_Detail flight2) {
if (flight1 == null || flight2 == null) {
return 0; // or handle the null case as needed
}
if (flight1.getPrice() == flight2.getPrice()) {
return 0;
} else if (flight1.getPrice() > flight2.getPrice()) {
return 1;
} else {
return -1;
}
}
});
return flights;
}
}
| yashpatel458/Aeroquest | src/DISNY/Sort_Flights.java |
249,194 | /*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/GUIForms/JFrame.java to edit this template
*/
package airline;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
//import org.apache.commons.dbutils.DbUtils;
import net.proteanit.sql.DbUtils;
/**
*
* @author sam
*/
public class Flights extends javax.swing.JFrame {
/**
* Creates new form Flights
*/
public Flights() {
initComponents();
DisplayFlights();
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel3 = new javax.swing.JLabel();
jLabel4 = new javax.swing.JLabel();
jLabel5 = new javax.swing.JLabel();
FCodeTb = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
jLabel7 = new javax.swing.JLabel();
SeatsTb = new javax.swing.JTextField();
jLabel8 = new javax.swing.JLabel();
jPanel3 = new javax.swing.JPanel();
jLabel9 = new javax.swing.JLabel();
jLabel10 = new javax.swing.JLabel();
PSourceCp = new javax.swing.JComboBox<>();
PDestCb = new javax.swing.JComboBox<>();
SaveBtn = new javax.swing.JButton();
EditBtn = new javax.swing.JButton();
DeleteBtn = new javax.swing.JButton();
BackBtn = new javax.swing.JButton();
jLabel11 = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
FlightsTable = new javax.swing.JTable();
PDate = new com.toedter.calendar.JDateChooser();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setUndecorated(true);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel3.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
jLabel3.setForeground(new java.awt.Color(0, 204, 255));
jLabel3.setText("Flights List");
jLabel4.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
jLabel4.setForeground(new java.awt.Color(0, 204, 255));
jLabel4.setText("Flight Code");
jLabel5.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
jLabel5.setForeground(new java.awt.Color(0, 204, 255));
jLabel5.setText("Source");
FCodeTb.setFont(new java.awt.Font("Arial Rounded MT Bold", 0, 14)); // NOI18N
jLabel6.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
jLabel6.setForeground(new java.awt.Color(0, 204, 255));
jLabel6.setText("TakeofDate");
jLabel7.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
jLabel7.setForeground(new java.awt.Color(0, 204, 255));
jLabel7.setText("Destination");
SeatsTb.setFont(new java.awt.Font("Arial Rounded MT Bold", 0, 14)); // NOI18N
SeatsTb.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SeatsTbActionPerformed(evt);
}
});
jLabel8.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
jLabel8.setForeground(new java.awt.Color(0, 204, 255));
jLabel8.setText("NumberofSeats");
jPanel3.setBackground(new java.awt.Color(0, 204, 255));
jLabel9.setFont(new java.awt.Font("Arial Black", 0, 25)); // NOI18N
jLabel9.setText("Top Flight");
jLabel10.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
jLabel10.setText("X");
jLabel10.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jLabel10MouseClicked(evt);
}
});
javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
jPanel3.setLayout(jPanel3Layout);
jPanel3Layout.setHorizontalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel3Layout.createSequentialGroup()
.addGap(243, 243, 243)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 153, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jLabel10)
.addContainerGap())
);
jPanel3Layout.setVerticalGroup(
jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
.addContainerGap(20, Short.MAX_VALUE)
.addComponent(jLabel9, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
.addGroup(jPanel3Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel10)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
PSourceCp.setFont(new java.awt.Font("Arial Narrow", 0, 14)); // NOI18N
PSourceCp.setForeground(new java.awt.Color(0, 204, 255));
PSourceCp.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Addis Ababa(ADD)", "Arba Minch(AMH)", "Asmara(ASM)", "Assosa(ASO)", "Hawassa(AWA)", "Jinka(BCO)", "Bahir Dar(BJR)", "Dire Dawa(DIR)", "Kombolcha(DSE)", "Gode(GDE)", "Gondar(GDQ)", "Gambella(GMB)", "Humera(HUE)", "Jijiga(JIJ)", "Lalibella(LLI)", "Shire(SHC)", "Semera(SZE)", " ", " ", " " }));
PDestCb.setForeground(new java.awt.Color(0, 204, 255));
PDestCb.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Addis Ababa(ADD)", "Arba Minch(AMH)", "Asmara(ASM)", "Assosa(ASO)", "Hawassa(AWA)", "Jinka(BCO)", "Bahir Dar(BJR)", "Dire Dawa(DIR)", "Kombolcha(DSE)", "Gode(GDE)", "Gondar(GDQ)", "Gambella(GMB)", "Humera(HUE)", "Jijiga(JIJ)", "Lalibella(LLI)", "Shire(SHC)", "Semera(SZE)", " ", " " }));
SaveBtn.setBackground(new java.awt.Color(204, 204, 204));
SaveBtn.setFont(new java.awt.Font("Arial Rounded MT Bold", 0, 14)); // NOI18N
SaveBtn.setForeground(new java.awt.Color(0, 204, 255));
SaveBtn.setText("Save");
SaveBtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
SaveBtnMouseClicked(evt);
}
});
EditBtn.setBackground(new java.awt.Color(204, 204, 204));
EditBtn.setFont(new java.awt.Font("Arial Rounded MT Bold", 0, 14)); // NOI18N
EditBtn.setForeground(new java.awt.Color(0, 204, 255));
EditBtn.setText("Edit");
EditBtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
EditBtnMouseClicked(evt);
}
});
DeleteBtn.setBackground(new java.awt.Color(204, 204, 204));
DeleteBtn.setFont(new java.awt.Font("Arial Rounded MT Bold", 0, 14)); // NOI18N
DeleteBtn.setForeground(new java.awt.Color(0, 204, 255));
DeleteBtn.setText("Delete");
DeleteBtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
DeleteBtnMouseClicked(evt);
}
});
DeleteBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
DeleteBtnActionPerformed(evt);
}
});
BackBtn.setBackground(new java.awt.Color(204, 204, 204));
BackBtn.setFont(new java.awt.Font("Arial Rounded MT Bold", 0, 14)); // NOI18N
BackBtn.setForeground(new java.awt.Color(0, 204, 255));
BackBtn.setText("Back");
BackBtn.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
BackBtnMouseClicked(evt);
}
});
jLabel11.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
jLabel11.setForeground(new java.awt.Color(0, 204, 255));
jLabel11.setText("Manage Flights");
FlightsTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String [] {
"Title 1", "Title 2", "Title 3", "Title 4"
}
));
FlightsTable.setSelectionBackground(new java.awt.Color(0, 204, 255));
FlightsTable.setShowGrid(true);
FlightsTable.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
FlightsTableMouseClicked(evt);
}
});
jScrollPane1.setViewportView(FlightsTable);
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jScrollPane1)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addGap(124, 124, 124)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(144, 144, 144)
.addComponent(PDestCb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel5)
.addGap(92, 92, 92)
.addComponent(jLabel7)))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(FCodeTb, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(PSourceCp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(jPanel1Layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(SaveBtn)
.addGap(57, 57, 57)
.addComponent(EditBtn)
.addGap(55, 55, 55)
.addComponent(DeleteBtn)
.addGap(20, 20, 20))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(254, 254, 254)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(22, 22, 22))))
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addComponent(PDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(30, 30, 30)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(SeatsTb, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel8)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(40, 40, 40)
.addComponent(BackBtn))))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(251, 251, 251)
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jLabel11, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(24, 24, 24)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(0, 90, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(SaveBtn)
.addComponent(EditBtn)
.addComponent(DeleteBtn)
.addComponent(BackBtn)))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel5)
.addComponent(jLabel7)
.addComponent(jLabel6)
.addComponent(jLabel8))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(FCodeTb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(PSourceCp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(PDestCb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(PDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(SeatsTb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
.addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(0, 0, 0))
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
java.sql.Connection con = null;
PreparedStatement pst = null;
ResultSet Rs = null;
java.sql.Statement St = null,St1 = null;
int FId = 0;
String Key = "";
private void DisplayFlights(){
try{
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/airlinedb","root","root");
St = con.createStatement();
Rs = St.executeQuery("select * from FlightTbl");
//FlightsTable.setModel(dataModel);
FlightsTable.setModel(DbUtils.resultSetToTableModel(Rs));
}catch(Exception e){
}
}
private void SeatsTbActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SeatsTbActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_SeatsTbActionPerformed
/*private void CountPassengers()
{
try{
St1 = con.createStatement();
Rs1 = St1.executeQuery("select max (pid) from flightTbl");
Rs1.next();
FId = Rs1.getInt(1)+1;
}catch(Exception e){
}
}*/
private void Clear()
{
FCodeTb.setText("");
SeatsTb.setText("");
}
private void SaveBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_SaveBtnMouseClicked
if(FCodeTb.getText().isEmpty() || SeatsTb.getText().isEmpty() || PSourceCp.getSelectedIndex()== -1 || PDestCb.getSelectedIndex()== -1)
{
JOptionPane.showMessageDialog(this,"missing information");
}else{
try{
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/airlinedb","root","root");
PreparedStatement Add = con.prepareStatement("insert into FlightTbl values (?,?,?,?,?)");
Add.setString(1,FCodeTb.getText() );
Add.setString(2,PSourceCp.getSelectedItem().toString());
Add.setString(3,PDestCb.getSelectedItem().toString());
Add.setString(4,PDate.getDate().toString());
Add.setInt(5,Integer.valueOf(SeatsTb.getText()));
int row = Add.executeUpdate();
JOptionPane.showMessageDialog(this,"Flights added");
con.close();
Clear();
DisplayFlights();
}catch(Exception e){
JOptionPane.showMessageDialog(this,e);
}
}
}//GEN-LAST:event_SaveBtnMouseClicked
private void BackBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_BackBtnMouseClicked
new MainForm().setVisible(true);
this.dispose();
}//GEN-LAST:event_BackBtnMouseClicked
private void EditBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_EditBtnMouseClicked
if(Key == "")
{
JOptionPane.showMessageDialog(this,"Select a flight");
}else{
try{
// CountPassengers();
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/airlinedb","root","root");
String Query = "Update FlightTbl set FlSource=?,FlDest=?,FlDate=?,FlSeats=? where FlCode=?";
PreparedStatement Add = con.prepareStatement(Query);
Add.setString(5,Key );
Add.setString(1,PSourceCp.getSelectedItem().toString());
Add.setString(2,PDestCb.getSelectedItem().toString());
Add.setString(3, PDate.getDate().toString());
Add.setString(4,SeatsTb.getText());
int row = Add.executeUpdate();
JOptionPane.showMessageDialog(this,"Flight updated");
con.close();
DisplayFlights();
Clear();
}catch(Exception e){
JOptionPane.showMessageDialog(this,e);
}
}
}//GEN-LAST:event_EditBtnMouseClicked
private void DeleteBtnMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_DeleteBtnMouseClicked
if(Key == ""){
JOptionPane.showMessageDialog(this,"select passenger");
}else {
try{
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/airlinedb","root","root");
String Query = "Delete from FlightTbl where FlCode ="+Key;
java.sql.Statement Del = con.createStatement();
Del.executeUpdate(Query);
JOptionPane.showMessageDialog(this,"Passenger deleted");
DisplayFlights();
}catch(Exception e){
JOptionPane.showMessageDialog(this,e);
}
}
}//GEN-LAST:event_DeleteBtnMouseClicked
//String key = "";
private void FlightsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_FlightsTableMouseClicked
DefaultTableModel model = (DefaultTableModel)FlightsTable.getModel();
int MyIndex = FlightsTable.getSelectedRow();
Key = model.getValueAt(MyIndex,0 ).toString();
PSourceCp.setSelectedItem(model.getValueAt(MyIndex,1 ).toString());
PDestCb.setSelectedItem(model.getValueAt(MyIndex,2 ).toString());
SeatsTb.setText(model.getValueAt(MyIndex,4 ).toString());
}//GEN-LAST:event_FlightsTableMouseClicked
private void DeleteBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DeleteBtnActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_DeleteBtnActionPerformed
private void jLabel10MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel10MouseClicked
System.exit(0);
}//GEN-LAST:event_jLabel10MouseClicked
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(Flights.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Flights.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Flights.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Flights.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new Flights().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton BackBtn;
private javax.swing.JButton DeleteBtn;
private javax.swing.JButton EditBtn;
private javax.swing.JTextField FCodeTb;
private javax.swing.JTable FlightsTable;
private com.toedter.calendar.JDateChooser PDate;
private javax.swing.JComboBox<String> PDestCb;
private javax.swing.JComboBox<String> PSourceCp;
private javax.swing.JButton SaveBtn;
private javax.swing.JTextField SeatsTb;
private javax.swing.JLabel jLabel10;
private javax.swing.JLabel jLabel11;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JLabel jLabel8;
private javax.swing.JLabel jLabel9;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel3;
private javax.swing.JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
}
| samiyamohammed/airline-online-ticket-reservation-java | Flights.java |
249,195 | package p1;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.ResultSet;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import p1.Airplane;
/**
* Servlet implementation class Search
*/
@WebServlet("/Search2")
public class Search2 extends HttpServlet {
String from,to,doj,no_of_persons,clas,type;
String promo=null;
public ArrayList<Airplane> search_flights(String type,String from,String to,String date,String clas,HttpServletRequest request) {
ArrayList<Airplane> flights=new ArrayList<Airplane>();
try {
HttpSession ses=request.getSession();
Date date1=new Date();
Date date2=new SimpleDateFormat("yyyy-mm-dd").parse(date);
Date d = null;
d = new SimpleDateFormat("yyyy-MM-dd").parse(date);
SimpleDateFormat s=new SimpleDateFormat("E");
String x=s.format(d);
x=x.toLowerCase();
ses.setAttribute("day", x);
//System.out.println(s.format(d));
String sql="select airplane.id,company.company,route.distance,airplane.start_time,airplane.dest_time,airplane.mon_seats,airplane.mon_seats_bus,airplane.price,airplane.price2 from airplane inner join company on company.id=airplane.company_id inner join route on route.id=airplane.route_id where route.from1=? and route.to1=? and mon=1";
if(x.equals("mon"))
sql="select airplane.id,company.company,route.distance,airplane.start_time,airplane.dest_time,airplane.mon_seats,airplane.mon_seats_eco,airplane.price,airplane.price2 from airplane inner join company on company.id=airplane.company_id inner join route on route.id=airplane.route_id where route.from1=? and route.to1=? and mon=1";
if(x.equals("tue"))
sql="select airplane.id,company.company,route.distance,airplane.start_time,airplane.dest_time,airplane.tue_seats,airplane.tue_seats_bus,airplane.price,airplane.price2 from airplane inner join company on company.id=airplane.company_id inner join route on route.id=airplane.route_id where route.from1=? and route.to1=? and tue=1";
if(x.equals("wed"))
sql="select airplane.id,company.company,route.distance,airplane.start_time,airplane.dest_time,airplane.wed_seats,airplane.wed_seats_bus,airplane.price,airplane.price2 from airplane inner join company on company.id=airplane.company_id inner join route on route.id=airplane.route_id where route.from1=? and route.to1=? and wed=1";
if(x.equals("thu"))
sql="select airplane.id,company.company,route.distance,airplane.start_time,airplane.dest_time,airplane.thu_seats,airplane.thu_seats_bus,airplane.price,airplane.price2 from airplane inner join company on company.id=airplane.company_id inner join route on route.id=airplane.route_id where route.from1=? and route.to1=? and thu=1";
if(x.equals("fri"))
sql="select airplane.id,company.company,route.distance,airplane.start_time,airplane.dest_time,airplane.fri_seats,airplane.fri_seats_bus,airplane.price,airplane.price2 from airplane inner join company on company.id=airplane.company_id inner join route on route.id=airplane.route_id where route.from1=? and route.to1=? and fri=1";
if(x.equals("sat"))
sql="select airplane.id,company.company,route.distance,airplane.start_time,airplane.dest_time,airplane.sat_seats,airplane.sat_seats_bus,airplane.price,airplane.price2 from airplane inner join company on company.id=airplane.company_id inner join route on route.id=airplane.route_id where route.from1=? and route.to1=? and sat=1";
if(x.equals("sun"))
sql="select airplane.id,company.company,route.distance,airplane.start_time,airplane.dest_time,airplane.sun_seats,airplane.sun_seats_bus,airplane.price,airplane.price2 from airplane inner join company on company.id=airplane.company_id inner join route on route.id=airplane.route_id where route.from1=? and route.to1=? and sun=1";
String url="jdbc:mysql://localhost:3306/flight?useSSL=false";
String root="root";
String password="anandavishnu1";
String css="<link rel='stylesheet' href='WebContent/css/1.css'>";
String sql1="select code,value from flight.promocode";
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con=DriverManager.getConnection(url, root, password);
PreparedStatement st=con.prepareStatement(sql);
Statement st1=(Statement) con.createStatement();
ResultSet rs1=st1.executeQuery(sql1);
st.setString(1, from);
st.setString(2, to);
int eco,bus,seats;
ResultSet rs=st.executeQuery();
while(rs.next()) {
Airplane a=new Airplane(rs.getInt(1),rs.getString(2),rs.getFloat(3),from,to,rs.getString(4),rs.getString(5),rs.getInt(6),rs.getInt(7),rs.getFloat(8),rs.getFloat(9));
flights.add(a);
}
String promo="";
while(rs1.next()) {
if(!(rs1.getString(1).equals("zero"))) {
promo=promo+"use code "+rs1.getString(1)+" and get flat Rs."+rs1.getFloat(2)+" off, ";
}}
ses.setAttribute("promo", promo);
System.out.println(promo);
}
catch(Exception e) {
e.printStackTrace();
}
return flights;
}
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
PrintWriter out=response.getWriter();
HttpSession ses=request.getSession();
//out.println("Sorry no flights available on this date ...showing flight on nearest dates");
String type=request.getParameter("ty");
String from=request.getParameter("from").toString();
String to=request.getParameter("to").toString();
if(from.equals(to)) {
out.print("<html><script>alert('From and To places cannot be same')</script>");
out.print("<script>location.href='index.jsp'</script></html>");
}
String date=request.getParameter("date").toString();
String clas=request.getParameter("clas").toString();
String date1=request.getParameter("ret_date").toString();
System.out.println(date);
System.out.println(from);
System.out.println(to);
Date date2=new Date();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String strDate = dateFormat.format(date2);
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = sdf.parse(date); //input date
System.out.println(d1);
Date d2 = sdf.parse(strDate);
System.out.println(d2);
int e=d1.compareTo(d2);
//System.out.println(e);
Date f1=new Date(); //todays date
DateFormat g1 = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(f1);
c.add(Calendar.DATE, 7);
Date c1=c.getTime(); //date after 7 days
if(d1.compareTo(d2)<0) {
out.print("<html><script>alert('Date out of scope')</script>");
out.print("<script>location.href='index.jsp'</script></html>");
}
else if(f1.compareTo(d1)*d1.compareTo(c1)<0){
out.print("<html><script>alert('Date out of scope')</script>");
out.print("<script>location.href='index.jsp'</script></html>");
}
}
catch(Exception e) {
}
int i=0;
ses.setAttribute("i", i);
ses.setAttribute("class", clas);
int num_eco=0;
int num_bus=0;
out=response.getWriter();
String val=null;
if(type.equals("Search Domestic")) {
val="domestic";
}
else {
val="international";
}
ArrayList<Airplane> a=search_flights(val,from,to,date,clas,request);
ArrayList<Airplane> b=search_flights(val,to,from,date1,clas,request);
if(a.size()==0) {
//ses.setAttribute("j", j+1);
RequestDispatcher rd=request.getRequestDispatcher("Search1");
rd.forward(request, response);
}
else {
out.print("<html><head><style>#you\r\n" +
"{\r\n" +
"padding:8px 16px;\r\n" +
"border-radius:30px;\r\n" +
"outline:none;\r\n" +
"background-colour:olive;\r\n" +
"border-color:olive;\r\n" +
"float:right;\r\n" +
"cursor:pointer;\r\n" +
"}\r\n" +
"</style></head></style>");
out.print("<form action='Customer' method='post'><input id='you' type='submit' value='logout' name='s1'></form>");
Iterator itr=a.iterator();
Iterator itr1=b.iterator();
while(itr.hasNext()) {
Airplane ap=(Airplane) itr.next();
if(i==0) {
out.print("<html>"
+ "<head>"
+ "<style>"
+ "table {\r\n" +
" font-family: arial, sans-serif;\r\n" +
" border-collapse: collapse;\r\n" +
" width: 100%;\r\n" +
"}\r\n" +
"\r\n" +
"td, th {\r\n" +
" border: 1px solid #dddddd;\r\n" +
" text-align: left;\r\n" +
" padding: 8px;\r\n" +
"}\r\n" +
"\r\n" +
"tr:nth-child(even) {\r\n" +
" background-color: #dddddd;\r\n" +
"}"
+ "</style>"
+"</head>"
+ "</html>");
out.print("<table>"
+"<tr>"
+"<th>Flight Id</th>"
+"<th>From</th>"
+"<th>To</th>"
+ "<th>Company</th>"
+ "<th>Distance</th>"
+ "<th>Date of Journey(YYYY/MM/DD)</th>"
+ "<th>Arrival Time</th>"
+ "<th>Destination Time</th>"
+ "<th>Economy Seat Price</th>"
+"<th>Business Seat Price</th>"
+ "<th>Availability(Economy)</th>"
+ "<th>Availability(Business)</th>"
+ "</tr>"
);
i=1;
}
int eco=ap.seat_eco;
int bus=ap.seat_bus;
int seats=eco+bus;
out.print("<html>"
+ "<head>"
+ "<style>"
+ "table {\r\n" +
" font-family: arial, sans-serif;\r\n" +
" border-collapse: collapse;\r\n" +
" width: 100%;\r\n" +
"}\r\n" +
"\r\n" +
"td, th {\r\n" +
" border: 1px solid #dddddd;\r\n" +
" text-align: left;\r\n" +
" padding: 8px;\r\n" +
"}\r\n" +
"\r\n" +
"tr:nth-child(even) {\r\n" +
" background-color: #dddddd;\r\n" +
"}"
+ "#one{"
+ "color:green;}"
+ "#two{"
+ "color:red;}"
+ "</style>"
+"</head>"
+ "</html>");
out.print("<tr>"
+"<td>"+ap.id+"</td>"
+ "<td>"+from+"</td>"
+ "<td>"+to+"</td>"
+"<td>"
+ ap.company
+"</td>"
+ "<td>"
+ap.distance+"km</td>"
+ "<td>"
+date+"</td>"
+ "<td>"+ap.start_time+"</td>"
+ "<td>"+ap.end_time+"</td>"
+"<td>"+ap.price+"</td>"
+ "<td>"+ap.price2+"</td>"
);
ses.setAttribute("from", from);
ses.setAttribute("to", to);
ses.setAttribute("date", date);
ses.setAttribute("eco1", eco);
ses.setAttribute("bus1", bus);
if(eco>0) {
out.print("<td id='one'><b><big>"
+ eco+" seats available</big></b></td>"
);
}
else {
out.print("<td id='two'><b><big>Seats Unavailable</big></b></td>");
}
if(bus>0) {
out.print("<td id='one'><b><big>"
+ bus+" seats available</big></b></td></tr>"
);
}
else {
out.print("<td id='two'><b><big>Seats Unavailable</big></b></td></tr>");
}
}
while(itr1.hasNext()) {
Airplane ap1=(Airplane) itr1.next();
int eco=ap1.seat_eco;
int bus=ap1.seat_bus;
int seats=eco+bus;
out.print("<html>"
+ "<head>"
+ "<style>"
+ "table {\r\n" +
" font-family: arial, sans-serif;\r\n" +
" border-collapse: collapse;\r\n" +
" width: 100%;\r\n" +
"}\r\n" +
"\r\n" +
"td, th {\r\n" +
" border: 1px solid #dddddd;\r\n" +
" text-align: left;\r\n" +
" padding: 8px;\r\n" +
"}\r\n" +
"\r\n" +
"tr:nth-child(even) {\r\n" +
" background-color: #dddddd;\r\n" +
"}"
+ "#one{"
+ "color:green;}"
+ "#two{"
+ "color:red;}"
+ "</style>"
+"</head>"
+ "</html>");
out.print("<tr>"
+"<td>"+ap1.id+"</td>"
+ "<td>"+to+"</td>"
+ "<td>"+from+"</td>"
+"<td>"
+ ap1.company
+"</td>"
+ "<td>"
+ap1.distance+"km</td>"
+ "<td>"
+date1+"</td>"
+ "<td>"+ap1.start_time+"</td>"
+ "<td>"+ap1.end_time+"</td>"
+"<td>"+ap1.price+"</td>"
+ "<td>"+ap1.price2+"</td>"
);
ses.setAttribute("from", from);
ses.setAttribute("to", to);
ses.setAttribute("date", date);
ses.setAttribute("eco1", eco);
ses.setAttribute("bus1", bus);
if(eco>0) {
out.print("<td id='one'><b><big>"
+ eco+" seats available</big></b></td>"
);
}
else {
out.print("<td id='two'><b><big>Seats Unavailable</big></b></td>");
}
if(bus>0) {
out.print("<td id='one'><b><big>"
+ bus+" seats available</big></b></td></tr>"
);
}
else {
out.print("<td id='two'><b><big>Seats Unavailable</big></b></td></tr>");
}
}
if(clas.equals("economy")) {
out.println("<center><tr><form action='add.jsp' method='post'>"
+ "<b><big style='margin-left:30px'>Flight Id:</big></b>"
+ "<input type='number' name='id' style='padding:5px 10px;margin-right:15px;' placeholder='Enter Flight Id'><br><br>");
out.print("<b><big style='margin-left:30px' id='1'>Enter Economy Class Seats:</big></b>"
+ "<input type='number' name='num' style='padding:5px 10px;margin-right:15px;' placeholder='Enter economy'>");
out.print("<b><big style='margin-left:20px'>Have a promo code:</big></b><input type='text' name='promo' style='padding:5px 10px;margin-right:15px;' placeholder='Promo Code'>"
+ " <input type='submit' style='padding:5px 10px' value='Book'></form><br><br></tr></center></table>");
}
else {
out.println("<center><tr><form action='add.jsp' method='post'>"
+ "<b><big style='margin-left:30px'>Flight Id:</big></b>"
+ "<input type='number' name='id' style='padding:5px 10px;margin-right:15px;' placeholder='Enter Flight Id'><br><br>");
out.print("<b><big id='2'>Enter Business Class Seats:</big></b>"
+ "<input type='number' name='num' style='padding:5px 10px;margin-right:15px;' placeholder='Enter number of seats'>");
out.print("<b><big style='margin-left:20px'>Have a promo code:</big></b><input type='text' name='promo' style='padding:5px 10px;margin-right:15px;' placeholder='Promo Code'>"
+ " <input type='submit' style='padding:5px 10px' value='Book'></form><br><br></tr></center></table>");
}
String promo=ses.getAttribute("promo").toString();
System.out.println(promo);
out=response.getWriter();
out.print("<br><br><marquee behavior='scroll' direction='left'><b style='color:red'><h3>Promo Codes:"
+promo
+ "</h3></b></marquee>");
}
}
}
| av0899/Airline-Reservation-System | src/p1/Search2.java |
249,196 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package airline;
/**
*
* @author Dell
*/
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.event.*;
import java.util.*;
import javax.swing.table.DefaultTableModel;
import assignment2.AddFlight;
import assignment2.updateFlight;
public class ManageFlights extends javax.swing.JFrame {
FlightRecord fRecordObj;
/**
* Creates new form ManageFlights (constructor)
*/
public ManageFlights() {
initComponents();
this.fRecordObj = new FlightRecord();
addRowToTable();
}
// public ManageFlights(FlightRecord fRecordObj) {
// initComponents();
// // this.fRecordObj=new FlightRecord();
// this.fRecordObj = fRecordObj;
// addRowToTable();
// }
ArrayList<Flight> LoadAllFlights() {
dbConnectivity db = new dbConnectivity();
return db.LoadAllFlights();
}
public void addRowToTable() {
ArrayList<Flight> flights = LoadAllFlights();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
Object rowdata[] = new Object[6];
for (int i = 0; i < flights.size(); i++) {
rowdata[0] = flights.get(i).flightNo;
rowdata[1] = flights.get(i).airline;
rowdata[2] = flights.get(i).origin;
rowdata[3] = flights.get(i).destination;
rowdata[4] = flights.get(i).date;
rowdata[5] = flights.get(i).time;
model.addRow(rowdata);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLayeredPane1 = new javax.swing.JLayeredPane();
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
goBackButton = new javax.swing.JButton();
addButton = new javax.swing.JButton();
updateButton = new javax.swing.JButton();
deleteButton = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
javax.swing.GroupLayout jLayeredPane1Layout = new javax.swing.GroupLayout(jLayeredPane1);
jLayeredPane1.setLayout(jLayeredPane1Layout);
jLayeredPane1Layout.setHorizontalGroup(
jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jLayeredPane1Layout.setVerticalGroup(
jLayeredPane1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jPanel1.setBackground(new java.awt.Color(255, 255, 255));
jLabel1.setFont(new java.awt.Font("Tempus Sans ITC", 1, 18)); // NOI18N
jLabel1.setText("All Flights");
goBackButton.setFont(new java.awt.Font("Tempus Sans ITC", 1, 11)); // NOI18N
goBackButton.setText("GO BACK");
goBackButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
goBackButtonActionPerformed(evt);
}
});
addButton.setFont(new java.awt.Font("Tempus Sans ITC", 1, 11)); // NOI18N
addButton.setText("ADD");
addButton.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusGained(java.awt.event.FocusEvent evt) {
addButtonFocusGained(evt);
}
public void focusLost(java.awt.event.FocusEvent evt) {
addButtonFocusLost(evt);
}
});
addButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
addButtonActionPerformed(evt);
}
});
updateButton.setFont(new java.awt.Font("Tempus Sans ITC", 1, 11)); // NOI18N
updateButton.setText("UPDATE");
updateButton.addFocusListener(new java.awt.event.FocusAdapter() {
public void focusLost(java.awt.event.FocusEvent evt) {
updateButtonFocusLost(evt);
}
});
updateButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
updateButtonActionPerformed(evt);
}
});
deleteButton.setFont(new java.awt.Font("Tempus Sans ITC", 1, 11)); // NOI18N
deleteButton.setText("DELETE");
deleteButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
deleteButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 265, Short.MAX_VALUE)
.addComponent(goBackButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(addButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(updateButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(deleteButton)
.addGap(55, 55, 55))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(goBackButton)
.addComponent(addButton)
.addComponent(updateButton)
.addComponent(deleteButton)))
.addContainerGap())
);
jTable1.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Flight Number", "Airline", "Origin", "Destination", "Date", "Time"
}
));
jScrollPane1.setViewportView(jTable1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addComponent(jScrollPane1)
.addContainerGap())))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(22, 22, 22))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void goBackButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goBackButtonActionPerformed
this.hide();
}//GEN-LAST:event_goBackButtonActionPerformed
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addButtonActionPerformed
AddFlight addFlight = new AddFlight();
addFlight.setVisible(true);
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
addRowToTable();
}//GEN-LAST:event_addButtonActionPerformed
private void updateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateButtonActionPerformed
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
try {
int SelectedRow = jTable1.getSelectedRow();
String flightNo = jTable1.getModel().getValueAt(SelectedRow, 0).toString();
String airline = jTable1.getModel().getValueAt(SelectedRow, 1).toString();
String origin = jTable1.getModel().getValueAt(SelectedRow, 2).toString();
String destination = jTable1.getModel().getValueAt(SelectedRow, 3).toString();
String date = jTable1.getModel().getValueAt(SelectedRow, 4).toString();
String time = jTable1.getModel().getValueAt(SelectedRow, 5).toString();
Flight obj = new Flight(flightNo, airline, origin, destination, date, time);
updateFlight update = new updateFlight(obj);
update.setVisible(true);
this.hide();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error! Please select something!");
}
model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
addRowToTable();
}//GEN-LAST:event_updateButtonActionPerformed
private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteButtonActionPerformed
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
int option = JOptionPane.showConfirmDialog(null, "Are you sure you want to delete?", "Delete", JOptionPane.YES_NO_OPTION);
if (option == 0) {
try {
int SelectedRow = jTable1.getSelectedRow();
String flightNo = jTable1.getModel().getValueAt(SelectedRow, 0).toString();
if (fRecordObj.delete(flightNo)) {
System.out.println("to be deleted" + flightNo);
JOptionPane.showMessageDialog(null, flightNo + " deleted successfully!");
model.removeRow(SelectedRow);
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error! Please select something!");
}
}
model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
addRowToTable();
}//GEN-LAST:event_deleteButtonActionPerformed
private void addButtonFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_addButtonFocusLost
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
addRowToTable();
}//GEN-LAST:event_addButtonFocusLost
private void addButtonFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_addButtonFocusGained
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
addRowToTable();
}//GEN-LAST:event_addButtonFocusGained
private void updateButtonFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_updateButtonFocusLost
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
model.setRowCount(0);
addRowToTable();
}//GEN-LAST:event_updateButtonFocusLost
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ManageFlights.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ManageFlights.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ManageFlights.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ManageFlights.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ManageFlights().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton addButton;
private javax.swing.JButton deleteButton;
private javax.swing.JButton goBackButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLayeredPane jLayeredPane1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
public javax.swing.JTable jTable1;
private javax.swing.JButton updateButton;
// End of variables declaration//GEN-END:variables
}
| meharfatimakhan/AirlineManagementSystem | ManageFlights.java |
249,197 | /**
* Flight
* @author Chris Moore, Evan Scales, Lyn Cork
*/
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.Map.Entry;
import java.time.LocalDate;
import java.util.ArrayList;
public class Flight extends ObjectToBeBooked {
private LocalDate date;
private String departingAirport;
private String destAirport;
private String takeOffTime;
private String landingTime;
private String totalFlightTime;
private boolean layover;
private ArrayList<Flight> flights;
private int numStops;
private double discountPercent;
private Map<String, Seating> seats;
private String departingGate;
private String destGate;
/**
* Constructor to use when first making a flight
* Use for normal flights
* @param date The date of the flight
* @param departingAirport The departing airport
* @param destAirport The dest airport
* @param takeOffTime The take off time
* @param landingTime The landing time
* @param totalFlightTime The total flight time
* @param layover If the flight has a layover, always false
* @param company The company
* @param pricing The pricing hashmap
* @param seats The seats hashmap
* @param departingGate The departing gatew
* @param destGate The arriving gate
*/
Flight(LocalDate date, String departingAirport, String destAirport,
String takeOffTime, String landingTime, String totalFlightTime,
boolean layover, String company, HashMap<String, Integer> pricing,
Map<String, Seating> seats, String departingGate, String destGate) {
super(company, pricing);
setIsLayover(layover);
setDate(date);
setDepartingAirport(departingAirport);
setDestAirport(destAirport);
setTakeOffTime(takeOffTime);
setLandingTime(landingTime);
setTotalFlightTime(totalFlightTime);
setSeats(seats);
setDapartingGate(departingGate);
setDestGate(destGate);
}
/**
* Constructor to use when loading flights from database
* Use for normal Flights
* @param date The date oif the flight
* @param departingAirport The departing airport
* @param destAirport The dest airport
* @param takeOffTime The take off time
* @param landingTime The landing time
* @param totalFlightTime The total time
* @param layover If the flight has a layover, always false
* @param company The company
* @param pricing The pricing hashmap
* @param seats The seats hashmap
* @param id The id
* @param departingGate The departing gate
* @param destGate The arriving gate
*/
Flight(LocalDate date, String departingAirport, String destAirport,
String takeOffTime, String landingTime, String totalFlightTime,
boolean layover, String company, HashMap<String, Integer> pricing,
Map<String, Seating> seats, UUID id, String departingGate, String destGate) {
super(company, pricing, id);
setIsLayover(layover);
setDate(date);
setDepartingAirport(departingAirport);
setDestAirport(destAirport);
setTakeOffTime(takeOffTime);
setLandingTime(landingTime);
setTotalFlightTime(totalFlightTime);
setSeats(seats);
setDapartingGate(departingGate);
setDestGate(destGate);
}
/**
* Constructor
* @param date
* @param departingAirport
* @param destAirport
* @param takeOffTime
* @param landingTime
* @param totalFlightTime
* @param layover
* @param flights
* @param numStops
* @param discountPercent
* @param company
*/
Flight(LocalDate date, String departingAirport, String destAirport, String takeOffTime,
String landingTime, String totalFlightTime, Boolean layover, ArrayList<Flight> flights,
int numStops, double discountPercent, String company) {
super(company, null);
HashMap<String, Integer> pricing = discountLayoverPrice(flights, discountPercent);
setPricingMap(pricing);
setDate(date);
setDepartingAirport(departingAirport);
setDestAirport(destAirport);
setTakeOffTime(takeOffTime);
setLandingTime(landingTime);
setTotalFlightTime(totalFlightTime);
setIsLayover(layover);
setFlights(flights);
setNumStops(numStops);
setDiscountPercent(discountPercent);
}
/**
* Constructor
* @param date
* @param departingAirport
* @param destAirport
* @param takeOffTime
* @param landingTime
* @param totalFlightTime
* @param layover
* @param flights
* @param numStops
* @param discountPercent
* @param id
* @param company
*/
Flight(LocalDate date, String departingAirport, String destAirport, String takeOffTime,
String landingTime, String totalFlightTime, Boolean layover, ArrayList<Flight> flights,
int numStops, double discountPercent, UUID id, String company) {
super(company, null, id);
HashMap<String, Integer> pricing = discountLayoverPrice(flights, discountPercent);
setPricingMap(pricing);
setDate(date);
setDepartingAirport(departingAirport);
setDestAirport(destAirport);
setTakeOffTime(takeOffTime);
setLandingTime(landingTime);
setTotalFlightTime(totalFlightTime);
setIsLayover(layover);
setFlights(flights);
setNumStops(numStops);
setDiscountPercent(discountPercent);
}
// Member functions
/**
* Sets the new pricing hashmap for flights with layovers
* To find the pricing of a flight with layover add up each corresponding cabin price
* for each connecting flight. Then discount that by 20% to get the new pricing map
* @param flights The connecitng flights
* @param discountPercent The discount number (0.8)
* @return The new pricing map
*/
public HashMap<String, Integer> discountLayoverPrice(ArrayList<Flight> flights, double discountPercent) {
HashMap<String, Integer> ret = new HashMap<>();
for (Flight flight : flights) {
HashMap<String, Integer> pricingMap = flight.getPricing();
for (String key : pricingMap.keySet()) {
int value = pricingMap.get(key);
if (ret.containsKey(key)) {
ret.put(key, ret.get(key) + value);
} else {
ret.put(key, value);
}
}
}
for (String key : ret.keySet()) {
int value = (int) Math.round(ret.get(key) * discountPercent);
ret.put(key, value);
}
return ret;
}
/**
* Sets the seat coresponding to the passed seat number to booked
* @param seatNum the seat number
*/
public void book(String seatNum) {
Seating seat = seats.get(seatNum);
seat.setBooked(true);
}
/**
* Sets the seat corresponding to the peassed seat number to unbooked
* @param seatNum the seat number
*/
public void unBook(String seatNum) {
Seating seat = seats.get(seatNum);
seat.setBooked(false);
}
/**
* Creates a String that is a map of available, unavailable, and medical seating
* @return String representation of seats
*/
public String printSeats() {
Set<Entry<String, Seating>> temp;
String ret = "";
ret = " First | Main Cabin | Economy";
ret += "\n 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30";
ret += "\nA ";
int i = 0;
if (getIsLayover() == false) {
temp = seats.entrySet();
} else {
temp = flights.get(0).getSeating().entrySet();
}
for (Map.Entry<String, Seating> entry : temp) {
i++;
Seating seat = entry.getValue();
boolean booked = seat.getBooked();
boolean medical = seat.getIsMedicalSeat();
if (i <= 30) {
if (booked == true) {
ret += "X ";
}
else if (booked == false && medical == false) {
ret += "O ";
}
else if (medical == true) {
ret += "M ";
}
}
else if (i == 31) {
ret += "\nB ";
if (booked == true) {
ret += "X ";
}
else if (booked == false && medical == false) {
ret += "O ";
}
else if (medical == true) {
ret += "M ";
}
}
else if (i > 31 && i <= 60) {
if (booked == true) {
ret += "X ";
}
else if (booked == false && medical == false) {
ret += "O ";
}
else if (medical == true) {
ret += "M ";
}
}
else if (i == 61) {
ret += "\n\nC ";
if (booked == true) {
ret += "X ";
}
else if (booked == false && medical == false) {
ret += "O ";
}
else if (medical == true) {
ret += "M ";
}
}
else if (i > 61 && i <= 90) {
if (booked == true) {
ret += "X ";
}
else if (booked == false && medical == false) {
ret += "O ";
}
else if (medical == true) {
ret += "M ";
}
}
else if (i == 91) {
ret += "\nD ";
if (booked == true) {
ret += "X ";
}
else if (booked == false && medical == false) {
ret += "O ";
}
else if (medical == true) {
ret += "M ";
}
}
else if (i > 91 && i <= 120) {
if (booked == true) {
ret += "X ";
}
else if (booked == false && medical == false) {
ret += "O ";
}
else if (medical == true) {
ret += "M ";
}
}
else if (i > 120) {
break;
}
}
return ret;
}
/**
* creates a string representation of the flight
* @return String representation of flight
*/
@Override
public String toString() {
String ret = "";
ret = departingAirport + " -> " + destAirport + " Economy Main Cabin First";
ret += "\n" + takeOffTime + " " + landingTime + " " + totalFlightTime;
if (numStops <= 0) {
ret += " Nonstop ";
}
else if (numStops == 1) {
ret += " " + numStops + " stop ";
} else {
ret += " " + numStops + " stops ";
}
ret += "$" + getPrice("Economy") + " $" + getPrice("Main Cabin")
+ " $" + getPrice("First");
if (getIsLayover() == false) {
ret += "\n" + getAvailableSeats() + " Seats Available";
}
if (numStops > 0 && getIsLayover() == true) {
for (int j = 0; j < flights.size(); j++) {
int nextAvailableSeats = 0;
Flight nextFlight = flights.get(j);
ret += "\n" + nextFlight.getDepartingAirport() + " -> " + nextFlight.getDestAirport();
nextAvailableSeats = nextFlight.getAvailableSeats();
ret += "\n" + nextAvailableSeats + " Seats Available";
}
}
ret += "\n" + company + "\n";
return ret;
}
private int getAvailableSeats() {
int i = 0;
int availableSeats = 0;
for (Map.Entry<String, Seating> entry : seats.entrySet()) {
i++;
Seating seat = entry.getValue();
boolean booked = seat.getBooked();
if (i <= 120) {
if (booked == false) {
availableSeats += 1;
}
} else {
break;
}
}
return availableSeats;
}
// GETTERS
/**
* gets date
* @return data
*/
public LocalDate getDate() {
return this.date;
}
/**
* get departing airport
* @return departing airport
*/
public String getDepartingAirport() {
return this.departingAirport;
}
/**
* get destination airport
* @return destination airport
*/
public String getDestAirport() {
return this.destAirport;
}
/**
* gets takeoff time
* @return takeoff time
*/
public String getTakeOffTime() {
return this.takeOffTime;
}
/**
* gets landing time
* @return landing time
*/
public String getLandingTime() {
return this.landingTime;
}
/**
* gets total flight time
* @return total flight time
*/
public String getTotalFlightTime() {
return this.totalFlightTime;
}
/**
* gets if flight has layover
* @return true or false
*/
public boolean getIsLayover() {
return this.layover;
}
/**
* gets arraylist of flights
* @return arraylist of flights
*/
public ArrayList<Flight> getFlights() {
return this.flights;
}
/**
* gets the number of stops made
* @return number of stops
*/
public int getNumStops() {
return this.numStops;
}
/**
* gets the discount percentage
* @return discount percentage
*/
public double getDiscountPercent() {
return this.discountPercent;
}
/**
* gets the hashmap of seats
* @return the hashmap of seats
*/
public Map<String, Seating> getSeating() {
return this.seats;
}
/**
* gets the departing gate
* @return the departing gate
*/
public String getDepartingGate() {
return this.departingGate;
}
/**
* gets the destination gate
* @return the destination gate
*/
public String getDestGate() {
return this.destGate;
}
// SETTERS
/**
* sets the date
* @param date date
*/
public void setDate(LocalDate date) {
this.date = date;
}
/**
* sets the departing airport
* @param departingAirport departing airport
*/
public void setDepartingAirport(String departingAirport) {
this.departingAirport = departingAirport;
}
/**
* sets the destination airport
* @param destAirport destination airport
*/
public void setDestAirport(String destAirport) {
this.destAirport = destAirport;
}
/**
* sets the takeoff time
* @param takeOffTime takeoff time
*/
public void setTakeOffTime(String takeOffTime) {
this.takeOffTime = takeOffTime;
}
/**
* sets the landing time
* @param landingTime landing time
*/
public void setLandingTime(String landingTime) {
this.landingTime = landingTime;
}
/**
* sets the total flight time
* @param totalFlightTime total flight time
*/
public void setTotalFlightTime(String totalFlightTime) {
this.totalFlightTime = totalFlightTime;
}
/**
*sets if flight has layover
* @param layover true/false
*/
public void setIsLayover(boolean layover) {
this.layover = layover;
}
/**
* sets arraylist of flights
* @param flights arraylist of flights
*/
public void setFlights(ArrayList<Flight> flights) {
if (flights != null)
this.flights = flights;
else
this.flights = new ArrayList<>();
}
/**
* sets the number of stops made
* @param numStops number of stops
*/
public void setNumStops(int numStops) {
this.numStops = numStops;
}
/**
* sets the discount percent
* @param discountPercent discount percent
*/
public void setDiscountPercent(double discountPercent) {
this.discountPercent = discountPercent;
}
/**
* sets the hashmap of seats
* @param seats the hashmap of seats
*/
public void setSeats(Map<String, Seating> seats) {
if (seats == null)
this.seats = null;
else if(seats.isEmpty())
this.seats = makeSeats();
else
this.seats = seats;
}
/**
* sets the departing gate
* @param departingGate departing gate
*/
public void setDapartingGate(String departingGate) {
this.departingGate = departingGate;
}
/**
* sets the destination gate
* @param destGate destination gate
*/
public void setDestGate(String destGate) {
this.destGate = destGate;
}
/**
* makes a hashmap of seats for the plane
* @return the hashmap of plane seats
*/
public Map<String, Seating> makeSeats() {
Map<String, Seating> ret = new LinkedHashMap<>();
/**
* Make 10 rows of First class seating
* Make 13 Rows of Main Cabin Seating
* Make 7 rows of Economy cabin seating
* First 2 columns are medical seats
*/
// Make A row seating
for (int i = 1; i < 31; i++) {
String seatNum = "";
Boolean medicalSeat;
Boolean booked = false;
int price;
String type;
seatNum = "A" + i;
// First class seats
if (i <= 10) {
if (i <= 2) {
medicalSeat = true;
} else {
medicalSeat = false;
}
type = "First";
} else if (i >= 24) { // Economy seating
medicalSeat = false;
type = "Economy";
} else { // Main cabin
medicalSeat = false;
type = "Main Cabin";
}
price = pricing.get(type);
Seating seat = new Seating(medicalSeat, booked, price, type, seatNum);
ret.put(seatNum, seat);
}
// Make B row seating
for (int i = 1; i < 31; i++) {
String seatNum = "";
Boolean medicalSeat;
Boolean booked = false;
int price;
String type;
seatNum = "B" + i;
// First class seats
if (i <= 10) {
if (i <= 2) {
medicalSeat = true;
} else {
medicalSeat = false;
}
type = "First";
} else if (i >= 24) { // Economy seating
medicalSeat = false;
type = "Economy";
} else { // Main cabin
medicalSeat = false;
type = "Main Cabin";
}
price = pricing.get(type);
Seating seat = new Seating(medicalSeat, booked, price, type, seatNum);
ret.put(seatNum, seat);
}
// Make C row seating
for (int i = 1; i < 31; i++) {
String seatNum = "";
Boolean medicalSeat;
Boolean booked = false;
int price;
String type;
seatNum = "C" + i;
// First class seats
if (i <= 10) {
if (i <= 2) {
medicalSeat = true;
} else {
medicalSeat = false;
}
type = "First";
} else if (i >= 24) { // Economy seating
medicalSeat = false;
type = "Economy";
} else { // Main cabin
medicalSeat = false;
type = "Main Cabin";
}
price = pricing.get(type);
Seating seat = new Seating(medicalSeat, booked, price, type, seatNum);
ret.put(seatNum, seat);
}
// Make D row seating
for (int i = 1; i < 31; i++) {
String seatNum = "";
Boolean medicalSeat;
Boolean booked = false;
int price;
String type;
seatNum = "D" + i;
// First class seats
if (i <= 10) {
if (i <= 2) {
medicalSeat = true;
} else {
medicalSeat = false;
}
type = "First";
} else if (i >= 24) { // Economy seating
medicalSeat = false;
type = "Economy";
} else { // Main cabin
medicalSeat = false;
type = "Main Cabin";
}
price = pricing.get(type);
Seating seat = new Seating(medicalSeat, booked, price, type, seatNum);
ret.put(seatNum, seat);
}
return ret;
}
} | evan-scales/flight-booking | src/Flight.java |
249,199 | import java.util.ArrayList;
public class ImportData {
public ArrayList<Passenger> passengers;
public ArrayList<Flight> flights;
public ImportData(ArrayList<Passenger> ps, ArrayList<Flight> fs)
{
passengers = ps;
flights = fs;
}
}
| TanaKonda/Airline_Reservation_System | ImportData.java |
249,200 | package Ex3;
import java.util.ArrayList;
import java.util.List;
public class ATC implements ATCInterface {
private List<Flight> flights;
public ATC() {
flights = new ArrayList<Flight>();
}
public void registerFlight(Flight flight) {
flights.add(flight);
}
@Override
public void notify(String message, Flight receiver) {
for (Flight flight : flights) {
if (flight == receiver) {
flight.receive(message);
}
}
}
}
| FranciscoCardita/leci-pds | lab10/Ex3/ATC.java |