why do i keep getting a syntax error for "unexpected token 'method' " in the final few lines - monkey-x

this is the code that i am using in Monkey X to try and build a game, the final method is supposed to draw the sprite within the game but it seems to register as an error and does not allow the method to be there, is there any way i can fix this
Import mojo
Class Vec2D
Field x: Float
Field y: Float
Method New (x: Float = 0, y: Float = 0)
set( x, y)
End
Method set (x: Float, y: Float)
Self.x = x
Self.y = y
End
End
Class Vec2Di
Field x: int
Field y: int
Method New (x: int = 0, y: int = 0)
set( x, y)
End
Method set (x: int, y: int)
Self.x = x
Self.y = y
End
End
Class Player
Field OriginalPosition: Vec2D
Field Position: Vec2D
Field Velocity: Vec2D
Field SpeedLR: Float = 2.0
Field SpeedUD: Float = 4.0
Field leftKey: Int
Field rightKey: Int
Field upKey: Int
Field downKey: Int
Method New(leftKey: Int, rightKey: Int, upKey: Int, downKey:Int, x: Float, y: Float)
OriginalPosition = New Vec2D(x, y)
Position = New Vec2D(x, y)
Velocity = New Vec2D()
Self.leftKey = leftKey
Self.rightKey = rightKey
Self.upKey = upKey
Self.downKey = downKey
End
Method Update()
Velocity.x = 0
Velocity.y = 0
If KeyDown (leftKey)
Velocity.x = -SpeedLR
If KeyDown (rightKey)
Velocity.x = SpeedLR
If KeyDown (upKey)
Velcity.y = SpeedUD
If KeyDown (downKey)
Velocity.y = -SpeedUD
End
Position.x += Velocity.x
Position.y += Velocity.y
End
Method Draw()
SetColor (0, 255, 0)
DrawRect (Position.x-16, Position.y-16, 32, 32)
End
End
after this i looked into the main catagory of my game and it has no problems apart from this one and for sopme reason i cannot seem to find the problem with it however hard i try. I have been following a tutorial on how to draw a sprite in game and this has been the exact same way that he did it but it still will not register the method. Does anyone have any ideas on a way that i can fix this issue and get the game to run.

Related

Why do the lines (muscles) not line up with part3 (blue)?

