How to let Stage show the pictures after timer - timer

After I click start button, my program will not show the second scene and thread , until the thread is finish. And the thread will not run correctly(grass didn't increase).
public class test111 extends Application {
private static int grass_i=130;
private static int grass_j=200;
private static int[][] map = new int[grass_i][grass_j];//草地資料grassdata
private static int totalgrass; //grass total number
private static int totalgrassrest; //grass rest number
private static int months=1; //月
private Timer timer;//時間
//GUI
Scene menusc ;
//START後的視窗
BorderPane bpAll = new BorderPane();
Pane playView = new Pane();
Scene mainsc = new Scene(bpAll);
//草
Image littlegrassImg = new Image(getClass().getResourceAsStream("map_littlegrass.png"));
Image midiumgrassImg = new Image(getClass().getResourceAsStream("map_midiumgrass.png"));
Image muchgrassImg = new Image(getClass().getResourceAsStream("map_muchgrass.png"));
Rectangle2D[][] viewportRect = new Rectangle2D[130][200];
private static ImageView[][] mapView = new ImageView[130][200];
//時間
#Override
public void start(Stage primaryStage) throws InterruptedException {
//MENU
Pane menu = new Pane();
menusc = new Scene(menu);
menu.setPrefSize(1000, 800);
Image MenuImg = new Image(getClass().getResourceAsStream("Menu_title.jpg"));
Image StartImg = new Image(getClass().getResourceAsStream("Start.jpg"));
menu.getChildren().add(new ImageView(MenuImg));
Button StartBt = new Button();
StartBt.setPrefSize(450, 150);
StartBt.setGraphic(new ImageView(StartImg));
StartBt.setMaxSize(450, 150);
StartBt.setLayoutX(300);
StartBt.setLayoutY(600);
menu.getChildren().addAll(new ImageView(MenuImg),StartBt);
primaryStage.setMinHeight(800);//固定視窗大小fix the size of Stage
primaryStage.setMinWidth(1000);//固定視窗大小fix the size of Stage
primaryStage.setMaxHeight(800);//固定視窗大小fix the size of Stage
primaryStage.setMaxWidth(1000);//固定視窗大小fix the size of Stage
primaryStage.setScene(menusc);
primaryStage.setTitle("Hypnos' yard");
//START
StartBt.setOnAction(e->{
BorderPane bp2 = bp2();
menusc = new Scene(bp2);
primaryStage.setScene(menusc);
});
primaryStage.show();
}
public BorderPane bp2(){
playView = playView();
bpAll = new BorderPane();
bpAll.setPrefSize(1000, 800);
playView.setPrefSize(1000, 650); //庭院
bpAll.setTop(playView);
Random ran = new Random();
totalgrass = (ran.nextInt(50)*1000)+48000;
totalgrassrest = totalgrass;
grasscreate();
//設定初始草地construct the initial grass
grassGraphicsLoading(); //loading grass pictures
return bpAll;
}
public Pane playView(){
playView = new Pane();
while(months<12){
timer = new Timer();
TimerTask task = new TimerTask(){
public void run(){
month();
}
};//after program executing 0.2s, a month past
timer.schedule(task, 200);
try {
Thread.sleep(200);
}
catch(InterruptedException e6) {
}
timer.cancel();
}
return playView;
}
//月month
protected void month(){
if(months<13){
grassgrow(totalgrass*2);//grass growth
Platform.runLater(new Runnable(){
#Override
public void run(){
grassGraphicsLoading();
}
});
months++;
}
}
//把草地資料帶入圖形loading grass pictures
private void grassGraphicsLoading(){
for (int i = 0; i < grass_i; i++) { // 設定imageView的圖形和位置
for (int j = 0; j < grass_j; j++) {
viewportRect[i][j] = new Rectangle2D(j * 5, i * 5, 5, 5);
if (170 <= j && j <= grass_j - 1) {
mapView[i][j] = new ImageView(muchgrassImg);
} else if (140 <= j && j < 170) {
mapView[i][j] = new ImageView(muchgrassImg);
} else {
if (map[i][j] == 0) {
mapView[i][j] = new ImageView(littlegrassImg);
} else if (map[i][j] == 1 || map[i][j] == 2) {
mapView[i][j] = new ImageView(midiumgrassImg);
} else {
mapView[i][j] = new ImageView(muchgrassImg);
}
}
playView.getChildren().add(mapView[i][j]);
mapView[i][j].setViewport(viewportRect[i][j]);
mapView[i][j].setX(j * 5);
mapView[i][j].setY(i * 5);
}
}
}
public static void main(String[] args) {
launch(args);
}
// 每經過30天(一個月)草地+1grassgrowth
protected void grassgrow(int sum) {
for (int i = 0; i < grass_i; i++) {
for (int j = grass_j - 1; j >= 0; j--) {
if (map[i][j] < 4 && totalgrass <sum) {
map[i][j] += 1;
totalgrass++;
}
if (totalgrass == 104000||totalgrass ==sum) {
break;
}
}
}
}
//建構草地construct grass
protected void grasscreate() {
for (int j = grass_j - 1; j >= 0; j--) {
for (int i = grass_i - 1; i >= 0; i--) {
if (170 <= j && j <= grass_j - 1) {
map[i][j] = 0;
} else if (140 <= j && j < 170) {
map[i][j] = 4;
totalgrassrest -= 4;
} else if (totalgrassrest <= 0) {
map[i][j] = 0;
} else if (4 * (j + 1) * grass_i <= totalgrassrest) {
map[i][j] = 4;
totalgrassrest -= 4;
} else if (totalgrassrest < 4) {
map[i][j] = totalgrassrest;
totalgrassrest = 0;
} else {
map[i][j] = rancreate();
totalgrassrest -= map[i][j];
}
}
}
totalgrass -= totalgrassrest;
totalgrassrest = 0;
}
// 一格(5X5)內草地數量隨機1-4平米z there is 1-4 grass inside a rectangle
private int rancreate() {
Random ran = new Random();
int grass = ran.nextInt(5);
return grass;
}
}`

Related

Need help on solving this Arrays problem using java

Make an array of integer (score) with 10 members. Randomize the
content with value between 0-100. For each of the member of array,
visualize the value using “-” for each ten. For example: score[0] = 55 will be visualized as “-----" (Using Java).
public class w9lab1 {
public static void main(String args[]) {
double[] temperature = new double[7];
for (int i = 0; i < 7; i++) {
temperature[i] = Math.random()*100;
}
for (int i = 0; i < 7; i++) {
System.out.println(temperature[i]);
}
double totalTemperature = 0;
for (int i = 0; i < 7 ; i++) {
totalTemperature += temperature[i];
}
double maxTemperature = temperature[0];
for (int i = 1; i < 7; i++){
if (temperature[i] > maxTemperature){
maxTemperature = temperature[i];
}
}
System.out.println("Temperatur maximum adalah " + maxTemperature);
}
}
import java.util.Random;
import java.util.Arrays;
public class w9lab1 {
public static void main(String[] args) {
Random random = new Random();
int[] score = new int[10];
for (int i = 0; i < score.length; i++) {
score[i] = random.nextInt(101);
for (int n = 1; n <= score[i] / 10; n++)
System.out.print('-');
System.out.println();
}
System.out.println(Arrays.toString(score));
}
}

unity array having 50 gameobjects but displays only 10 object

i have build a level menu with levels, i also created and empty array (GameObject[ ] lvlBut; )to store the level icons instantiated, but only 10 level icons are displayed on the screen where as i have 50 levels. for some reason its only taking 10 levels and i don’t t know where i have gone wrong. any suggestions?
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UI;
using TMPro;
public class LevelSelector : MonoBehaviour{
public GameObject levelHolder;
public GameObject levelIcon;
public GameObject thisCanvas;
public int numberOfLevels = 50;
public Vector2 iconSpacing;
private Rect panelDimensions;
private Rect iconDimensions;
private int amountPerPage;
private int currentLevelCount;
int levelsUnlocked;
GameObject[] lvlBut;
void Start()
{
panelDimensions = levelHolder.GetComponent<RectTransform>().rect;
iconDimensions = levelIcon.GetComponent<RectTransform>().rect;
int maxInARow = Mathf.FloorToInt((panelDimensions.width + iconSpacing.x) / (iconDimensions.width + iconSpacing.x));
int maxInACol = Mathf.FloorToInt((panelDimensions.height + iconSpacing.y) / (iconDimensions.height + iconSpacing.y));
amountPerPage = maxInARow * maxInACol;
int totalPages = Mathf.CeilToInt((float)numberOfLevels / amountPerPage);
LoadPanels(totalPages);
}
void LoadPanels(int numberOfPanels)
{
GameObject panelClone = Instantiate(levelHolder) as GameObject;
PageSwiper swiper = levelHolder.AddComponent<PageSwiper>();
swiper.totalPages = numberOfPanels;
for (int i = 1; i <= numberOfPanels; i++)
{
GameObject panel = Instantiate(panelClone) as GameObject;
panel.transform.SetParent(thisCanvas.transform, false);
panel.transform.SetParent(levelHolder.transform);
panel.name = "Page-" + i;
panel.GetComponent<RectTransform>().localPosition = new Vector2(panelDimensions.width * (i - 1), 0);
SetUpGrid(panel);
int numberOfIcons = i == numberOfPanels ? numberOfLevels - currentLevelCount : amountPerPage;
LoadIcons(numberOfIcons, panel);
}
Destroy(panelClone);
}
void SetUpGrid(GameObject panel)
{
GridLayoutGroup grid = panel.AddComponent<GridLayoutGroup>();
grid.cellSize = new Vector2(iconDimensions.width, iconDimensions.height);
grid.childAlignment = TextAnchor.MiddleCenter;
grid.spacing = iconSpacing;
}
void LoadIcons(int numberOfIcons, GameObject parentObject)
{
for (int i = 1; i <= numberOfIcons; i++)
{
currentLevelCount++;
GameObject icon = Instantiate(levelIcon) as GameObject;
icon.transform.SetParent(thisCanvas.transform, false);
icon.transform.SetParent(parentObject.transform);
icon.name = "Level " + i;
icon.GetComponentInChildren<TextMeshProUGUI>().SetText(currentLevelCount.ToString());
}
lvlBut = GameObject.FindGameObjectsWithTag("LevelButton");
levelsUnlocked = PlayerPrefs.GetInt("levelsUnlocked", 1);
for (int i = 0; i < lvlBut.Length; i++)
{
lvlBut[i].GetComponentInChildren<Button>().interactable = false;
}
for (int i = 0; i < levelsUnlocked; i++)
{
lvlBut[i].GetComponentInChildren<Button>().interactable = true;
}
}
}

Boolean fuction to all the elements in an array processing 3.0

I'm trying to make a program which shows some circles, and when the user puts all the circles in one place, the background changes. The problem I have is that when one circle is moved to that place the background changes, but I need that to happened once all the elements of the array had changed position..
DragMe[] drags = new DragMe[15];
PGraphics topLayer;
PGraphics toperLayer;
color backgr;
void setup() {
size(500, 500);
for (int i = 0; i < drags.length; i++) {
drags[i] = new DragMe();
}
topLayer = createGraphics(width, height, g.getClass().getName());
}
void draw() {
background(backgr);
{
topLayer.beginDraw();
topLayer.noFill();
topLayer.stroke(0 );
if (mousePressed ==true) {
topLayer.line( pmouseX, pmouseY, mouseX, mouseY );
topLayer.endDraw();
}
image( topLayer, 0, 0 );
}
for (int i = 0; i < drags.length; i++) {
drags[i].display();
drags[i].update();
}
for (int i = 0; i < drags.length; i++) {
drags[i].fondo();
}
{
ellipse(width/2.5, height/2.5, 110, 110);
fill(255);
}
}
void mousePressed() {
for (int i = 0; i < drags.length; i++) {
if (!drags[i].isOver())
drags[i].dontMove = true;
drags[i].offset_x = mouseX - drags[i].pos_x;
drags[i].offset_y = mouseY - drags[i].pos_y;
}
}
void mouseReleased() {
for (int i = 0; i < drags.length; i++) {
drags[i].locked = false;
drags[i].dontMove = false;
}
}
class DragMe {
float pos_x, pos_y, SIZE = 25;
float prev_x, prev_y;
boolean locked;
boolean dontMove;
boolean all;
color c = color (255);
float offset_x, offset_y;
DragMe() {
pos_x = random(width-SIZE);
pos_y = random(height-SIZE);
}
void update() {
if (isOver() && !locked && !dontMove || locked && !dontMove )
c = color (255);
else
c = color (255);
if (isClicked()) {
locked = true;
}
if (isIn()) {
locked = false;
all = true;
}
if (locked && !dontMove) {
pos_x = mouseX - offset_x;
pos_y = mouseY - offset_y;
}
}
void display() {
fill(c);
ellipse(pos_x, pos_y, SIZE, SIZE);
ellipseMode(CORNER);
noStroke();
}
boolean isOver() {
float right_x = pos_x + SIZE;
float bottom_y = pos_y + SIZE;
return mouseX >= pos_x && mouseX <= right_x &&
mouseY >= pos_y && mouseY <= bottom_y;
}
boolean isClicked() {
return isOver() && mousePressed && !dontMove;
}
boolean isIn() {
float right_x = pos_x + SIZE;
float bottom_y = pos_y + SIZE;
return right_x >= width/2.5 + SIZE && right_x <= width/2.5 + 100 &&
bottom_y >= height/2.5 + SIZE && bottom_y <= height/2.5 + 100;
}
void fondo() {
if (all == true)
backgr= 255;
}
}
You have 15 instances of DragMe.
Each of those instances contains a variable named all.
When one instance's all is true, you set the background to white.
Specifically, this function:
void fondo() {
if (all == true)
backgr= 255;
}
Which you call from draw():
for (int i = 0; i < drags.length; i++) {
drags[i].fondo();
}
Instead, you need to check every instance's all variable, and only change the background if they are all true (in other words, if none of them are false):
boolean allIn = true;
for (int i = 0; i < drags.length; i++) {
if (!drags[i].all) {
allIn = false;
}
}
if (allIn) {
backgr= 255;
}
For future questions, please try to make sure your code is formatted. It might also be a good idea to use better variable names- naming a variable all is a bit hard to talk about. Maybe something like isInsideWhiteCircle would be better.

WPF: Create XpsDocument Pagination

I am trying to create a Paginator that will in turn create an XpsDocument that I can preview with the and then print. I have the following code that I found on the web but do not understand how it is working.
The issue I am having is that if I run this as is, the pages are generated successfully. If I comment out the lines within OnRender() that generate the actual values of data (all the lines after Random...) I get pages that are about one row high and no text on them but they appear to be the correct length. What is it that is keeping the values of "Row Number" & "Column i" from being shown?
I have included 2 screen shots to illustrate.
public class TaxCodePrintPaginator : DocumentPaginator
{
private int _RowsPerPage;
private Size _PageSize;
private int _Rows;
private List<TaxCode> _dataList;
public TaxCodePrintPaginator(List<TaxCode> dt, int rows, Size pageSize)
{
_dataList = dt;
_Rows = rows;
PageSize = pageSize;
}
public override DocumentPage GetPage(int pageNumber)
{
int currentRow = _RowsPerPage * pageNumber;
var page = new PageElement(currentRow, Math.Min(_RowsPerPage, _Rows - currentRow))
{
Width = PageSize.Width,
Height = PageSize.Height
};
page.Arrange(new Rect(new Point(0, 0), PageSize));
return new DocumentPage(page);
}
public override bool IsPageCountValid
{ get { return true; } }
public override int PageCount
{ get { return (int)Math.Ceiling(_Rows / (double)_RowsPerPage); } }
public override Size PageSize
{
get { return _PageSize; }
set
{
_PageSize = value;
_RowsPerPage = 40;
//Can't print anything if you can't fit a row on a page
Debug.Assert(_RowsPerPage > 0);
}
}
public override IDocumentPaginatorSource Source
{ get { return null; } }
}
public class PageElement : UserControl
{
private const int PageMargin = 75;
private const int HeaderHeight = 25;
private const int LineHeight = 20;
private const int ColumnWidth = 140;
private int _CurrentRow;
private int _Rows;
public PageElement(int currentRow, int rows)
{
Margin = new Thickness(PageMargin);
_CurrentRow = currentRow;
_Rows = rows;
}
private static FormattedText MakeText(string text)
{
return new FormattedText(text, CultureInfo.CurrentCulture,
FlowDirection.LeftToRight,
new Typeface("Tahoma"), 14, Brushes.Black);
}
public static int RowsPerPage(double height)
{
return (int)Math.Floor((height - (2 * PageMargin)
- HeaderHeight) / LineHeight);
}
protected override void OnRender(DrawingContext dc)
{
Point curPoint = new Point(0, 0);
dc.DrawText(MakeText("Row Number"), curPoint);
curPoint.X += ColumnWidth;
for (int i = 1; i < 4; i++)
{
dc.DrawText(MakeText("Column " + i), curPoint);
curPoint.X += ColumnWidth;
}
curPoint.X = 0;
curPoint.Y += LineHeight;
dc.DrawRectangle(Brushes.Black, null, new Rect(curPoint, new Size(Width, 2)));
curPoint.Y += HeaderHeight - LineHeight;
Random numberGen = new Random();
for (int i = _CurrentRow; i < _CurrentRow + _Rows; i++)
{
dc.DrawText(MakeText(i.ToString()), curPoint);
curPoint.X += ColumnWidth;
for (int j = 1; j < 4; j++)
{
dc.DrawText(MakeText(numberGen.Next().ToString()), curPoint);
curPoint.X += ColumnWidth;
}
curPoint.Y += LineHeight;
curPoint.X = 0;
}
}
}
Before
After

All elements change in Arraylist - Processing

My program is a zombie survival game, set in a 2d array of blocks.
I use an arraylist - my first attempt - to store the zombies, and each in tern "checks" if there is a block above, below and around it, to detect it's movement.
I'll post the relevant code here, and upload the sketch folder separately.
ArrayList zombies;
void setup() {
zombies = new ArrayList();
}
void draw() {
for (int i = 0; i < zombies.size(); i++) {
Zombie zombie = (Zombie) zombies.get(i);
zombie.draw();
}
}
void keyPressed() {
if (key == 'z') {
zombies.add(new Zombie());
}
}
class Zombie
{
int posX = 20;
int posY = 10;
boolean fall;
boolean playerOnBlock;
Zombie() {
posX = 10;
posY = 590;
fall = false;
}
void draw() {
grid.blockCheck(posX, posY, 2);
fill(0, 255, 0);
rect(posX, posY, 10, 10);
}
void fall() {
posY += 5;
println("zombiefall"+posY);
}
void move(boolean left, boolean right, boolean above) {
if (left == true && player.playerX < posX) {
posX -= 1;
}
if (right == true && player.playerX > posX) {
posX += 1;
}
}
}
class Grid {
void blockCheck(int x, int y, int e) {
for (int i = 0; i < l; i++)
for (int j = 0; j < h; j++)
{
grid[i][j].aroundMe (x, y, i, j, e);
}
}
}
class Block {
void aroundMe(int _x, int _y, int _i, int _j, int entity) {
int pGX = _x/10;
int pGY = _y/10;
if (entity == 1) {
if (pGY+1 == _j && pGX == _i && state == 4) {
player.fall();
}
if (pGX == _i && pGX-1 <= _i && _y == posY && state == 4) {
leftOfMe = true;
}
else
{
leftOfMe = false;
}
if (pGX+1 == _i && _y == posY && state == 4) {
rightOfMe = true;
}
else
{
rightOfMe = false;
}
if (pGY-1 == _j && _x == posX && state ==4) {
aboveOfMe = true;
}
else
{
aboveOfMe = false;
}
player.controls(leftOfMe, rightOfMe, aboveOfMe);
}
if (entity == 2) {
if (pGY+1 == _j && pGX == _i && state == 4) {
for (int i = 0; i < zombies.size(); i++) {
Zombie zombie = (Zombie) zombies.get(i);
zombie.fall();
}
}
if (pGX == _i && pGX-1 <= _i && _y == posY && state == 4) {
ZleftOfMe = true;
}
else
{
ZleftOfMe = false;
}
if (pGX+1 == _i && _y == posY && state == 4) {
ZrightOfMe = true;
}
else
{
ZrightOfMe = false;
}
if (pGY-1 == _j && _x == posX && state ==4) {
ZaboveOfMe = true;
}
else
{
ZaboveOfMe = false;
}
for (int i = 0; i < zombies.size(); i++) {
Zombie zombie = (Zombie) zombies.get(i);
zombie.move(ZleftOfMe, ZrightOfMe, ZaboveOfMe);
}
}
Sketch is here: http://www.mediafire.com/?u5v3117baym846v
I believe the problem lies in specifying which element of an arraylist I am referring to, as I can observe the issues to be:
All "zombies" fall when one detects that it should fall.
Zombie's speed increases with each additional zombie added - somehow treating all the zombie elements as one zombie object?
This might be a similar issue:
All elements of An ArrayList change when a new one is added?
But I've fiddled with my project and I can't seem to get it working still.
Please don't hesitate to ask for more information on my project. I will be with my computer all evening so should be able to reply quickly. Thanks in advance.
Thanks for your help.
I'm using it like this:
ArrayList <Zombie> zombies = new ArrayList <Zombie>();
-------------------------------------------
void setup(){
zombies = new ArrayList();
-------------------------------------------
void draw(){
for (Zombie z:zombies) {
z.draw();
}
}
-------------------------------------------
void keyPressed() {
if (key == 'z') {
for (int i = 0; i< 1; i++) {
zombies.add(new Zombie(i));
}
}
-------------------------------------------
class Zombie
{
int posX = 20;
int posY = 10;
boolean fall;
boolean playerOnBlock;
int z;
Zombie(int _z) {
posX = 10;
posY = 590;
fall = false;
z = _z;
}
void draw() {
grid.blockCheck(posX, posY, 2);
fill(0, 255, 0);
rect(posX, posY, 10, 10);
}
void fall() {
posY += 5;
println("zombiefall"+posY);
}
void move(boolean left, boolean right, boolean above) {
if (left == true && player.playerX < posX) {
posX -= 1;
}
if (right == true && player.playerX > posX) {
posX += 1;
}
}
}
Here is the idea :)
//use generics to keep it simple. Only Zoombies in this list
ArrayList <Zoombie> samp = new ArrayList <Zoombie>();
void setup() {
//a regular for loop to use the i as id
for (int i = 0; i< 100; i++) {
samp.add(new Zoombie(i));
}
//run just once
noLoop();
}
void draw() {
//a enhanced for, no need for use get()
// z will represent each element in the collection
for (Zoombie z:samp) {
z.d();
}
println("done");
}
// a dummy class ;)
class Zoombie {
int id;
Zoombie (int _id)
{
id =_id;
}
void d()
{
println(id);
}
}

Resources