Animating a Loop in Flutter - animation

I'm trying to make an animation of sorting algorithms in flutter. So far I've coded the algorithm and managed to get some sort of animation by iterating once at a time instead of the whole sorting process but you have to keep tapping the button to sort, one item at a time. I've been trying to look for a way to animate this process. Here's my code:
import 'package:flutter/material.dart';
import 'dart:math';
List<double> rectHeights = new List<double>();
int n = 2;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Sorting',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
int _selectedIndex = 0;
final _widgetOptions = [
Text('Index 0: Sort'),
Text('Index 1: Shuffle'),
];
#override
void initState() {
super.initState();
Random random = new Random();
for (int i = 0; i < 35; i++) {
double ranNum = random.nextDouble() * 600;
rectHeights.add(ranNum);
}
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: EdgeInsets.all(8.0),
child: Center(
child: Row(
children: rectangles(),
),
),
),
bottomNavigationBar: BottomNavigationBar(
iconSize: 50.0,
items: <BottomNavigationBarItem>[
BottomNavigationBarItem(icon: Icon(Icons.sort), title: Text('Sort', style: TextStyle(fontSize: 20.0),)),
BottomNavigationBarItem(icon: Icon(Icons.shuffle), title: Text('Shuffle', style: TextStyle(fontSize: 20.0),)),
],
currentIndex: _selectedIndex,
fixedColor: Colors.blue,
onTap: _onItemTapped,
),
);
}
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
switch(_selectedIndex) {
case 0:
setState(() {
insertSortOnce(rectHeights, 1);
});
break;
case 1:
setState(() {
shuffle(rectHeights);
n = 2;
});
}
}
}
List<Widget> rectangles() {
List<Widget> rects = new List<Widget>();
for (double height in rectHeights) {
var rect = Padding(
padding: EdgeInsets.symmetric(horizontal: 1.0),
child: Container(
width: 8.0,
height: height,
decoration: BoxDecoration(
shape: BoxShape.rectangle,
color: Colors.blue
),
),
);
rects.add(rect);
}
return rects;
}
void insertSort(values, choice) {
int i, j;
double key, temp;
for (i = 1; i < values.length; i++) {
key = values[i];
j = i - 1;
switch (choice) {
case 1:
while (j >= 0 && key < values[j]) {
temp = values[j];
values[j] = values[j + 1];
values[j + 1] = temp;
j--;
}
break;
case 2:
while (j >= 0 && key > values[j]) {
temp = values[j];
values[j] = values[j + 1];
values[j + 1] = temp;
j--;
}
break;
}
}
}
void insertSortOnce(values, choice) {
int i, j;
double key, temp;
for (i = 1; i < n; i++) {
key = values[i];
j = i - 1;
switch (choice) {
case 1:
while (j >= 0 && key < values[j]) {
temp = values[j];
values[j] = values[j + 1];
values[j + 1] = temp;
j--;
}
break;
case 2:
while (j >= 0 && key > values[j]) {
temp = values[j];
values[j] = values[j + 1];
values[j + 1] = temp;
j--;
}
break;
}
}
n++;
}
List shuffle(List items) {
var random = new Random();
// Go through all elements.
for (var i = items.length - 1; i > 0; i--) {
// Pick a pseudorandom number according to the list length
var n = random.nextInt(i + 1);
var temp = items[i];
items[i] = items[n];
items[n] = temp;
}
return items;
}

You can use a Future function with a short delay, for example (one second) to call the insertSort() after each second till the rectHeights are sorted:
var _notSorted = true ;
var _shiftNotPressed = true ;
Future sortRectangles() async {
while(_notSorted & _shiftPressed) { // You have to provide a condition to know when to stop
await new Future.delayed(const Duration(seconds: 1), () {
insertSortOnce(rectHeights, 1);
}
);
}
}
Then checking for shuffling:
void _onItemTapped(int index) {
setState(() {
_selectedIndex = index;
});
switch(_selectedIndex) {
case 0:
setState(() {
insertSortOnce(rectHeights, 1);
});
break;
case 1:
_shiftNotPressed = false ; // This is what you should add
setState(() {
shuffle(rectHeights);
n = 2;
});
}
}
Then Sorting completion:
void insertSortOnce(values, choice) {
_notSorted = false ; // if it didn't execute the loop it means sorted
int i, j;
double key, temp;
for (i = 1; i < n; i++) {
key = values[i];
j = i - 1;
switch (choice) {
case 1:
while (j >= 0 && key < values[j]) {
_notSorted = true ; //You should figure a more efficient way to do this
temp = values[j];
values[j] = values[j + 1];
values[j + 1] = temp;
j--;
}
break;
case 2:
while (j >= 0 && key > values[j]) {
temp = values[j];
values[j] = values[j + 1];
values[j + 1] = temp;
j--;
}
break;
}
}
n++;
}
Also, You should include in your condition whether the shift button is pressed and to terminate accordingly.

