'var' is not defined in 'for' loop - python-3.x

This is a code example from book:
width, height = 240, 60
midx, midy = width // 2, height // 2
for xen in range(width):
for уen in range(height):
if xen < 5 or xen >= width - 5 or уen < 5 or уen >= height - 5:
image[xen, yen] = border_color
elif midx - 20 < xen < midx + 20 and midy - 20 < уen < midy + 20:
image[xen, yen] = square_color
When I try to run this, I get error: 'yen' is not defined. But it was defined in 'for' loop, and so 'xen' was defined. I know that the book I am reading is kind of old, but I don't understand why am I getting this error and how to avoid this. I know there are loops, but this code seems fully legit to me. What's the trick?

When I copy and paste your code, the y in yen in your for loop is an odd character (maybe a Cyrillic 'U'). It looks like a y but it's not. Try retyping the line:
for уen in range(height):
These look the same, but if you run the snippet, you'll see they aren't:
console.log("уen" == "yen")

Related

p5.js sprite movement back and forth

Hi all I am in need of some help. I am working on a project and would like my enemy sprite to move back end forth for a specific distance. I have manged to get him to flip from right to left, then after that he disappears. I am sure there is something wrong with my conditional statement (or maybe I may need a loop) please help.
if(enemystart <= 0 && enemystart >= -100)
{
enemystart = enemystart + (enemyspeed * enemydirection * -1);
image(zombieL[frameCount % 10], enemystart, floorPos_y - 58, 60, 60);
}
else if(enemyp1 >= -100 && enemyp1 <= 0)
{
enemyp1 = enemyp1 + (enemyspeed * enemydirection);
image(zombie[frameCount % 10], enemyp1, floorPos_y - 58, 60, 60);
}
I think you didn't change the enemydirection variable. Change it to 90 on turning right and -90 on turning left. And also 0 on turning towards top and 180 on turning bottom. This might solve the problem? I guess so!

Why is this specific if condition never executes ? [if mid < k <= right:]

Im trying to solve a specific leetcode problem and but a particular if else block never executes in my code and I cant figure why. Here is the code. I'm new to python and I think i'm making a noob mistake but I just figure what it is.
class Solution:
def findDuplicate(self, nums: List[int]) -> int:
left, right = 1, len(nums) - 1
while left < right :
mid = left + (right-left)//2
count = 0
print("l,r -->" + str(left) + ',' + str(right))
print("mid -->" + str(mid))
for k in nums :
if mid < k <= right: # this block never executes.
print(k)
count += 1
print("count -->" + str(count))
if count > right -mid:
left = mid + 1
else :
right = mid
return right
For one thing, this
if mid < k <= right: # this block never executes.
is not doing what you think it is -- instead, you want
if mid < k and k <= right:

Correct use of cos() and sin() in Python

I'm trying to convert, just for fun, a code listing written in a language called Seed7 into Python. I've got it just about to beta phase, except for one part. This is the extract of the Seed7 listing:
x1 := flt(column) + 0.5;
y1 := flt(row) + 0.5;
angle := (course - 1.0) * 0.785398;
delta_x := cos(angle);
delta_y := -sin(angle);
inquad := TRUE;
blocked := FALSE;
number := 1;
while number <= distance do
y1 := y1 + delta_y;
x1 := x1 + delta_x;
row := trunc(y1);
column := trunc(x1);
if column < 1 or column > 8 or row < 1 or row > 8 then
inquad := FALSE;
number := distance;
else
if sect[row][column] <> 1 then (* Object blocking move *)
blocked := TRUE;
number := distance;
end if;
end if;
incr(number);
end while;
Which all makes sense, except for the fact that I don't understand how the functions cos() and sin() work in Seed7.
The manual says:
sin
const func float: sin (in float: x)
Compute the sine of x, where x is given in radians.
Returns:
the trigonometric sine of an angle.
but I can't make the equivalent in Python.
This problem is purely one caused by me not understanding Python properly (and not really being that great with maths either), so I come here to ask someone who does understand these things.
What code is required to make the above code work in Python? Help!!! :-)
Many thanks,
Joseph.
Edit: I think the problem is the incr() function. Basically, it is possible to warp in this game less than 1. From the help files:
writeln("Warp - One warp moves you the width of a quadrant. A warp of .5 will move you");
writeln("halfway through a quadrant. Moving diagonally across a quadrant to the next");
writeln("will require 1.414 warps. Warp 3 will move you 3 quadrants providing nothing");
writeln("in your present quadrant blocks your exit. Once you leave the quadrant that");
writeln("you were in, you will enter hyperspace; coming out of hyperspace will place you");
writeln("randomly in the new quadrant. Klingons in a given quadrant will fire at you");
writeln("whenever you leave, enter, or move within the quadrant. Entering a course or");
writeln("warp of zero can be used to return to the command mode.")
My code looks like this:
x1 = float(column) + 0.5
y1 = float(row) + 0.5
angle = (course - 1.0) * 0.785398
deltaX = math.cos(angle)
deltaY = -math.sin(angle)
inQuad = True
blocked = False
num = 1
while num <= distance:
y1 += deltaY
x1 += deltaX
row = int(round(y1))
column = int(round(x1))
if column < 0 or column > 7 or row < 0 or row > 7:
inQuad = False
num = distance
else:
if sect[row][column] != 1:
blocked = True
num = distance
num += 1
The thing is I'm using num+=1 at the end there, as opposed to incr, but I don't understand incr. As I have said, I've been a bit long out of the game, and certain things are really catching me out.
Any help in shining a light would be appreciated.
Joseph.
A guess:
If Seed7 expects radians, you may need to convert degrees to radians before applying sin or cos:
import math
math.sin(math.radians(1))