https://imgur.com/a/hDRx3SI
The lines (muscles) start out in the center as I want. (This video starts out a second or two into the sketch.) Why do the muscles not line up with the center of part3 (Blue circle)? Is it simply a trigonometric issue where I'm trying to force them into an impossible position given the constraints?
Part part1;
Part part2;
Part part3;
Muscle muscle1;
Muscle muscle2;
Muscle muscle3;
void setup() {
size (800, 800);
frameRate(1);
part1 = new Part(width/2, height/2, 50, color(255, 0, 0));
part2 = new Part(width/2 + 100, height/2, 50, color(0, 255, 0));
part3 = new Part(width/2 + 50, height/2 - 75, 50, color(0, 0, 255));
muscle1 = new Muscle(part1.x, part1.y, part2.x, part2.y, dist(part1.x, part1.y, part2.x,part2.y), color(0, 255, 0));
muscle2 = new Muscle(part1.x, part1.y, part3.x, part3.y, dist(part1.x, part1.y, part3.x, part3.y), color(0, 255, 0));
muscle3 = new Muscle(part2.x, part2.y, part3.x, part3.y, dist(part2.x, part2.y, part3.x, part3.y), color(0, 255, 0));
}
void draw() {
background(255);
part1.drawpart();
part2.drawpart();
part3.drawpart();
muscle1.drawmuscle(part1, part2);
muscle2.drawmuscle(part1, part3);
muscle3.drawmuscle(part2, part3);
part2.movepart();
}
class Muscle{
float leftx;
float lefty;
float rightx;
float righty;
float size = 100;
int musclecolor;
Muscle(float leftpositionx, float leftpositiony, float rightpositionx, float rightpositiony, float musclesize, int musclemusclecolor) {
leftx = leftpositionx;
lefty = leftpositiony;
rightx = rightpositionx;
righty = rightpositiony;
size = musclesize;
musclecolor = musclemusclecolor;
}
void drawmuscle(Part obj1, Part obj2) {
strokeWeight(5);
float dx = obj2.x - obj1.x;
float dy = obj2.y - obj1.y;
float angle = atan2(dy, dx);
obj2.x = obj1.x + cos(angle) * size;
obj2.y = obj1.y + sin(angle) * size;
line(obj1.x, obj1.y, obj2.x, obj2.y);
}
}
class Part{
float x;
float y;
float size;
int partcolor;
Part(float positionx, float positiony, float partsize, int partpartcolor) {
x = positionx;
y = positiony;
size = partsize;
partcolor = partpartcolor;
}
void drawpart() {
fill(partcolor);
strokeWeight(1);
ellipseMode(CENTER);
ellipse(x, y, size, size);
}
void movepart() {
y += 10;
}
}
There are two different problems here which interacts with one another, which is why this is hard to solve. You'll be happy to notice, though, that your math are irreproachable.
First issue is in the drawmuscle() method. You modify coordinates while drawing them, which isn't necessarily an issue. The problem is that you're doing this in cascade for 3 different parts, which depend on each other to be calculated. The variables all end up all right - so mathematically it works - but as you draw some parts before others have been calculated, they end up with unexpected coordinates that are neither the old ones nor the new ones.
To fix this, I modified the drawmuscle() method so it only draws the muscles, and I added a new method to update the muscles/parts coordinates. It's still all your code, just displaced into different containers. Then I modified the draw() method to reflect this change: the coordinates have to be calculated first, then the parts can be drawn.
Now, the blue circle was still misplaced. That's also because of a matter of order in the draw() method: as the circles were drawn before their coordinates were updated, they were subject to be misdrawn. Again, at the end of every frame, your calculations were correct, but in the way the operations to get there were applied and drawn they would appear off.
As a rule of thumb, I would say that you need to remember from this project the following rule: calculate first, draw last.
So here are the changes I made to your methods:
void draw() {
background(255);
// calculating new positions
muscle1.moveMuscle(part1, part2);
muscle2.moveMuscle(part1, part3);
muscle3.moveMuscle(part2, part3);
// drawing
part1.drawpart();
part2.drawpart();
part3.drawpart();
muscle1.drawmuscle(part1, part2);
muscle2.drawmuscle(part1, part3);
muscle3.drawmuscle(part2, part3);
muscle1.growmuscle(part1, part2);
}
void drawmuscle(Part obj1, Part obj2) {
// no calculations here
strokeWeight(5);
line(obj1.x, obj1.y, obj2.x, obj2.y);
}
void moveMuscle(Part obj1, Part obj2) {
// every calculations here
float dx = obj2.x - obj1.x;
float dy = obj2.y - obj1.y;
float angle = atan2(dy, dx);
obj2.x = obj1.x + cos(angle) * size;
obj2.y = obj1.y + sin(angle) * size;
rightx = obj2.x;
righty = obj2.y;
}
I hope this will help. Have fun!

Processing - why does my Random Walker always tend toward the top left?

I am currently going through Daniel Shiffman's 'The Nature Of Code', and have been playing around with one of the first exercises - a simple 'RandomWalker()'. I have implemented similar things in Java & had no trouble, however for some reason my walker always seems to go in more or less the same direction:
RandomWalker
This happens 100% of the time. Here is my code:
class Walker
{
int x;
int y;
// Constructor
Walker()
{
x = width / 2;
y = height / 2;
}
void display()
{
stroke(0); // Colour
point(x, y); // Colours one pixel in
}
void step()
{
float stepX;
float stepY;
stepX = random(-1, 1);
stepY = random(-1, 1);
x += stepX;
y += stepY;
}
}
Walker w;
void setup()
{
size(640, 360);
w = new Walker();
background(255);
}
void draw()
{
w.step();
w.display();
}
Is this some artefact of the random function? My first thought is that it's something to do with the pseudorandom nature of the function but the textbook specifically states that this should not be noticeable, and yet this happens every single time. I was wondering if maybe there's something wrong with my code?
Thanks in advance.
Your x and y variables are both int types. That means that they don't have a decimal part, so any time you add or subtract from them, they are truncated. Here are some examples:
int x = 1;
x = x + .5;
//1.5 is truncated, and x stays 1
int x = 1;
x = x - .5;
//.5 is truncated, and x becomes 0
This is why you see your x and y variables only decreasing. To fix this, just change x and y to float types, so they keep track of the decimals.
If you really need x and y to be int values, then you need stepX and stepY to also be int values:
int stepX;
int stepY;
stepX = (int)random(-5, 5);
stepY = (int)random(-5, 5);
x += stepX;
y += stepY;
But you probably just want to store x and y as float values.
PS: I love random walkers!