Related

Determine the next point on the Bézier curve based on the straight-line distance from the previous point

I need to keep the same distance between the balls on the Bézier curve. Now I'm using a simple iteration of possible positions on the curve, adding some step amount for each iteration until position with required distance, greater or equal, is found.
It works, but can be resource-intensive when there are a large amount of balls. CodeSandbox
class TestScene extends Phaser.Scene {
create() {
// prettier-ignore
const curve = new Phaser.Curves.QuadraticBezier(
[
55, 310,
40, 0,
250, 310
]
);
const graphicsLayer = this.add.graphics({
lineStyle: {
width: 2,
color: 0x0000ff
}
});
curve.draw(graphicsLayer);
const balls = this.initBalls(6);
this.curve = curve;
this.balls = balls;
}
initBalls(quantity) {
const balls = [];
for (let i = 0; i < quantity; i++) {
const ball = this.add.circle(0, 0, 12, 0x00ff00);
ball.t = 0;
balls.push(ball);
}
return balls;
}
calcNextBallT(previous) {
const ballDiameter = previous.radius * 2;
const curve = this.curve;
const curveLen = curve.getLength();
const previousPos = new Phaser.Math.Vector2(previous);
const previousT = previous.t;
const startingT = (1 / curveLen) * ballDiameter + previousT;
const step = 1 / 1000;
let nextT = startingT;
let nextPos;
let currentDistance = 0;
while (nextT >= 0 && nextT <= 1) {
nextPos = curve.getPointAt(nextT);
currentDistance = previousPos.distance(nextPos);
if (currentDistance >= ballDiameter) {
break;
}
nextT += step;
}
return nextT;
}
update() {
const {
curve,
balls
} = this;
if (!curve || !balls) {
return;
}
const speed = 1;
const curveLen = curve.getLength();
const step = (1 / curveLen) * speed;
balls.forEach((ball, index, array) => {
let nextT = ball.t;
if (index === 0) {
nextT += step;
if (nextT > 1) {
nextT = 0;
}
} else {
const previous = array[index - 1];
nextT = this.calcNextBallT(previous);
}
ball.t = nextT;
ball.copyPosition(curve.getPointAt(nextT));
});
}
}
const game = new Phaser.Game({
width: 320,
height: 320,
powerPreference: 'low-power',
audio: {
noAudio: true
},
scene: [TestScene]
});
<script src="https://unpkg.com/phaser#3.55.2/dist/phaser.min.js"></script>
I think maybe there is a mathematical or algorithmic solution. Something like finding the intersection of a larger circle with a curve, but as I understood it is impossible.
Is there a better way to determine the next point on the Bézier curve based on the straight-line distance from the previous point?
UPDATE 1: A solution using Binary Search, as suggested by #MBo, shows good stability with an average of 5-10 iterations, even with varying curves and ball sizes. CodeSandbox
class TestScene extends Phaser.Scene {
init() {
this.input.on('drag', (pointer, gameObject, dragX, dragY) => {
gameObject.setPosition(dragX, dragY);
});
this.iters = [];
}
create() {
// prettier-ignore
const p0 = this.add.circle(55, 310, 4, 0xffff00),
p1 = this.add.circle(40, 5, 4, 0xffff00),
p2 = this.add.circle(250, 310, 4, 0xffff00);
const curve = new Phaser.Curves.QuadraticBezier(p0, p1, p2);
const graphicsLayer = this.add.graphics({
lineStyle: {
width: 2,
color: 0x0000ff
}
});
curve.draw(graphicsLayer);
const curveDragHandler = () => {
curve.updateArcLengths();
graphicsLayer.clear();
curve.draw(graphicsLayer);
};
[p0, p1, p2].forEach((p) => {
p.setDepth(10).setInteractive();
this.input.setDraggable(p);
p.on('drag', curveDragHandler);
});
const balls = this.initBalls(3, 50);
const text = this.add.text(0, 0, '', {
color: 'yellow'
});
this.curve = curve;
this.balls = balls;
this.text = text;
}
initBalls(quantity, diameter) {
const radius = diameter / 2;
const balls = [];
for (let i = 0; i < quantity; i++) {
const ball = this.add.circle(0, 0, radius, 0x00ff00);
ball.t = 0;
balls.push(ball);
}
return balls;
}
calcNextBallT(previous) {
const ballDiameter = previous.radius * 2;
const curve = this.curve;
const previousPos = new Phaser.Math.Vector2(previous);
const previousT = previous.t;
let nextT = 1;
let lowT = previousT;
let highT = 1;
let iter = 1;
const skip = previousPos.distance(curve.getEndPoint()) <= ballDiameter;
while (lowT <= highT && !skip) {
nextT = lowT + (highT - lowT) / 2;
const nextPos = curve.getPointAt(nextT);
const currentDistance = previousPos.distance(nextPos);
if (fuzzySame(currentDistance, ballDiameter)) {
break;
}
if (currentDistance > ballDiameter) {
highT = nextT;
} else {
lowT = nextT;
}
iter++;
}
if (!skip) {
this.iters.push(iter);
}
return nextT;
}
update() {
const {
curve,
balls
} = this;
if (!curve || !balls) {
return;
}
const speed = 1;
const curveLen = curve.getLength();
const step = (1 / curveLen) * speed;
balls.forEach((ball, index, array) => {
let nextT = ball.t;
if (index === 0) {
nextT += step;
if (nextT > 1) {
const average = findAverage(this.iters).toFixed(2);
const maximum = findMaximum(this.iters);
this.text.setText(`Average: ${average}\nMaximum: ${maximum}`);
this.iters = [];
nextT = 0;
}
} else {
const previous = array[index - 1];
nextT = this.calcNextBallT(previous);
}
ball.t = nextT;
ball.copyPosition(curve.getPointAt(nextT));
});
}
}
const fuzzySame = (num1, num2) => {
const tolerance = 0.2;
return num1 >= num2 - tolerance && num1 <= num2 + tolerance;
};
const findAverage = (array) => {
const len = array.length;
let total = 0;
array.forEach((num) => (total += num));
return total / len;
};
const findMaximum = (array) => {
return [...array].sort((a, b) => b - a)[0];
};
const game = new Phaser.Game({
width: 320,
height: 320,
powerPreference: 'low-power',
audio: {
noAudio: true
},
scene: [TestScene]
});
<script src="https://unpkg.com/phaser#3.55.2/dist/phaser.min.js"></script>
Instead of straight iterations use binary search over t range.
Math solution requires solving equation of 6-th degree (for cubic curve) - there is no closed formula, so one needs to use numerical methods (iterations again)

