Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions BackGround.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package ru.gb.jtwo.online.circles;

import java.awt.*;

public class BackGround {

private int changeSpeed;
private int counter;

BackGround(int updateTime){
this.changeSpeed = updateTime;
}

void update(GameCanvas canvas){
counter++;

if ((counter % changeSpeed) == 0) {
Color color = new Color(
(int)(Math.random() * 255),
(int)(Math.random() * 255),
(int)(Math.random() * 255)
);
canvas.setBackground(color);
}

}
}
47 changes: 47 additions & 0 deletions Ball.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package ru.gb.jtwo.online.circles;

import java.awt.*;

public class Ball extends Sprite {
private float vx = 150 + (float)(Math.random() * 200f);
private float vy = 150 + (float)(Math.random() * 200f);
private final Color color = new Color(
(int)(Math.random() * 255),
(int)(Math.random() * 255),
(int)(Math.random() * 255)
);

Ball() {
halfHeight = 20 + (float)(Math.random() * 50f);
halfWidth = halfHeight;
}

@Override
void update(GameCanvas canvas, float deltaTime) {
x += vx * deltaTime;
y += vy * deltaTime;
if (getLeft() < canvas.getLeft()) {
setLeft(canvas.getLeft());
vx = -vx;
}
if (getRight() > canvas.getRight()) {
setRight(canvas.getRight());
vx = -vx;
}
if (getTop() < canvas.getTop()) {
setTop(canvas.getTop());
vy = -vy;
}
if (getBottom() > canvas.getBottom()) {
setBottom(canvas.getBottom());
vy = -vy;
}
}

@Override
void render(GameCanvas canvas, Graphics g) {
g.setColor(color);
g.fillOval((int) getLeft(), (int) getTop(),
(int) getWidth(), (int) getHeight());
}
}
44 changes: 44 additions & 0 deletions GameCanvas.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package ru.gb.jtwo.online.circles;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class GameCanvas extends JPanel {

private MainCircles gameWindow;
private long lastFrameTime;



GameCanvas(MainCircles gameWindow) {
this.gameWindow = gameWindow;
addMouseListener(new MouseController(this));
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

канва умеет рисоваться. канва ничего не знает о периферийных устройствах. нам нужно оставить её в максимально абстрагированном виде, чтобы мочь использовать в другом проекте. В Вашем случае, мы вынуждаем другой проект использовать мышку, хотя там может быть, например, клавиатура

}

@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);

long currentTime = System.nanoTime();
float delta = (currentTime - lastFrameTime) * 0.000000001f;
lastFrameTime = currentTime;

try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}

gameWindow.onDrawPanel(this, g, delta);
repaint();
}

public int getLeft() { return 0; }
public int getRight() { return getWidth() - 1; }
public int getTop() { return 0; }
public int getBottom() { return getHeight() - 1; }
public MainCircles getGameWindow(){return gameWindow;};
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

чую неладное, зачем расприватили?


}
86 changes: 86 additions & 0 deletions MainCircles.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package ru.gb.jtwo.online.circles;

import javax.swing.*;
import java.awt.*;
import java.lang.reflect.Array;

public class MainCircles extends JFrame {
/*
Полностью разобраться с кодом
Прочитать методичку к следующему уроку
Написать класс Бэкграунд, изменяющий цвет канвы в зависимости от времени
* Реализовать добавление новых кружков по клику используя ТОЛЬКО массивы
** Реализовать по клику другой кнопки удаление кружков (никаких эррейЛист)
* */

private static final int POS_X = 600;
private static final int POS_Y = 200;
private static final int WINDOW_WIDTH = 800;
private static final int WINDOW_HEIGHT = 600;
Sprite[] sprites = new Sprite[10];
BackGround backGround = new BackGround(100);
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не было желания сделать его спрайтом?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сделать BackGround спрайтом? Не было) Как это вообще)


public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new MainCircles();
}
});
}

private MainCircles() {
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setBounds(POS_X, POS_Y, WINDOW_WIDTH, WINDOW_HEIGHT);
setTitle("Circles");

GameCanvas gameCanvas = new GameCanvas(this);
add(gameCanvas);
initGame();
setVisible(true);
}

private void initGame() {
for (int i = 0; i < sprites.length; i++) {
sprites[i] = new Ball();
}
}

void onDrawPanel(GameCanvas canvas, Graphics g, float deltaTime) {
update(canvas, deltaTime);
render(canvas, g);
}

private void update(GameCanvas canvas, float deltaTime) {
for (int i = 0; i < sprites.length; i++) {
sprites[i].update(canvas, deltaTime);
}

//Обновление фона
backGround.update(canvas);
}

private void render(GameCanvas canvas, Graphics g) {
for (int i = 0; i < sprites.length; i++) {
sprites[i].render(canvas, g);
}

}

//Удаление шарика из массива
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

на мой взгляд дороговато каждый раз пересоздавать массив и по + и по -... но об этом мы поговорим на уроке.

protected void deleteSprite(){
if (sprites.length > 0) {
Sprite[] newSptites = new Sprite[sprites.length - 1];
System.arraycopy(sprites, 0, newSptites, 0, sprites.length - 1);
sprites = newSptites;
}
}

//Добавление шарика
protected void addSprite(){
Sprite[] newSprites = new Sprite[sprites.length + 1];
System.arraycopy(sprites, 0, newSprites, 0, sprites.length);
newSprites[sprites.length] = new Ball();
sprites = newSprites;
}
}
30 changes: 30 additions & 0 deletions MouseController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package ru.gb.jtwo.online.circles;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

public class MouseController extends MouseAdapter {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

не обязательно было создавать прям свой отдельный контроллер для такой простой задачи, адаптера было достаточно

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Зато в конструкторе канвы на вызов обработчика одна строчка, а не забор

GameCanvas canvas;

public MouseController(GameCanvas canvas) {
super();
this.canvas = canvas;
}
@Override
public void mouseClicked(MouseEvent e) {
super.mouseClicked(e);

if (e.getButton() == MouseEvent.BUTTON1)
{
canvas.getGameWindow().addSprite();
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ах вот оно что... понял зачем расприватили... собственно, это должно было натолкнуть на мысль, что вешать обработчик мыши на канву - плохо, длинноватая цепочка у сигнала получается

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Самое интересное, что в Java 1 преподаватель делает цепочки вот такие

board.getGame().getCurrentPlayer().getPlayerSign()

Из чего делаешь вывод, что так делать и нужно)

}

if (e.getButton() == MouseEvent.BUTTON3)
{
canvas.getGameWindow().deleteSprite();
}

}


}
45 changes: 45 additions & 0 deletions Sprite.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package ru.gb.jtwo.online.circles;

import java.awt.*;

public class Sprite {
protected float x;
protected float y;
protected float halfWidth;
protected float halfHeight;

protected float getLeft() {
return x - halfWidth;
}
protected void setLeft(float left) {
x = left + halfWidth;
}
protected float getRight() {
return x + halfWidth;
}
protected void setRight(float right) {
x = right - halfWidth;
}
protected float getTop() {
return y - halfHeight;
}
protected void setTop(float top) {
y = top + halfHeight;
}
protected float getBottom() {
return y + halfHeight;
}
protected void setBottom(float bottom) {
y = bottom - halfHeight;
}
protected float getWidth() {
return 2f * halfWidth;
}
protected float getHeight() {
return 2f * halfHeight;
}

void update(GameCanvas canvas, float deltaTime) {}
void render(GameCanvas canvas, Graphics g) {}

}