Detect and fix text skew by rotating image

Is there a way (using something like OpenCV) to detect text skew and correct it by rotating the image? Pretty much like this?
Rotating an image seems easy enough if you know the angle, but for the images I'm processing, I wont...it will need to be detected somehow.
Based on your above comment, here is the code based on the tutorial here, working fine for the above image,
Source
Rotated
Mat src=imread("text.png",0);
Mat thr,dst;
threshold(src,thr,200,255,THRESH_BINARY_INV);
imshow("thr",thr);
std::vector<cv::Point> points;
cv::Mat_<uchar>::iterator it = thr.begin<uchar>();
cv::Mat_<uchar>::iterator end = thr.end<uchar>();
for (; it != end; ++it)
if (*it)
points.push_back(it.pos());
cv::RotatedRect box = cv::minAreaRect(cv::Mat(points));
cv::Mat rot_mat = cv::getRotationMatrix2D(box.center, box.angle, 1);
//cv::Mat rotated(src.size(),src.type(),Scalar(255,255,255));
Mat rotated;
cv::warpAffine(src, rotated, rot_mat, src.size(), cv::INTER_CUBIC);
imshow("rotated",rotated);
Edit:
Also see the answer here , might be helpful.
Here's an implementation of the Projection Profile Method algorithm for skew angle estimation. Various angle points are projected into an accumulator array where the skew angle can be defined as the angle of projection within a search interval that maximizes alignment. The idea is to rotate the image at various angles and generate a histogram of pixels for each iteration. To determine the skew angle, we compare the maximum difference between peaks and using this skew angle, rotate the image to correct the skew.
Input
Result
Skew angle: -5
import cv2
import numpy as np
from scipy.ndimage import interpolation as inter
def correct_skew(image, delta=1, limit=5):
def determine_score(arr, angle):
data = inter.rotate(arr, angle, reshape=False, order=0)
histogram = np.sum(data, axis=1, dtype=float)
score = np.sum((histogram[1:] - histogram[:-1]) ** 2, dtype=float)
return histogram, score
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
scores = []
angles = np.arange(-limit, limit + delta, delta)
for angle in angles:
histogram, score = determine_score(thresh, angle)
scores.append(score)
best_angle = angles[scores.index(max(scores))]
(h, w) = image.shape[:2]
center = (w // 2, h // 2)
M = cv2.getRotationMatrix2D(center, best_angle, 1.0)
corrected = cv2.warpAffine(image, M, (w, h), flags=cv2.INTER_CUBIC, \
borderMode=cv2.BORDER_REPLICATE)
return best_angle, corrected
if __name__ == '__main__':
image = cv2.imread('1.png')
angle, corrected = correct_skew(image)
print('Skew angle:', angle)
cv2.imshow('corrected', corrected)
cv2.waitKey()
Note: You may have to adjust the delta or limit values depending on the image. The delta value controls iteration step, it will iterate up until the limit which controls the maximum angle. This method is straightforward by iteratively checking each angle + delta and currently only works to correct skew in the range of +/- 5 degrees. If you need to correct at a larger angle, adjust the limit value.
I would provide javacv for your reference.
package com.test13;
import org.opencv.core.*;
import org.opencv.imgproc.Imgproc;
import org.opencv.imgcodecs.Imgcodecs;
public class EdgeDetection {
static{ System.loadLibrary(Core.NATIVE_LIBRARY_NAME); }
public static void main( String[] args ) throws Exception{
Mat src = Imgcodecs.imread("src//data//inclined_text.jpg");
Mat src_gray = new Mat();
Imgproc.cvtColor(src, src_gray, Imgproc.COLOR_BGR2GRAY);
Imgcodecs.imwrite("src//data//inclined_text_src_gray.jpg", src_gray);
Mat output = new Mat();
Core.bitwise_not(src_gray, output);
Imgcodecs.imwrite("src//data//inclined_text_output.jpg", output);
Mat points = Mat.zeros(output.size(),output.type());
Core.findNonZero(output, points);
MatOfPoint mpoints = new MatOfPoint(points);
MatOfPoint2f points2f = new MatOfPoint2f(mpoints.toArray());
RotatedRect box = Imgproc.minAreaRect(points2f);
Mat src_squares = src.clone();
Mat rot_mat = Imgproc.getRotationMatrix2D(box.center, box.angle, 1);
Mat rotated = new Mat();
Imgproc.warpAffine(src_squares, rotated, rot_mat, src_squares.size(), Imgproc.INTER_CUBIC);
Imgcodecs.imwrite("src//data//inclined_text_squares_rotated.jpg",rotated);
}
}
private fun main(){
val bmp:Bitmap? = null //Any bitmap (if you are working with bitmap)
var mRgba = Mat() // else you can direct use MAT on onCameraFrame
val mGray = Mat()
val bmp32: Bitmap = bmp.copy(Bitmap.Config.ARGB_8888, true)
Utils.bitmapToMat(bmp32, mRgba)
Imgproc.cvtColor(mRgba, mGray, Imgproc.COLOR_BGR2GRAY)
mRgba = makeOrientationCorrection(mRgba,mGray)// here actual magic starts
Imgproc.cvtColor(mRgba, mGray, Imgproc.COLOR_BGR2GRAY)
val bmpOutX = Bitmap.createBitmap(
mRgba.cols(),
mRgba.rows(),
Bitmap.Config.ARGB_8888
)
Utils.matToBitmap(mRgba, bmpOutX)
binding.imagePreview.setImageBitmap(bmpOutX!!)
}
private fun makeOrientationCorrection(mRGBA:Mat, mGRAY:Mat):Mat{
val dst = Mat()
val cdst = Mat()
val cdstP: Mat
Imgproc.Canny(mGRAY, dst, 50.0, 200.0, 3, false)
Imgproc.cvtColor(dst, cdst, Imgproc.COLOR_GRAY2BGR)
cdstP = cdst.clone()
val linesP = Mat()
Imgproc.HoughLinesP(dst, linesP, 1.0, Math.PI/180, 50, 50.0, 10.0)
var biggestLineX1 = 0.0
var biggestLineY1 = 0.0
var biggestLineX2 = 0.0
var biggestLineY2 = 0.0
var biggestLine = 0.0
for (x in 0 until linesP.rows()) {
val l = linesP[x, 0]
Imgproc.line(
cdstP, org.opencv.core.Point(l[0], l[1]),
org.opencv.core.Point(l[2], l[3]),
Scalar(0.0, 0.0, 255.0), 3, Imgproc.LINE_AA, 0)
}
for (x in 0 until linesP.rows()) {
val l = linesP[x, 0]
val x1 = l[0]
val y1 = l[1]
val x2 = l[2]
val y2 = l[3]
val lineHeight = sqrt(((x2 - x1).pow(2.0)) + ((y2 - y1).pow(2.0)))
if(biggestLine<lineHeight){
val angleOfRotationX1 = angleOf(PointF(x1.toFloat(),y1.toFloat()),PointF(x2.toFloat(),y2.toFloat()))
Log.e("angleOfRotationX1","$angleOfRotationX1")
if(angleOfRotationX1<45.0 || angleOfRotationX1>270.0){
biggestLine = lineHeight
if(angleOfRotationX1<45.0){
biggestLineX1 = x1
biggestLineY1 = y1
biggestLineX2 = x2
biggestLineY2 = y2
}
if(angleOfRotationX1>270.0){
biggestLineX1 = x2
biggestLineY1 = y2
biggestLineX2 = x1
biggestLineY2 = y1
}
}
}
if(x==linesP.rows()-1){
Imgproc.line(
cdstP, org.opencv.core.Point(biggestLineX1, biggestLineY1),
org.opencv.core.Point(biggestLineX2, biggestLineY2),
Scalar(255.0, 0.0, 0.0), 3, Imgproc.LINE_AA, 0)
}
}
var angle = angleOf(PointF(biggestLineX1.toFloat(),biggestLineY1.toFloat()),PointF(biggestLineX2.toFloat(),biggestLineY2.toFloat()))
Log.e("angleOfRotationX2","$angle")
angle -= (angle * 2)
return deskew(mRGBA,angle)
}
fun angleOf(p1: PointF, p2: PointF): Double {
val deltaY = (p1.y - p2.y).toDouble()
val deltaX = (p2.x - p1.x).toDouble()
val result = Math.toDegrees(Math.atan2(deltaY, deltaX))
return if (result < 0) 360.0 + result else result
}
private fun deskew(src:Mat, angle:Double):Mat{
val center = org.opencv.core.Point((src.width() / 2).toDouble(), (src.height() / 2).toDouble())
val scaleBy = if(angle<0){
1.0+((0.5*angle)/45)//max scale down by 0.50(50%) based on angle
}else{
1.0-((0.3*angle)/45)//max scale down by 0.50(50%) based on angle
}
Log.e("scaleBy",""+scaleBy)
val rotImage = Imgproc.getRotationMatrix2D(center, angle, scaleBy)
val size = Size(src.width().toDouble(), src.height().toDouble())
Imgproc.warpAffine(src, src, rotImage, size, Imgproc.INTER_LINEAR + Imgproc.CV_WARP_FILL_OUTLIERS)
return src
}
Make sure you run this "makeOrientationCorrection()" method on another thread. otherwise, UI won't update for 2-5 sec.

Need help reversing the values somehow

I have a very strange problem. Everything in my code works super fine, but I still have an issue.
import processing.serial.*;
float r_height;
float r_width;
float hypotnuse;
int d = 20;
float x ;
float y ;
float ledGlow;
Serial myPort; // Create object from Serial class
void setup () {
size (510, 510);
String portName = Serial.list()[8];
myPort = new Serial(this, portName, 9600);
background (0);
fill(204);
ellipseMode (CORNER);
x = 0;
y = 0;
ellipse (x, y, d, d);
}
void draw () {
r_height = mouseY - y;
r_width = mouseX - x;
println ("Height is " + r_height);
println ("Width is " + r_width);
hypotnuse = sqrt (( (sq(r_height)) + (sq (r_width)) ) );
ledGlow = round (hypotnuse/2.84);
myPort.write(ledGlow);
println (ledGlow);
}
I need to get values 0-255 from the hypotenuse of my triangle. but when I am writing it to the serial port (myPort.write (ledGlow)), i need those values to be flipped. So if the hypotenuse is 0, it actually needs to equal to 255, if it's 1 it needs to be 254 and so on. I am not sure how to approach this problem.
Can you just subtract the hypotenuse from 255 at that time, to get the flipped hypotenuse value?
new_hypotenuse = 255 - hypotenuse ;

Rotate some elements in an ellipse path

I am trying to make some objects, say 12, to rotate in an ellipse path continuously in Processing. I got a sketch which does rotation in a circle and I want to make it to rotate in a ellipse. I have some pointer from processing forum but the code from the pointer is different from the code that I posted and I couldn't understand yet (weak in trigonometry).
I googled a bit and found a post trying to achieve this with this algorithm:
You need to define your ellipse with a few parameters:
x, y: center of the ellipse
a, b: semimajor and semiminor axes
If you want to move on the elipses this means that you change the
angle between the major axes and your position on the ellipse. Lets
call this angle alpha.
Your position (X,Y) is:
X = x + (a * Math.cos(alpha));
Y = y + (b * Math.sin(alpha));
In order to move left or right you need to increase/decrease alpha and
then recalculate your position. Source:
http://answers.unity3d.com/questions/27620/move-object-allong-an-ellipsoid-path.html
How do I integrate it into my sketch? Thank you.
Here's my sketch:
void setup()
{
size(1024, 768);
textFont(createFont("Arial", 30));
}
void draw()
{
background(0);
stroke(255);
int cx = 500;
int cy = 350;
int r = 300; //radius of the circle
float t = millis()/4000.0f; //increase to slow down the movement
ellipse(cx, cy, 5, 5);
for (int i = 1 ; i <= 12; i++) {
t = t + 100;
int x = (int)(cx + r * cos(t));
int y = (int)(cy + r * sin(t));
line(cx, cy, x, y);
textSize(30);
text(i, x, y);
if (i == 10) {
textSize(15);
text("x: " + x + " y: " + y, x - 50, y - 20);
}
}
}
Replace
int r = 300; //radius of the circle
with
int a = 350; // major axis of ellipse
int b = 250; // minor axis of ellipse
and replace
int x = (int)(cx + r * cos(t));
int y = (int)(cy + r * sin(t));
with
int x = (int)(cx + a * cos(t));
int y = (int)(cy + b * sin(t));

Resources