SWT Treeviewer flickers while scrolling

I have a SWT Treeviewer with custom labelprovider. But it flickers while scrolling even if it is not very large. I think it is because of the paint method. How can I improve performance of the it.
Thank you in advance.
Here is my paint method :
public class TreeLabelProvider extends OwnerDrawLabelProvider {
public ImageData[] getImage(Object element) {
//This function just have if else to return corrent imageData
}
public String getText(Object element) {
//This function also just have if else to return matching text to display
}
#Override
protected void measure(Event event, Object element) {
TreeItem item = (TreeItem) event.item;
Tree tree = item.getParent();
ImageData[] images = getImage(element);
int imgWidht = 0;
int imgHeight = 0;
if (images != null) {
for (int i = 0; i < images.length; i++) {
imgWidht += images[i].width;
int imgHeightTemp = images[i].height;
if (imgHeightTemp > imgHeight) {
imgHeight = imgHeightTemp;
}
}
}
if (!event.gc.isDisposed()) {
Point point = event.gc.textExtent(getText(element));
int rectangleWidth = 0;
rectangleWidth = imgWidht + point.x + 10;
event.setBounds(new Rectangle(event.x, event.y, rectangleWidth, imgHeight));
event.height = imgHeight + 3;
}
}
#Override
protected void paint(Event event, Object element) {
Rectangle bounds = event.getBounds();
int imgWidth = 0;
int x = bounds.width > 0 ? bounds.x + bounds.width : bounds.x;
ImageData[] img = getImage(element);
if (img != null) {
for (int imgIndex = 0; imgIndex < img.length; imgIndex++) {
event.gc.setAntialias(SWT.ON);
// make the image transparent
ImageData ideaData = img[imgIndex];
int whitePixel = ideaData.palette.getPixel(new RGB(255, 255, 255));
ideaData.transparentPixel = whitePixel;
Image transparentIdeaImage = new Image(Display.getDefault(), ideaData);
if (imgIndex > 0) {
event.gc.drawImage(transparentIdeaImage,
x + transparentIdeaImage.getBounds().width - 4, bounds.y + 2);
} else {
event.gc.drawImage(transparentIdeaImage, x - 5, bounds.y + 2);
}
imgWidth += transparentIdeaImage.getBounds().width;
// dispose Image
transparentIdeaImage.dispose();
}
}
event.gc.drawText(getText(element), x + imgWidth + 1, bounds.y + 3, true);
}
#Override
protected void erase(Event event, Object element) {}
}

