-
Notifications
You must be signed in to change notification settings - Fork 0
Домашняя работа #1 #1
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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); | ||
} | ||
|
||
} | ||
} |
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()); | ||
} | ||
} |
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)); | ||
} | ||
|
||
@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;}; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. чую неладное, зачем расприватили? |
||
|
||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,57 @@ | ||
import java.util.Arrays; | ||
|
||
public class Main { | ||
|
||
public static void main(String[] args) { | ||
String str = "500 3 1 2\n2 3 2 2\n5 6 7 1\n300 3 1 0"; | ||
int summa = 0; | ||
String[][] arr = null; | ||
|
||
try { | ||
arr = strToArray(str); | ||
summa = sum(arr); | ||
System.out.println(summa); | ||
}catch (SizeExeption e){ | ||
System.out.println("Матрица имела неверный размер!"); | ||
}catch (NumberFormatException e){ | ||
System.out.println("Один из элементов не является числом!"); | ||
} | ||
|
||
|
||
} | ||
|
||
public static String[][] strToArray (String source) throws SizeExeption{ | ||
String[][] returnedArray = new String[4][4]; | ||
|
||
String[] array_splitted = source.split("\n"); | ||
|
||
if (array_splitted.length != 4) { | ||
throw new SizeExeption("Matrix size incorrect!"); | ||
} | ||
|
||
for (int i = 0; i < array_splitted.length; i++){ | ||
String[] row = array_splitted[i].split("\\s"); | ||
|
||
if (row.length != 4){ | ||
throw new SizeExeption("Matrix size incorrect!"); | ||
}else{ | ||
for (int j = 0; j < row.length; j++) { | ||
returnedArray[i][j] = row[j]; | ||
} | ||
} | ||
|
||
} | ||
return returnedArray; | ||
} | ||
|
||
public static int sum(String[][] source) throws NumberFormatException{ | ||
int result = 0; | ||
for (int i = 0; i < source.length; i++) { | ||
for (int j = 0; j < source.length; j++) { | ||
result+= Integer.parseInt(source[i][j]); | ||
} | ||
} | ||
|
||
return result / 2; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
public class SizeExeption extends RuntimeException { | ||
public SizeExeption(String message) { | ||
super(message); | ||
} | ||
} |
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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. не было желания сделать его спрайтом? There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
} | ||
|
||
} | ||
|
||
//Удаление шарика из массива | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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; | ||
} | ||
} |
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 { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. не обязательно было создавать прям свой отдельный контроллер для такой простой задачи, адаптера было достаточно There was a problem hiding this comment. Choose a reason for hiding this commentThe 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(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. ах вот оно что... понял зачем расприватили... собственно, это должно было натолкнуть на мысль, что вешать обработчик мыши на канву - плохо, длинноватая цепочка у сигнала получается There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Самое интересное, что в Java 1 преподаватель делает цепочки вот такие
Из чего делаешь вывод, что так делать и нужно) |
||
} | ||
|
||
if (e.getButton() == MouseEvent.BUTTON3) | ||
{ | ||
canvas.getGameWindow().deleteSprite(); | ||
} | ||
|
||
} | ||
|
||
|
||
} |
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) {} | ||
|
||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
канва умеет рисоваться. канва ничего не знает о периферийных устройствах. нам нужно оставить её в максимально абстрагированном виде, чтобы мочь использовать в другом проекте. В Вашем случае, мы вынуждаем другой проект использовать мышку, хотя там может быть, например, клавиатура