How do I create an object boundary in Three.js / WebGL?

I'm new to graphics and was wondering how I would go about creating an object boundary for my game.
Right now I have an object following my mouse. This works fine for my boundary when my ship has a rotation.z of 0. However, when I rotate the ship, the boundary has odd behavior.
I tried getting the world position of the ship and simply checking the x and y boundaries. However, the world position seems to give me a different x and y when I rotate. How can I
go about creating a boundary that works for all the rotations of my ship.
Here's my game(collisions turned off for purpose of help): http://www.cis.gvsu.edu/~chaua/CS371/WebGLProject/home.html
The behavior I'd like occurs when you don't rotate the ship.
Rotate the ship with left/right mouse.
Relevant code snippets(in render loop):
if(mouseLeftDown)
ship.rotation.z += leanSpeed;
if(mouseRightDown)
ship.rotation.z += -leanSpeed;
....
....
targetX = ((lastMouseX / window.innerWidth) * 2 - 1) * 90;
targetY = -((lastMouseY / window.innerHeight) * 2 - 1) * 60;
var worldPosition = (new THREE.Vector3()).getPositionFromMatrix(ship.matrixWorld);
if(worldPosition.x + targetX <= (randSpawnWidth/2)-500 && worldPosition.x + targetX >= -(randSpawnWidth/2)+500)
ship.translateX(targetX);
if(worldPosition.y + targetY <= (randSpawnHeight/2)-500 && worldPosition.y + targetY >= -(randSpawnHeight/2)+500)
ship.translateY(targetY);
I would appreciate any help. Thanks!

Algorithm for drawing a 4-connected line

I'm looking for an algorithm (coded in Java would be nice, but anything clear enough to translate to Java is fine) to draw a 4-connected line. It seems that Bresenham's algorithm is the most widely used, but all the understandable implementations I've found are 8-connected. OpenCV's cvline function apparently has a 4-connected version, but the source code is, to me, as a mediocre and nearly C-illiterate programmer, impenetrable. Various other searches have turned up nothing.
Thanks for any help anyone can provide.
The following is a Bresenham-like algorithm that draws 4-connected lines. The code is in Python but I suppose can be understood easily even if you don't know the language.
def line(x0, y0, x1, y1, color):
dx = abs(x1 - x0) # distance to travel in X
dy = abs(y1 - y0) # distance to travel in Y
if x0 < x1:
ix = 1 # x will increase at each step
else:
ix = -1 # x will decrease at each step
if y0 < y1:
iy = 1 # y will increase at each step
else:
iy = -1 # y will decrease at each step
e = 0 # Current error
for i in range(dx + dy):
draw_pixel(x0, y0, color)
e1 = e + dy
e2 = e - dx
if abs(e1) < abs(e2):
# Error will be smaller moving on X
x0 += ix
e = e1
else:
# Error will be smaller moving on Y
y0 += iy
e = e2
The idea is that to draw a line you should increment X and Y with a ratio that matches DX/DY of the theoretic line. To do this I start with an error variable e initialized to 0 (we're on the line) and at each step I check if the error is lower if I only increment X or if I only increment Y (Bresenham check is to choose between changing only X or both X and Y).
The naive version for doing this check would be adding 1/dy or 1/dx, but multiplying all increments by dx*dy allows using only integer values and that improves both speed and accuracy and also avoids the need of special cases for dx==0 or dy==0 thus simplifying the logic.
Of course since we're looking for a proportion error, using a scaled increment doesn't affect the result.
Whatever is the line quadrant the two possibilities for the increment will always have a different sign effect on the error... so my arbitrary choice was to increment the error for an X step and decrement the error for an Y step.
The ix and iy variables are the real directions needed for the line (either +1 or -1) depending on whether the initial coordinates are lower or higher than the final coordinates.
The number of pixels to draw in a 4-connected line is obviously dx+dy, so I just do a loop for that many times to draw the line instead of checking if I got to the end point. Note that this algorithm draws all pixels except the last one; if you want also that final pixel then an extra draw_pixel call should be added after the end of the loop.
An example result of the above implementation can be seen in the following picture
For the Python-illiterate, here is a C version of 6502's code:
void drawLine(int x0, int y0, int x1, int y1) {
int dx = abs(x1 - x0);
int dy = abs(y1 - y0);
int sgnX = x0 < x1 ? 1 : -1;
int sgnY = y0 < y1 ? 1 : -1;
int e = 0;
for (int i=0; i < dx+dy; i++) {
drawPixel(x0, y0);
int e1 = e + dy;
int e2 = e - dx;
if (abs(e1) < abs(e2)) {
x0 += sgnX;
e = e1;
} else {
y0 += sgnY;
e = e2;
}
}
}

Resources