Convert image data to format needed for gfa

If I have an Image file (png, bmp, or jpg), and I need to get the data for the ZPL GFA tag, how do I do that?
I would like some example in vb.net or C#
please add this class to your project:
public class zplImageConverter : Component, IBindableComponent
{
private int blackLimit=125;
private int total;
private int widthBytes;
private bool compressHex= false;
public int BlacknessLimitPercentage
{
get
{
return (blackLimit * 100 / 255);
}
set
{
blackLimit = (value * 255 / 100);
}
}
public bool CompressHex
{
get { return compressHex; }
set { compressHex = value; }
}
private Image _image = null;
public Image Image
{
get { return _image; }
set
{
_image = value;
}
}
public string zplValue
{
get
{
return this._image != null ? FromImage( (Bitmap)this._image ) : "^A0,10,8^FDError!";
}
}
#region IBindableComponent Members
private BindingContext bindingContext;
private ControlBindingsCollection dataBindings;
[Browsable( false )]
public BindingContext BindingContext
{
get
{
if (bindingContext == null)
{
bindingContext = new BindingContext();
}
return bindingContext;
}
set
{
bindingContext = value;
}
}
[DesignerSerializationVisibility( DesignerSerializationVisibility.Content )]
public ControlBindingsCollection DataBindings
{
get
{
if (dataBindings == null)
{
dataBindings = new ControlBindingsCollection( this );
}
return dataBindings;
}
}
#endregion
private static Dictionary<int, string> mapCode= new Dictionary<int, string>() {
{ 1,"G"},
{ 2,"H"},
{ 3,"I"},
{ 4,"J"},
{ 5,"K"},
{ 6,"L"},
{ 7,"M"},
{ 8,"N"},
{ 9,"O"},
{ 10, "P"},
{ 11, "Q"},
{ 12, "R"},
{ 13, "S"},
{ 14, "T"},
{ 15, "U"},
{ 16, "V"},
{ 17, "W"},
{ 18, "X"},
{ 19, "Y"},
{ 20, "g"},
{ 40, "h"},
{ 60, "i"},
{ 80, "j"},
{ 100, "k"},
{ 120, "l"},
{ 140, "m"},
{ 160, "n"},
{ 180, "o"},
{ 200, "p"},
{ 220, "q"},
{ 240, "r"},
{ 260, "s"},
{ 280, "t"},
{ 300, "u"},
{ 320, "v"},
{ 340, "w"},
{ 360, "x"},
{ 380, "y"},
{ 400, "z"},
};
public string FromImage( Bitmap image )
{
string cuerpo= createBody(image);
if (compressHex) cuerpo = HexToAscii( cuerpo );
return headDoc() + cuerpo;
}
private string createBody( Bitmap orginalImage )
{
StringBuilder sb = new StringBuilder();
Graphics graphics = Graphics.FromImage( orginalImage);
graphics.DrawImage( orginalImage, 0, 0 );
int height = orginalImage.Height;
int width = orginalImage.Width;
int index = 0;
// int rgb;
int red;
int green;
int blue;
char[] auxBinaryChar = new char[] { '0', '0', '0', '0', '0', '0', '0', '0' };
widthBytes = (width / 8);
if (((width % 8)
> 0))
{
widthBytes = (((int)((width / 8))) + 1);
}
else
{
widthBytes = (width / 8);
}
this.total = (widthBytes * height);
for (int h = 0; h < height; h++)
{
for (int w = 0; w < width ; w++)
{
var rgb = orginalImage.GetPixel( w, h );
red = rgb.R;
green = rgb.G;
blue = rgb.B;
char auxChar = '1';
int totalColor = (red + green + blue)/3;
if ((totalColor > blackLimit || rgb.A<= blackLimit)) auxChar = '0';
auxBinaryChar[index] = auxChar;
index++;
if (((index == 8) || (w == (width - 1))))
{
sb.Append( ByteBinary( new string( auxBinaryChar ) ) );
auxBinaryChar = new char[] { '0', '0', '0', '0', '0', '0', '0', '0' };
index = 0;
}
}
sb.Append( "\n" );
}
return sb.ToString();
}
private string ByteBinary( string binary )
{
int dec = Convert.ToInt32(binary, 2);//int.Parse(binaryStr);//Integer.parseInt(binaryStr,2);
if (dec > 15)
{
return dec.ToString( "X" ).ToUpper();//int.toString( dec, 16 ).toUpperCase();
}
else
{
return "0" + dec.ToString( "X" ).ToUpper();//Integer.toString( dec, 16 ).toUpperCase();
}
}
private string HexToAscii( string code )
{
int maxlinea = widthBytes * 2;
StringBuilder sbCode = new StringBuilder();
StringBuilder sbLinea = new StringBuilder();
String previousLine = null;
int counter = 1;
char aux = code[0];
bool firstChar = false;
for (int i = 1; i < code.Length; i++)
{
var d=code[i];
if (firstChar)
{
aux = code[i];
firstChar = false;
continue;
}
if (code[i] == '\n')
{
if (counter >= maxlinea && aux == '0')
{
sbLinea.Append( "," );
}
else if (counter >= maxlinea && aux == 'F')
{
sbLinea.Append( "!" );
}
else if (counter > 20)
{
int multi20 = (counter/20)*20;
int resto20 = (counter%20);
sbLinea.Append( mapCode[multi20] );
if (resto20 != 0)
{
sbLinea.Append( mapCode[resto20] + aux );
}
else
{
sbLinea.Append( aux );
}
}
else
{
sbLinea.Append( mapCode[counter] + aux );
if (mapCode[counter] == null) { }
}
counter = 1;
firstChar = true;
if (sbLinea.ToString().Equals( previousLine ))
{
sbCode.Append( ":" );
}
else
{
sbCode.Append( sbLinea.ToString() );
}
previousLine = sbLinea.ToString();
sbLinea.Clear();//.setLength( 0 );
continue;
}
if (aux == code[i])
{
counter++;
}
else
{
if (counter > 20)
{
int multi20 = (counter/20)*20;
int resto20 = (counter%20);
sbLinea.Append( mapCode[multi20] );
if (resto20 != 0)
{
sbLinea.Append( mapCode[resto20] + aux );
}
else
{
sbLinea.Append( aux );
}
}
else
{
sbLinea.Append( mapCode[counter] + aux );
}
counter = 1;
aux = code[i];
}
}
return sbCode.ToString();
}
private String headDoc()
{
String str = "^GFA,"+ total + ","+ total + "," + widthBytes +", \n";
return str;
}
}
then to use:
zplImageConverter cvt= new zplImageConverter();
cvt.Image = Properties.Resources.images;//Set Image to convert
cvt.CompressHex = true;// Enable compresion HexString
cvt.BlacknessLimitPercentage = 50;// Configure the porcentaje for ilumination
Console.WriteLine( cvt.zplValue );// Print on Screen the zplCode (add ^XA before and ^XZ after and try on http://labelary.com/viewer.html)
labelary.com

