Java - I think my boolean is defaulting to true for some reason - boolean

I'm having an issue with my hangman program. When I run it, the label holding the int variable "lives" is supposed to update when you guess a wrong letter. But for some reason it isn't. I've placed this in my code as a test mechanism, and it isn't appearing even here.
if (used[letter] = false) {
System.out.println("test");
However, when I place it here.. It DOES work..
if (finished == false) {
boolean found = false;
boolean www = false;
System.out.println("test");
if (used[letter] = false) {
It almost leads me to believe that used[letter] is true by default, when it really shouldn't be. The variable is declared at the very top. Any thoughts?
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import java.util.ArrayList;
public class Hangman implements ActionListener {
JFrame frame;
JPanel stats = new JPanel();
JLabel currentWordLA = new JLabel("Current word:");
JLabel triedLettersLA = new JLabel("Tried letters:");
JLabel triesLeftLA = new JLabel("Tries remaining:");
private String[] wordList = {"computer","java","activity","alaska","appearance","article",
"automobile","basket","birthday","canada","central","character","chicken","chosen",
"cutting","daily","darkness","diagram","disappear","driving","effort","establish","exact",
"establishment","fifteen","football","foreign","frequently","frighten","function","gradually",
"hurried","identity","importance","impossible","invented","italian","journey","lincoln",
"london","massage","minerals","outer","paint","particles","personal","physical","progress",
"quarter","recognise","replace","rhythm","situation","slightly","steady","stepped",
"strike","successful","sudden","terrible","traffic","unusual","volume","yesterday" };
public String mysteryWord;
public int lives;
private boolean finished = false;
private boolean won = false;
private Button a[];
public boolean used[] = new boolean[26];
public static void main (String[] args) {
Hangman gui = new Hangman();
gui.go();
}
class myDrawPanel extends JPanel {
public void paintComponent(Graphics g) {
setBackground(Color.white);
g.setColor(Color.gray);
g.fillRect(50, 200, 150, 20);
g.fillRect(90,20,10,200);
g.fillRect(90,20,60,10);
g.setColor(Color.black);
g.fillRect(145,20,5,25);
g.setColor(Color.green);
if (lives < 6 )
g.drawOval(132,45,30,30);
if (lives < 5 )
g.drawLine(147,75,147,100);
if (lives < 4 )
g.drawLine(147,100,167,133);
if (lives < 3 )
g.drawLine(147,100,127,133);
if (lives < 2 )
g.drawLine(147,75,167,85);
if (lives < 1 )
g.drawLine(147,75,127,85);
StringBuffer guessed = new StringBuffer();
for (int cl = 0; cl < mysteryWord.length(); cl++) {
if (used[(int)mysteryWord.charAt(cl)-'a'])
guessed.append(mysteryWord.charAt(cl));
else
guessed.append("*");
}
currentWordLA.setText("Current word: " + guessed.toString());
if (lives < 1) {
g.setColor(Color.white);
g.fillRect(70, 200, 200, 30);
g.setColor(Color.black);
g.drawString(mysteryWord.toString(),75,230);
Font fff = new Font("Helvetica",Font.BOLD,36);
g.setFont(fff);
g.setColor(Color.red);
g.drawString("You lose!",200,100);
//finished = true;
}
if (won) {
Font fff = new Font("Helvetica",Font.BOLD,36);
g.setFont(fff);
// Color red=new Color.red
g.setColor(Color.red);
g.drawString("You Win!",200,100);
//finished = true;
}
}
}
public void go() {
///////////////////////DESIGN BEGIN//////////////////////////////////////////////
frame = new JFrame("Hangman");
JPanel topPanel = new JPanel();
myDrawPanel noosePanel = new myDrawPanel();
JPanel bottomPanel = new JPanel();
JPanel scorePanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout( new GridLayout( 2, 0) );
bottomPanel.setLayout( new GridLayout( 0, 2) );
scorePanel.setSize(20,100);
noosePanel.setBorder(BorderFactory.createTitledBorder("Your progress."));
topPanel.setBorder(BorderFactory.createTitledBorder("Your arsenal."));
scorePanel.setBorder(BorderFactory.createTitledBorder("Your score."));
frame.add(topPanel);
frame.add(bottomPanel);
bottomPanel.add(scorePanel);
bottomPanel.add(noosePanel);
//Just the stats panel.
JButton restart = new JButton("Reset");
currentWordLA.setFont(new Font("Verdana", Font.PLAIN, 10));
currentWordLA.setForeground(Color.black);
triedLettersLA.setFont(new Font("Verdana", Font.PLAIN, 10));
triedLettersLA.setForeground(Color.black);
triesLeftLA.setFont(new Font("Verdana", Font.PLAIN, 10));
triesLeftLA.setForeground(Color.black);
restart.setFont(new Font("Verdana", Font.PLAIN, 16));
restart.setForeground(Color.red);
stats.setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(20,0,0,0);
c.anchor = GridBagConstraints.LINE_START;
stats.add(currentWordLA, c);
c.gridx = 0;
c.gridy = 1;
c.anchor = GridBagConstraints.LINE_START;
stats.add(triedLettersLA, c);
c.gridx = 0;
c.gridy = 2;
c.anchor = GridBagConstraints.LINE_START;
stats.add(triesLeftLA, c);
c.gridx = 0;
c.gridy = 3;
c.anchor = GridBagConstraints.LINE_START;
stats.add(restart, c);
scorePanel.add(stats);
///////////////////////DESIGN END//////////////////////////////////////////////
///////////////////////ALPHABET BEGIN//////////////////////////////////////////
int i;
StringBuffer buffer;
a = new Button[26];
topPanel.setLayout( new GridLayout( 4,0, 10, 10) );
for (i = 0; i <26; i++) {
buffer = new StringBuffer();
buffer.append((char)(i+'a'));
a[i] = new Button(buffer.toString());
a[i].setSize(100,100);
a[i].addActionListener( this );
topPanel.add(a[i]);
}
///////////////////////ALPHABET END//////////////////////////////////////////
//Just shows the entire window.
frame.setSize(500, 500);
frame.setResizable(false);
frame.setVisible(true);
//////////////////////GAMEPLAY BEGIN////////////////////////////////////////
lives = 6;
triesLeftLA.setText("Tries remaining: " + lives);
mysteryWord = wordGen();
}
//Returns a random word from the wordList bank.
private String wordGen() {
return wordList[0 + (int)(Math.random() * ((63 - 0) + 1)) ]; //Make sure to set these to nonprinted chars eventually
}
public void consultWord(int letter) {
if (finished == false) {
boolean found = false;
boolean www = false;
if (used[letter] = false) {
System.out.println("test");
for (int cl = 0 ; cl < mysteryWord.length(); cl++) {
if (mysteryWord.charAt(cl)==((char)(letter + 'a'))) {
found = true;
}
}
if (found == false) {
lives = lives - 1;
triesLeftLA.setText ("Tries remaining: " + lives);
}
}
used[letter] = true;
for (int cl = 0; cl < mysteryWord.length(); cl++) {
if (!used[(int)(mysteryWord.charAt(cl)) - 'a']){
www = true;
}
}
if (www == false) {
won = true;
}
frame.repaint();
}
}
public void actionPerformed( ActionEvent e) {
int i;
for (i = 0; i < 26; i++) {
if (e.getSource() == a[i]) {
consultWord(i); }
}
}
}

Make that:
if (used[letter] == false) {
System.out.println("test");

if (used[letter] = false) {
You just set used[letter] to false. Try ==
Of course, to avoid this typo you shouldn't be using == but rather ...
if (!used[letter]) {

Related

IndexOutOfRangeException: Can't figure out why index out of bound

So, I have a list of Upgrade systems for my game but it has a bug on it when I press upgrade for a second time the index out of range then pressed for the third times the index out of range gone. this whole script.
void Start()
{
newSelectedIndex = previousSelectedIndex = PlayerPrefs.GetInt("currentPlayer");
btn = Select_Player[newSelectedIndex].GetComponent<Button>();
btn.interactable = false;
Coins = M_CoinManager.instance.Coins;
for (int i = 0; i < Select_Player.Length; i++)
{
priceText[i].text = Cost_Player[i].ToString();
value_player[i] = "" + i;
Select_Player[i].SetActive(false);
buyPlayer[i] = PlayerPrefs.GetInt(value_player[i]);
}
//if(PlayerPrefs.HasKey("currentPlayer")){
selectedVehicleIndex = PlayerPrefs.GetInt("currentPlayer");
theVehicles[selectedVehicleIndex].SetActive(true);
VehicleInfo();
UpgradeButtonStatus();
}
// Update is called once per frame
void Update()
{
for (int i = 0; i < Select_Player.Length; i++)
{
buyPlayer[i] = PlayerPrefs.GetInt(value_player[i]);
if (i == buyPlayer[i])
{
Select_Player[i].SetActive(true);
upgradeBtn[i].interactable = true;
UpgradeButtonStatus();
}
else
{
upgradeBtn[i].interactable = false;
}
}
}
public void BuyCharact(int id)
{
M_SoundManager.instance.playUIsfx();
if (Cost_Player[id] <= Coins)
{
M_CoinManager.instance.AddCoins(-Cost_Player[id]);
PlayerPrefs.SetInt(value_player[id], id);
}
else
{
_CoinShake.DoShake();
Debug.Log("Does have enough coin");
}
}
public void Reset()
{
for (int i = 0; i < Select_Player.Length; i++)
{
PlayerPrefs.SetInt(value_player[i], 0);
}
}
public void Select(int id)
{
previousSelectedIndex = newSelectedIndex;
newSelectedIndex = id;
newSelectedIndex = selectedVehicleIndex;
PlayerPrefs.SetInt("currentPlayer", newSelectedIndex);
Button newbtn = Select_Player[previousSelectedIndex].GetComponent<Button>();
btn = Select_Player[newSelectedIndex].GetComponent<Button>();
btn.interactable = false;
newbtn.interactable = true;
M_SoundManager.instance.playUIsfx();
Debug.Log("Selected TypeCar" + newSelectedIndex);
}
public void nextVehicle()
{
M_SoundManager.instance.playUIsfx();
theVehicles[selectedVehicleIndex].SetActive(false);
selectedVehicleIndex = (selectedVehicleIndex + 1) % theVehicles.Length;
theVehicles[selectedVehicleIndex].SetActive(true);
VehicleInfo();
UpgradeButtonStatus();
}
public void PreviousVehicle()
{
M_SoundManager.instance.playUIsfx();
theVehicles[selectedVehicleIndex].SetActive(false);
selectedVehicleIndex--;
if (selectedVehicleIndex < 0)
{
selectedVehicleIndex += theVehicles.Length;
}
theVehicles[selectedVehicleIndex].SetActive(true);
VehicleInfo();
UpgradeButtonStatus();
}
public void VehicleInfo()
{
currLevel = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel;
levelText[selectedVehicleIndex].text = "Level: " + (currLevel + 1);
powerText[selectedVehicleIndex].text = "Power: " + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[currLevel].motorPower;
brakeText[selectedVehicleIndex].text = "Brake: " + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[currLevel].brakePower;
Debug.Log(selectedVehicleIndex);
}
public void upgradeMethod()
{
nextLevelIndex = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel + 1;
if (Coins >= _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex].unlockCost)
{
Coins -= _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex].unlockCost;
_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel++;
if (_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel < _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel.Length - 1)
{
upgradeBtnText[selectedVehicleIndex].text = "Upgrade Cost :" + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex + 1].unlockCost;
}
else
{
upgradeBtn[selectedVehicleIndex].interactable = false;
upgradeBtnText[selectedVehicleIndex].text = "Max Level";
}
VehicleInfo();
}
}
private void UpgradeButtonStatus()
{
if (_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel < _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel.Length - 1)
{
upgradeBtn[selectedVehicleIndex].interactable = true;
nextLevelIndex = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel + 1;
upgradeBtnText[selectedVehicleIndex].text = "Upgrade Cost :" + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex + 1].unlockCost;
}
else
{
upgradeBtn[selectedVehicleIndex].interactable = false;
upgradeBtnText[selectedVehicleIndex].text = "Max Level";
}
}
and the error reference to this method :
private void UpgradeButtonStatus()
{
if (_VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel < _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel.Length - 1)
{
upgradeBtn[selectedVehicleIndex].interactable = true;
nextLevelIndex = _VehicleStats[0].carItem[selectedVehicleIndex].unlockedLevel + 1;
upgradeBtnText[selectedVehicleIndex].text = "Upgrade Cost :" + _VehicleStats[0].carItem[selectedVehicleIndex].vehicleLevel[nextLevelIndex + 1].unlockCost;
}
else
{
upgradeBtn[selectedVehicleIndex].interactable = false;
upgradeBtnText[selectedVehicleIndex].text = "Max Level";
}
}
as you can see on the update that's what I mean. after i press upgrade for third times the error stopped.
and this for the inpector
Arrays length is one higher than their highest index, but last iteration of "for" loops goes to array.length.
You need to make "for" loops to array.length-1.
I see you do "for" loops of up to array.length.
I haven't truly read thru your whole script so there might be more, but it's a typical error in my "for" loops so I think that is causing your error.

2D procedural dungeon generation game

I am currently messing around with a procedural 2D game in unity. Below are the scripts i am using to generate the dungeon and wanted to know if there was anyway of specifying a standard starting room. I have prefab room built but would like to have a single prefab room players always start in.
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class DungeonGeneration : MonoBehaviour {
[SerializeField]
private int numberOfRooms;
[SerializeField]
private int numberOfObstacles;
[SerializeField]
private Vector2Int[] possibleObstacleSizes;
[SerializeField]
private int numberOfEnemies;
[SerializeField]
private GameObject[] possibleEnemies;
[SerializeField]
private GameObject goalPrefab;
[SerializeField]
private TileBase obstacleTile;
private Room[,] rooms;
private Room currentRoom;
private static DungeonGeneration instance = null;
void Awake () {
if (instance == null) {
DontDestroyOnLoad (this.gameObject);
instance = this;
this.currentRoom = GenerateDungeon ();
} else {
string roomPrefabName = instance.currentRoom.PrefabName ();
GameObject roomObject = (GameObject) Instantiate (Resources.Load (roomPrefabName));
Tilemap tilemap = roomObject.GetComponentInChildren<Tilemap> ();
instance.currentRoom.AddPopulationToTilemap (tilemap, instance.obstacleTile);
Destroy (this.gameObject);
}
}
void Start () {
string roomPrefabName = this.currentRoom.PrefabName ();
GameObject roomObject = (GameObject) Instantiate (Resources.Load (roomPrefabName));
Tilemap tilemap = roomObject.GetComponentInChildren<Tilemap> ();
this.currentRoom.AddPopulationToTilemap (tilemap, this.obstacleTile);
}
private Room GenerateDungeon() {
int gridSize = 3 * numberOfRooms;
rooms = new Room[gridSize, gridSize];
Vector2Int initialRoomCoordinate = new Vector2Int ((gridSize / 2) - 1, (gridSize / 2) - 1);
Queue<Room> roomsToCreate = new Queue<Room> ();
roomsToCreate.Enqueue (new Room(initialRoomCoordinate.x, initialRoomCoordinate.y));
List<Room> createdRooms = new List<Room> ();
while (roomsToCreate.Count > 0 && createdRooms.Count < numberOfRooms) {
Room currentRoom = roomsToCreate.Dequeue ();
this.rooms [currentRoom.roomCoordinate.x, currentRoom.roomCoordinate.y] = currentRoom;
createdRooms.Add (currentRoom);
AddNeighbors (currentRoom, roomsToCreate);
}
int maximumDistanceToInitialRoom = 0;
Room finalRoom = null;
foreach (Room room in createdRooms) {
List<Vector2Int> neighborCoordinates = room.NeighborCoordinates ();
foreach (Vector2Int coordinate in neighborCoordinates) {
Room neighbor = this.rooms [coordinate.x, coordinate.y];
if (neighbor != null) {
room.Connect (neighbor);
}
}
room.PopulateObstacles (this.numberOfObstacles, this.possibleObstacleSizes);
room.PopulatePrefabs (this.numberOfEnemies, this.possibleEnemies);
int distanceToInitialRoom = Mathf.Abs (room.roomCoordinate.x - initialRoomCoordinate.x) + Mathf.Abs(room.roomCoordinate.y - initialRoomCoordinate.y);
if (distanceToInitialRoom > maximumDistanceToInitialRoom) {
maximumDistanceToInitialRoom = distanceToInitialRoom;
finalRoom = room;
}
}
GameObject[] goalPrefabs = { this.goalPrefab };
finalRoom.PopulatePrefabs(1, goalPrefabs);
return this.rooms [initialRoomCoordinate.x, initialRoomCoordinate.y];
}
private void AddNeighbors(Room currentRoom, Queue<Room> roomsToCreate) {
List<Vector2Int> neighborCoordinates = currentRoom.NeighborCoordinates ();
List<Vector2Int> availableNeighbors = new List<Vector2Int> ();
foreach (Vector2Int coordinate in neighborCoordinates) {
if (this.rooms[coordinate.x, coordinate.y] == null) {
availableNeighbors.Add (coordinate);
}
}
int numberOfNeighbors = (int)Random.Range (1, availableNeighbors.Count);
for (int neighborIndex = 0; neighborIndex < numberOfNeighbors; neighborIndex++) {
float randomNumber = Random.value;
float roomFrac = 1f / (float)availableNeighbors.Count;
Vector2Int chosenNeighbor = new Vector2Int(0, 0);
foreach (Vector2Int coordinate in availableNeighbors) {
if (randomNumber < roomFrac) {
chosenNeighbor = coordinate;
break;
} else {
roomFrac += 1f / (float)availableNeighbors.Count;
}
}
roomsToCreate.Enqueue (new Room(chosenNeighbor));
availableNeighbors.Remove (chosenNeighbor);
}
}
private void PrintGrid() {
for (int rowIndex = 0; rowIndex < this.rooms.GetLength (1); rowIndex++) {
string row = "";
for (int columnIndex = 0; columnIndex < this.rooms.GetLength (0); columnIndex++) {
if (this.rooms [columnIndex, rowIndex] == null) {
row += "X";
} else {
row += "R";
}
}
Debug.Log (row);
}
}
public void MoveToRoom(Room room) {
this.currentRoom = room;
}
public Room CurrentRoom() {
return this.currentRoom;
}
public void ResetDungeon() {
this.currentRoom = GenerateDungeon ();
}
}
and
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
public class Room
{
public Vector2Int roomCoordinate;
public Dictionary<string, Room> neighbors;
private string[,] population;
private Dictionary<string, GameObject> name2Prefab;
public Room (int xCoordinate, int yCoordinate)
{
this.roomCoordinate = new Vector2Int (xCoordinate, yCoordinate);
this.neighbors = new Dictionary<string, Room> ();
this.population = new string[18, 10];
for (int xIndex = 0; xIndex < 18; xIndex += 1) {
for (int yIndex = 0; yIndex < 10; yIndex += 1) {
this.population [xIndex, yIndex] = "";
}
}
this.population [8, 5] = "Player";
this.name2Prefab = new Dictionary<string, GameObject> ();
}
public Room (Vector2Int roomCoordinate)
{
this.roomCoordinate = roomCoordinate;
this.neighbors = new Dictionary<string, Room> ();
this.population = new string[18, 10];
for (int xIndex = 0; xIndex < 18; xIndex += 1) {
for (int yIndex = 0; yIndex < 10; yIndex += 1) {
this.population [xIndex, yIndex] = "";
}
}
this.population [8, 5] = "Player";
this.name2Prefab = new Dictionary<string, GameObject> ();
}
public List<Vector2Int> NeighborCoordinates () {
List<Vector2Int> neighborCoordinates = new List<Vector2Int> ();
neighborCoordinates.Add (new Vector2Int(this.roomCoordinate.x, this.roomCoordinate.y - 1));
neighborCoordinates.Add (new Vector2Int(this.roomCoordinate.x + 1, this.roomCoordinate.y));
neighborCoordinates.Add (new Vector2Int(this.roomCoordinate.x, this.roomCoordinate.y + 1));
neighborCoordinates.Add (new Vector2Int(this.roomCoordinate.x - 1, this.roomCoordinate.y));
return neighborCoordinates;
}
public void Connect (Room neighbor) {
string direction = "";
if (neighbor.roomCoordinate.y < this.roomCoordinate.y) {
direction = "N";
}
if (neighbor.roomCoordinate.x > this.roomCoordinate.x) {
direction = "E";
}
if (neighbor.roomCoordinate.y > this.roomCoordinate.y) {
direction = "S";
}
if (neighbor.roomCoordinate.x < this.roomCoordinate.x) {
direction = "W";
}
this.neighbors.Add (direction, neighbor);
}
public string PrefabName () {
string name = "Room_";
foreach (KeyValuePair<string, Room> neighborPair in neighbors) {
name += neighborPair.Key;
}
return name;
}
public Room Neighbor (string direction) {
return this.neighbors [direction];
}
public void PopulateObstacles (int numberOfObstacles, Vector2Int[] possibleSizes) {
for (int obstacleIndex = 0; obstacleIndex < numberOfObstacles; obstacleIndex += 1) {
int sizeIndex = Random.Range (0, possibleSizes.Length);
Vector2Int regionSize = possibleSizes [sizeIndex];
List<Vector2Int> region = FindFreeRegion (regionSize);
foreach (Vector2Int coordinate in region) {
this.population [coordinate.x, coordinate.y] = "Obstacle";
}
}
}
public void PopulatePrefabs (int numberOfPrefabs, GameObject[] possiblePrefabs) {
for (int prefabIndex = 0; prefabIndex < numberOfPrefabs; prefabIndex += 1) {
int choiceIndex = Random.Range (0, possiblePrefabs.Length);
GameObject prefab = possiblePrefabs [choiceIndex];
List<Vector2Int> region = FindFreeRegion (new Vector2Int(1, 1));
this.population [region[0].x, region[0].y] = prefab.name;
this.name2Prefab [prefab.name] = prefab;
}
}
private List<Vector2Int> FindFreeRegion (Vector2Int sizeInTiles) {
List<Vector2Int> region = new List<Vector2Int>();
do {
region.Clear();
Vector2Int centerTile = new Vector2Int(UnityEngine.Random.Range(2, 18 - 3), UnityEngine.Random.Range(2, 10 - 3));
region.Add(centerTile);
int initialXCoordinate = (centerTile.x - (int)Mathf.Floor(sizeInTiles.x / 2));
int initialYCoordinate = (centerTile.y - (int)Mathf.Floor(sizeInTiles.y / 2));
for (int xCoordinate = initialXCoordinate; xCoordinate < initialXCoordinate + sizeInTiles.x; xCoordinate += 1) {
for (int yCoordinate = initialYCoordinate; yCoordinate < initialYCoordinate + sizeInTiles.y; yCoordinate += 1) {
region.Add(new Vector2Int(xCoordinate, yCoordinate));
}
}
} while(!IsFree (region));
return region;
}
private bool IsFree (List<Vector2Int> region) {
foreach (Vector2Int tile in region) {
if (this.population [tile.x, tile.y] != "") {
return false;
}
}
return true;
}
public void AddPopulationToTilemap (Tilemap tilemap, TileBase obstacleTile) {
for (int xIndex = 0; xIndex < 18; xIndex += 1) {
for (int yIndex = 0; yIndex < 10; yIndex += 1) {
if (this.population [xIndex, yIndex] == "Obstacle") {
tilemap.SetTile (new Vector3Int (xIndex - 9, yIndex - 5, 0), obstacleTile);
} else if (this.population [xIndex, yIndex] != "" && this.population [xIndex, yIndex] != "Player") {
GameObject prefab = GameObject.Instantiate (this.name2Prefab[this.population [xIndex, yIndex]]);
prefab.transform.position = new Vector2 (xIndex - 9 + 0.5f, yIndex - 5 + 0.5f);
}
}
}
}
}
any help would be awesome even if you can point me in the direction to a how to.
Nice procedural dungeon generator! Just as a suggestion, could you cache the first room at the beginning when you are generating the dungeon? Then you can grab the initialRoomForPlayerSpawn coordinates/ position as a reference point for the character placement.
Room initialRoomForPlayerSpawn = null;
while (roomsToCreate.Count > 0 && createdRooms.Count < numberOfRooms) {
Room currentRoom = roomsToCreate.Dequeue ();
this.rooms [currentRoom.roomCoordinate.x, currentRoom.roomCoordinate.y] = currentRoom;
createdRooms.Add (currentRoom);
AddNeighbors (currentRoom, roomsToCreate);
/* Cache First Room */
if(createdRooms != null && createdRooms.Count <= 1) {
initialRoomForPlayerSpawn = currentRoom;
}
}

My Program Creates 1 Ball not 2

I made a program that creates a frame and then creates 2 balls and moves them around seperately, my problem is that somehow the first or second ball is getting the coordinates of the other, and therefore are being painted on each other, sorry for the bad indentation this is my first time posting a question .
Main Class:
public class Game extends JPanel {
Ball ball01 = new Ball();
Ball ball02 = new Ball();
int ball01x = 0,ball01y = 0,ball02x = 0,ball02y = 0;
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.fillOval(ball01x, ball01y, 10, 10);
g2d.setColor(Color.RED);
g2d.fillOval(ball02x, ball02y, 10, 10);
}
public static void main(String[] args) throws InterruptedException {
JFrame frame = new JFrame("Sample Frame");
Game game = new Game();
frame.add(game);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
game.createBalls();
while (true) {
game.getCoords();
game.updateBalls();
game.repaint();
System.out.println("Ball01 x: " + game.ball01x + " Ball02 x " + game.ball02x);
Thread.sleep(10);
}
}
public void getCoords(){
ball01x = ball01.getX();
ball01y = ball01.getY();
ball02x = ball02.getX();
ball02y = ball02.getY();
}
public void createBalls(){
ball01.create(300,300);
ball02.create(50,20);
}
public void updateBalls(){
ball01.Ball();
ball02.Ball();
}
}
Ball Class:
public class Ball{
private static int x;
private static int y;
private static int xSize = 30;
private static int ySize = 30;
static boolean xright = true,ydown = true;
static boolean grow = false;
public void Ball(){
this.moveBall();
this.ballSize();
}
public void create(int startX, int startY){
this.x = startX;
this.y = startY;
}
private void moveBall() {
if(this.x >= 370){
xright = false;
}
if(this.x <= 0){
xright = true;
}
if(this.y >= 370){
ydown = false;
}
if(this.y < 0){
ydown = true;
}
if(xright == true){
this.x = this.x + 1;
}else if (xright == false){
this.x = this.x - 1;
}
if(ydown == true){
this.y = this.y + 1;
}else if (ydown == false){
this.y = this.y - 1;
}
}
private void ballSize(){
if (xSize <= 5 && ySize <= 5){
grow = true;
}else if (xSize >= 10 && ySize >= 10){
grow = false;
}
if (grow == true){
xSize = xSize + 1;
ySize = ySize + 1;
//System.out.println("Debug");
}else if (grow == false){
xSize--;
ySize--;
//System.out.println("Debug");
}
}
public int getX(){
return x;
}
public int getY(){
return y;
}
}

Check manually a JMenuItem in a JPopUpMenu?

I have a JPopUpMenu with several JCheckBoxMenuItem's on it.
Actually what I would like to do is basicly to select an item of the JPopUpMenu with a specific index.
For exemple, a method like myPopUpMenu.setSelected(2), which would select "Algérie" in my JPopUpMenu.
The problem is that I don't know any method which would allow me to check an item manually...
Here's the code of my JPopUpMenu :
MainVue.java:
public class MainVue extends JFrame implements ActionListener {
private static final JScrollPopupMenu menuProduit = new JScrollPopupMenu();
private static final JScrollPopupMenu menuPays = new JScrollPopupMenu();
private static List<String> listeFiltres = new ArrayList<String>();
private String listeDeFiltres;
private String[] tableauFiltrePermanent;
private String listeFiltrePermanent;
private String[] tableauPays = { "Autres", "Afrique du sud", "Algérie", "Allemagne", "Arabie Saoudite", "Argentine",
"Australie", "Bangladesh", "Belgique", "Brésil", "Bulgarie", "Canada", "Chine", "Corée du sud", "Egypte",
"Emirats-Arabes Unis", "Espagne", "Etats-Unis", "Ethiopie", "Europe", "France", "Hongrie", "Inde",
"Indonésie", "Irak", "Iran", "Israél", "Italie", "Japon", "Jordanie", "Kazakhstan", "Koweit", "Liban",
"Libye", "Malaisie", "Maroc", "Mexique", "Monde", "Oman", "Pakistan", "Pays-Bas", "Philippines", "Poligne",
"Portugal", "Qatar", "République tchéque", "Roumanie", "Russie", "Taïwan", "Tunisie", "Turquie",
"Ukraine" };
private String[] tableauProduit = { "Blé", "Colza", "Mais", "Orge", "Orge de Brasserie", "Palme", "Soja",
"Tournesol", "Tourteaux De Colza", "Tourteaux de Soja", "Huile de Soja", "Huile De Colza" };
private List<JCheckBoxMenuItem> listJCBProduit = new ArrayList<JCheckBoxMenuItem>();
private List<JCheckBoxMenuItem> listJCBPays = new ArrayList<JCheckBoxMenuItem>();
public static PropertiesConfiguration prop;
public MainVue(Modele modele, Controleur controleur) throws ClassNotFoundException, SQLException, IOException {
prop = new PropertiesConfiguration("config.properties");
for (int i = 0; i < tableauProduit.length; i++) {
listJCBProduit.add(new JCheckBoxMenuItem(tableauProduit[i]));
}
for (int j = 0; j < listJCBProduit.size(); j++) {
JCheckBoxMenuItem produitActuel = listJCBProduit.get(j);
menuProduit.add(produitActuel);
produitActuel.addActionListener(new OpenAction(menuProduit, boutonProduit));
}
for (int i = 0; i < tableauPays.length; i++) {
listJCBPays.add(new JCheckBoxMenuItem(tableauPays[i]));
}
for (int j = 0; j < listJCBPays.size(); j++) {
JCheckBoxMenuItem paysActuel = listJCBPays.get(j);
menuPays.add(paysActuel);
paysActuel.addActionListener(new OpenAction(menuPays, boutonPays));
}
listeDeFiltres = "";
for (int p = 0; p < listeFiltres.size(); p++) {
String filtreActuel = listeFiltres.get(p);
if (listeDeFiltres == "") {
listeDeFiltres += filtreActuel;
} else {
listeDeFiltres += "," + filtreActuel;
}
}
prop.setProperty("listeFiltres", listeDeFiltres);
}
}
Here's the JScrollPopUpMenu component :
JScrollPopUpMenu.java:
package fr.views;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import javax.swing.JPopupMenu;
import javax.swing.JScrollBar;
public class JScrollPopupMenu extends JPopupMenu {
protected int maximumVisibleRows = 10;
public JScrollPopupMenu() {
this(null);
}
public JScrollPopupMenu(String label) {
super(label);
setLayout(new ScrollPopupMenuLayout());
super.add(getScrollBar());
addMouseWheelListener(new MouseWheelListener() {
#Override public void mouseWheelMoved(MouseWheelEvent event) {
JScrollBar scrollBar = getScrollBar();
int amount = (event.getScrollType() == MouseWheelEvent.WHEEL_UNIT_SCROLL)
? event.getUnitsToScroll() * scrollBar.getUnitIncrement()
: (event.getWheelRotation() < 0 ? -1 : 1) * scrollBar.getBlockIncrement();
scrollBar.setValue(scrollBar.getValue() + amount);
event.consume();
}
});
}
private JScrollBar popupScrollBar;
protected JScrollBar getScrollBar() {
if(popupScrollBar == null) {
popupScrollBar = new JScrollBar(JScrollBar.VERTICAL);
popupScrollBar.addAdjustmentListener(new AdjustmentListener() {
#Override public void adjustmentValueChanged(AdjustmentEvent e) {
doLayout();
repaint();
}
});
popupScrollBar.setVisible(false);
}
return popupScrollBar;
}
public int getMaximumVisibleRows() {
return maximumVisibleRows;
}
public void setMaximumVisibleRows(int maximumVisibleRows) {
this.maximumVisibleRows = maximumVisibleRows;
}
public void paintChildren(Graphics g){
Insets insets = getInsets();
g.clipRect(insets.left, insets.top, getWidth(), getHeight() - insets.top - insets.bottom);
super.paintChildren(g);
}
protected void addImpl(Component comp, Object constraints, int index) {
super.addImpl(comp, constraints, index);
if(maximumVisibleRows < getComponentCount()-1) {
getScrollBar().setVisible(true);
}
}
public void remove(int index) {
// can't remove the scrollbar
++index;
super.remove(index);
if(maximumVisibleRows >= getComponentCount()-1) {
getScrollBar().setVisible(false);
}
}
public void show(Component invoker, int x, int y){
JScrollBar scrollBar = getScrollBar();
if(scrollBar.isVisible()){
int extent = 0;
int max = 0;
int i = 0;
int unit = -1;
int width = 0;
for(Component comp : getComponents()) {
if(!(comp instanceof JScrollBar)) {
Dimension preferredSize = comp.getPreferredSize();
width = Math.max(width, preferredSize.width);
if(unit < 0){
unit = preferredSize.height;
}
if(i++ < maximumVisibleRows) {
extent += preferredSize.height;
}
max += preferredSize.height;
}
}
Insets insets = getInsets();
int widthMargin = insets.left + insets.right;
int heightMargin = insets.top + insets.bottom;
scrollBar.setUnitIncrement(unit);
scrollBar.setBlockIncrement(extent);
scrollBar.setValues(0, heightMargin + extent, 0, heightMargin + max);
width += scrollBar.getPreferredSize().width + widthMargin;
int height = heightMargin + extent;
setPopupSize(new Dimension(width, height));
}
super.show(invoker, x, y);
}
protected static class ScrollPopupMenuLayout implements LayoutManager{
#Override public void addLayoutComponent(String name, Component comp) {}
#Override public void removeLayoutComponent(Component comp) {}
#Override public Dimension preferredLayoutSize(Container parent) {
int visibleAmount = Integer.MAX_VALUE;
Dimension dim = new Dimension();
for(Component comp :parent.getComponents()){
if(comp.isVisible()) {
if(comp instanceof JScrollBar){
JScrollBar scrollBar = (JScrollBar) comp;
visibleAmount = scrollBar.getVisibleAmount();
}
else {
Dimension pref = comp.getPreferredSize();
dim.width = Math.max(dim.width, pref.width);
dim.height += pref.height;
}
}
}
Insets insets = parent.getInsets();
dim.height = Math.min(dim.height + insets.top + insets.bottom, visibleAmount);
return dim;
}
#Override public Dimension minimumLayoutSize(Container parent) {
int visibleAmount = Integer.MAX_VALUE;
Dimension dim = new Dimension();
for(Component comp : parent.getComponents()) {
if(comp.isVisible()){
if(comp instanceof JScrollBar) {
JScrollBar scrollBar = (JScrollBar) comp;
visibleAmount = scrollBar.getVisibleAmount();
}
else {
Dimension min = comp.getMinimumSize();
dim.width = Math.max(dim.width, min.width);
dim.height += min.height;
}
}
}
Insets insets = parent.getInsets();
dim.height = Math.min(dim.height + insets.top + insets.bottom, visibleAmount);
return dim;
}
#Override public void layoutContainer(Container parent) {
Insets insets = parent.getInsets();
int width = parent.getWidth() - insets.left - insets.right;
int height = parent.getHeight() - insets.top - insets.bottom;
int x = insets.left;
int y = insets.top;
int position = 0;
for(Component comp : parent.getComponents()) {
if((comp instanceof JScrollBar) && comp.isVisible()) {
JScrollBar scrollBar = (JScrollBar) comp;
Dimension dim = scrollBar.getPreferredSize();
scrollBar.setBounds(x + width-dim.width, y, dim.width, height);
width -= dim.width;
position = scrollBar.getValue();
}
}
y -= position;
for(Component comp : parent.getComponents()) {
if(!(comp instanceof JScrollBar) && comp.isVisible()) {
Dimension pref = comp.getPreferredSize();
comp.setBounds(x, y, width, pref.height);
y += pref.height;
}
}
}
}
}
Thanks in advance for any help !
The index which you get from getIndex() method use as follows. You are adding ScrollBar in your JScrollPopupMenu at 0 index. So to remove casting error update your code as follow.
int index = getIndex("name");
((JCheckBoxMenuItem)menuProduit.getComponentAtIndex(index+1)).setState(true);

How do I incorporate a scroll bar after a few instances of actionListener?

Ok. so I'm writing a grocery checkout system code and on the right side of the frame, I'm displaying a Jpanel with Labels. Every time I click the 'Scan' button, I add a new label into the JPanel so that everytime I click, it displays the output. However, I can only fit so many entries in my window, how do I incorporate a scroll bar so that I can scroll through the groceries?
I tried inputting a scroll bar EAST with a BorderLayout and all the labels CENTER, however, everytime I click the button, it only reprints it at the same exact spot instead of top/down so that I can scroll. (Please, bare in mind that this is a very very rough draft. I'll be incorporating the logic beneath the code once I get the nitty-gritty with the GUI)
Here's my code:
public class Checkout extends JFrame implements ActionListener
{
private int numOfItems = 21;
private Integer[] itemCode = new Integer[numOfItems];
private StringBuffer[] itemDesc = new StringBuffer[numOfItems];
private Double[] unitPrice = new Double[numOfItems];
private Integer[] taxCode = new Integer[numOfItems];
private Integer[] quantity = new Integer[numOfItems];
private Integer[] reorderLevel = new Integer[numOfItems];
private double subTotal, tax, grandTotal;
private JButton scan = new JButton("Scan");
private JButton pay = new JButton("Finish & Pay");
private JButton readFile = new JButton("Read from File");
private JTextField itemNumber = new JTextField(4);
private JTextField itemQuantity = new JTextField(4);
private JLabel displayReceipt = new JLabel();
private JPanel p4;
public Checkout()
{
setValues();
JPanel p2 = new JPanel(new FlowLayout());
p2.add(scan);
p2.add(pay);
p2.add(readFile);
JPanel p1 = new JPanel(new FlowLayout());
p1.add(new JLabel("Item Number:"));
p1.add(itemNumber);
p1.add(new JLabel("Item Quantity:"));
p1.add(itemQuantity);
p1.setBorder(new TitledBorder("Scan Items First. Then Hit 'Finish and Pay'"));
JPanel p3 = new JPanel(new BorderLayout(5, 5));
p3.add(p1, BorderLayout.NORTH);
p3.add(p2, BorderLayout.CENTER);
p4 = new JPanel(new GridLayout(0, 1, 0, 0));
JScrollPane scroll = new JScrollPane(p4);
add(p3, BorderLayout.WEST);
add(p4, BorderLayout.CENTER);
scan.addActionListener(this);
pay.addActionListener(this);
readFile.addActionListener(this);
}
public void setValues()
{
String[] tokens = new String[6];
String[][] multi = new String[numOfItems][6];
try{BufferedReader textReader = new BufferedReader(new FileReader("inventory.txt"));
for(int i = 0; i < numOfItems; i++) // Split the file
{
tokens = textReader.readLine().split("\t");
for(int j = 0; j < tokens.length; j++)
{
multi[i][j] = tokens[j];
}
}
for(int i = 0; i < numOfItems; i++)
{
itemCode[i] = (Integer.parseInt(multi[i][0]));
itemDesc[i] = new StringBuffer(multi[i][1]);
unitPrice[i] = (Double.parseDouble(multi[i][2]));
taxCode[i] = (Integer.parseInt(multi[i][3]));
quantity[i] = (Integer.parseInt(multi[i][4]));
reorderLevel[i] = (Integer.parseInt(multi[i][5]));
}}
catch(Exception e){}
}
public void setQuantity(int item, int itemCount)
{
for(int i = 0; i < numOfItems; i++)
{
if(itemCode[i].equals(item))
{
quantity[i] = quantity[i] - itemCount;
subTotal = itemCount * unitPrice[i];
if(quantity[i] < reorderLevel[i])
itemDesc[i] = itemDesc[i].append("**MARKED FOR REORDER**\t");
}
}
}
public String toString()
{
System.out.println("CUST TICKET");
//for(int i = 0; i < numOfItems; i++)
//return (itemCode[i] + "\t" + itemDesc[i] + "\t" + unitPrice[i] + "\t" + taxCode[i] + "\t" + quantity[i] + "\t" + reorderLevel[i]);
System.out.println("SUBTOTAL\t" + subTotal);
System.out.println("TAX\t\t" + tax);
System.out.println("GRAND TOTAL\t" + grandTotal);
return "";
}
public static void main(String[] args) throws Exception
{
Checkout frame = new Checkout(); // Frame layout
frame.setSize(600, 135);
frame.setTitle("Computer Science 202: Final Project - Supermarket Checkout System");
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
/*Scanner input = new Scanner(System.in);
System.out.print("Please enter item number: ");
Integer itemNumber = Integer.parseInt(input.nextLine());
System.out.print("Please enter quantity: ");
Integer quantity = Integer.parseInt(input.nextLine());
System.out.println(frame.stockCheck(itemNumber, quantity));*/
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == scan)
{
try
{
Integer quantityOrdered = 1;
Integer item = Integer.parseInt(itemNumber.getText());
quantityOrdered = Integer.parseInt(itemQuantity.getText());
for(int i = 0; i < numOfItems; i++)
{
if(itemCode[i].equals(item))
{
if(quantityOrdered > 1)
{
p4.add(new JLabel(itemDesc[i] + "" + unitPrice[i]));
p4.add(new JLabel(quantityOrdered + " # " + unitPrice[i]));
p4.revalidate();
p4.repaint();
}
else
{
p4.add(new JLabel(itemDesc[i] + "\t" + unitPrice[i]));
p4.revalidate();
p4.repaint();
}
}
}
setQuantity(item, quantityOrdered);
}
catch(Exception ex){}
}
else if(e.getSource() == pay)
{
displayReceipt.setText(toString());
}
else if(e.getSource() == readFile)
{
System.out.println("READ FILE");
}
}
}