print shapes in java

I want to print this shape big X from collection of small x using recursion
this is my code
private static void shape(PrintWriter output, int times, int k, int times2) {
if(times < 0){
return;
} else{
for (int i =0; i<times; i++){
if (i==times)
output.print("X");
else if(i==k)
output.print("X");
else
output.print(" ");
}
output.println();
shape(output,times-1,k+1,times2);
}
}
but I couldn't print the shape requested
Try this.
static void shape(PrintWriter output, int size, int index) {
if (index >= size)
return;
char[] buffer = new char[size];
Arrays.fill(buffer, ' ');
buffer[index] = buffer[size - index - 1] = 'X';
output.println(new String(buffer));
shape(output, size, index + 1);
}
and
try (PrintWriter output = new PrintWriter(new OutputStreamWriter(System.out))) {
shape(output, 11, 0);
}
Just change
int arr[] = new int[times]
to
int arr[] = new int[times2]
where times2 is the width of a single row.
However a more cleaner way would be:
public class InputTest {
private static void FCITshape(int times, int k,int times2) {
if (times < 0) {
return;
} else {
for (int i = 0; i <= times2; i++) {
if (i == times)
System.out.print("X");
else if (i == k)
System.out.print("X");
else
System.out.print(" ");
}
System.out.println();
FCITshape(times - 1, k + 1, times2);
}
}
public static void main(String[] args) {
FCITshape(10, 0, 10);
}
}
Regards.
With recursion
Now just call printX(0, 10);
public static void printX(int x, int l) {
if (x <= l) {
if (x < l / 2) {
for (int i = 0; i < x ; i++) {
System.out.print(" ");
}
} else {
for (int i = 0; i < l - x; i++) {
System.out.print(" ");
}
}
System.out.print("x");
if (x < l / 2) {
for (int j = 0; j < l - x * 2 - 1; j++) {
System.out.print(" ");
}
} else {
for (int j = 0; j < (x * 2 - l) - 1; j++) {
System.out.print(" ");
}
}
if (x != l / 2) {
System.out.print("x");
}
System.out.println();
printX(x + 1, l);
}
}

Unable to run the program

I am making a game in Eclipse Mars using the Processing library. I had made the game elsewhere and it ran fine. There were no errors after I copied and pasted the files from my flash drive to the folder in Eclipse. When I tried to run it, it said "The selection cannot be launched, and there are no recent launches." There were no recent launches because I had just gotten Eclipse. My code is as follows:
Main Class:
//package dogeball;
import processing.core.PApplet;
import processing.core.PImage;
import java.awt.Color;
import processing.core.PFont;
public class Dogeball extends PApplet {
Ball ball;
Furniture butterChair;
Furniture[] bricks;
PFont dogefont;
float py;
float score;
boolean game;
int checker;
boolean mode;
PImage img = loadImage("doge.jpg");
PImage img2 = loadImage("doge2.png");
public void setup() {
checker = 0;
size(300,250);
game = false;
mode = true;
ball = new Ball(this, 100, 225, 0, 0, 10, Color.DARK_GRAY );
butterChair = new Furniture(this, 130, 238, 40, 10, Color.YELLOW);
py = butterChair.w /2;
bricks = new Furniture[56];
dogefont = loadFont("ComicSansMS-48.vlw");
for(int rowNum = 0; rowNum<8; rowNum+= 1) {
for(int colNum = 0; colNum<7; colNum += 1){
bricks[7*rowNum + colNum] = new Furniture(this, 10+40*colNum, 10+15*rowNum, 40, 15, Color.red);
score = 0;
}
}
}
public void draw() {
if(game == false) {
background(img);
fill(0,255,255);
textSize(30);
textFont(dogefont);
text("DogeBall",33, 170);
fill(255,255,0);
textSize(20);
text("Press Space", 120,190);
fill(255,0,0);
text("Such BrickBreaker", 20, 20);
fill(0,0,255);
text("Much Atari", 190, 80);
fill(0,255,0);
text("How Breakout", 150, 230);
}
if(keyPressed == true) {
if (key == ' ') {
game = true;
}
}
if(game == true) {
if(keyPressed == true) {
if (key == 'm') {
mode = !mode;
}
}
//checker = 0;
background(img);
ball.appear();
ball.hover();
butterChair.appear();
if(mode == true) {
butterChair.x = mouseX-butterChair.w/2;
}
if(mode == false) {
if(keyPressed == true) {
if (key == CODED) {
if (keyCode == LEFT){
butterChair.x -= 3;
}
}
}
if(keyPressed == true) {
if (key == CODED) {
if (keyCode == RIGHT){
butterChair.x += 3;
}
}
}
}
if(butterChair.x <= 0) {
butterChair.x = 0;
}
if(butterChair.x >= width - butterChair.w) {
butterChair.x = width - butterChair.w;
}
textFont(dogefont);
fill(255,0,255);
text("Much Doge", 12, 160);
fill(255,0,0);
textSize(20);
text("M to toggle mouse mode.", 20,200);
fill(0);
textSize(10);
text("You might have to press twice", 10,220);
fill(0,0,255);
textSize(20);
text("Press S to Start", 150, 230);
if (keyPressed == true) {
if (key == 's' || key == 'S'){
ball.vy = 2;
ball.vx = 1;
}
}
/*if(mousePressed == true) {
ball.vx = 0;
ball.vy = 0;
}*/
for(int i = 0; i<56; i+= 1) {
bricks[i].appear();
}
}
detectCollision();
if(ball.y >= height) {
checker = 0;
if(checker ==0){
background(img);
ball.vx = 0;
ball.vy = 0;
textSize(30);
fill(255,0,0);
game = false;
text("Such Sorry", 130, 160);
fill(0,255,255);
text("Much Game Over", 20, 215);
fill(255,255,0);
text("So Losing", 10, 30);
textSize(20);
text("Press P to Play Again", 20, 245);
}
if(keyPressed == true) {
if(key == 'p') {
game = true;
ball.x = 100;
ball.y = 225;
checker = 1;
for(int rowNum = 0; rowNum<8; rowNum+= 1) {
for(int colNum = 0; colNum<7; colNum += 1){
bricks[7*rowNum + colNum] = new Furniture(this, 10+40*colNum, 10+15*rowNum, 40, 15, Color.red);
score = 0;
}
}
}
}
}
}
void detectCollision() {
if(keyPressed == true) {
if(key == '-')
{
for(int cCode = 0; cCode < 56; cCode += 1) {
Furniture b = bricks[cCode];
b.x = width * 2;
b.y = height * 2;
score = 56;
}
}}
if(ball.x >= butterChair.x &&
ball.x <= butterChair.x + butterChair.w &&
ball.y + ball.s /2 > butterChair.y) {
ball.vy *= -1;
}
for(int i = 0; i<bricks.length; i+= 1) {
Furniture b = bricks[i];
if(ball.x >= b.x && ball.x <= b.x+b.w && ball.y-ball.s/2 <= b.y) {
b.y = height * 2;
b.x = width * 2;
ball.vy *= -1;
score += 1;
}
if(score == 56){
background(img);
ball.vx = 0;
ball.vy = 0;
fill(255,0,0);
textSize(20);
text("Such Winning!", 20, 20);
textSize(40);
fill(0,255,0);
text("Much Congrats!",12 ,160);
textSize(20);
fill(255,0,255);
text("Press P to Play Again", 20, 245);
if(keyPressed == true) {
if(key == 'p') {
game = true;
ball.x = 100;
ball.y = 225;
checker = 1;
for(int rowNum = 0; rowNum<8; rowNum+= 1) {
for(int colNum = 0; colNum<7; colNum += 1){
bricks[7*rowNum + colNum] = new Furniture(this, 10+40*colNum, 10+15*rowNum, 40, 15, Color.red);
score = 0;
}
}
}
}
}
}
}
static public void main(String args[]) {
PApplet.main("Dogeball");
}
}
Ball Class:
//package dogeball;
import java.awt.Color;
import processing.core.PApplet;
public class Ball extends PApplet {
float x;
float y;
float vx;
float vy;
float s;
Color c;
PApplet p;
Ball(PApplet pApp, float xLocation, float yLocation, float xSpeed, float ySpeed, float size, Color shade){
x = xLocation;
y = yLocation;
vx = xSpeed;
vy = ySpeed;
s = size;
c = shade;
p = pApp;
}
void hover() {
x += vx;
y += vy;
if(x< 0 || x> p.width) {
vx *= -1;
}
if(y< 0) {
vy *= -1;
}
}
void appear() {
p.fill(c.getRGB() );
p.ellipse(x,y,s,s);
}
}
Paddle Class:
//package dogeball;
import java.awt.Color;
import processing.core.PApplet;
public class Furniture extends PApplet {
float x;
float y;
float w;
float h;
Color c;
PApplet p;
Furniture(PApplet PApp, float locationX, float locationY, float fWidth, float fHeight, Color shade) {
x = locationX;
y = locationY;
w = fWidth;
h = fHeight;
c = shade;
p = PApp;
}
void appear() {
p.fill(c.getRGB());
p.rect(x,y,w,h);
}
}
You have probably the wrong project selected on the projects tree or the run configurations are set to another project, since you haven't run it yet.
Either way, you have to right click your projects folder on the projects tree, then find Run As > Java Applet.
Another way to do it would be adding a main function, as you already did, and run is as a Java Application. Instead of using the current main function, you can try to use the code below to see it in present mode and see if it works:
public static void main(String args[]) {
PApplet.main(new String[] { "--present", "Dogeball" });
}

Resources