Im using an if statement to detect whether the player's coordinates after moving up (y coordinate increases) are equal to an open space's coordinates.
Ex:
player_coordinate = player.pos() # We can say that the coordinate returned is (-10.00,10.00)
space_coordinate = space.pos() # And the coordinate returned is (-10.00,20.00)
movement = 10 # How far the player can move at once
if (player_coordinate[0], player_coordinate[1] + movement) == space_coordinate:
player can move
Now, I used this same method, however when the player's position has a negative y value, the statement is false.
For example:
# Works:
if (-90.0, 30.0) == (-90.00,30.00)
# Doesn't Work
if (-90.0, -10.0) == (-90.00,-10.00)
(By the way the first tuple uses the vales stated previously, player_coordinate[0], player_coordinate[1] + movement, so i have no clue why it returns with one decimal place instead of two like in the original .pos() tuple but it shouldn't matter because the problem only occurs when the y-value is negative)
It looks like it is saying that -10.0 is not equal to -10.00. Any ideas on why this might not be working?
Here is the actual code too if it helps. I use 'in' because Im storing all of the space coordinates in a dictionary:
def player_movement(player, total, direction):
current = player.pos()
if direction == 'up':
if (current[0], current[1] + total) in space_coordinates.values():
player.shape('Player_Up.gif') # Changes player sprite
player.goto(current[0], current[1] + total) # Moves player
I already checked if the coordinate I needed was in the dictionary and it was
Turtles wander a floating point plane so exact comparisons are to be avoided. Instead of asking:
turtle_1.position() == turtle_2.position()
you should consider asking:
turtle_1.distance(turtle_2) < 10
That is, are they in close proximity to each other, not on the exact same coordinate.
Related
I am working on a ground station to track our future cubesat, one of the things needed is to calculate the doppler shift in the frequency as it passes over head. To test this we are using the ISS TLE. I am using Skyfield and it has been super helpful, but I am having a simple issue that I can't seem to figure out. I need the velocity of the object, which has been easily attained, but I also need the direction relative to my position. I assumed it would be part of the velocity vector, since velocity is both magnitude and direction. Maybe I'm missing something in the code that is obvious, the way it is fixed at the moment is to get the distance at two points in time and figure out if its closing in or distancing itself. Then I simply multiply the vector by -1 if its closing in, and 1 otherwise. I figured something like this would be handled with the .velocity function but it does not seem so.
diff = satObsDiff.at(ts_now)
diff1 = satObsDiff.at(ts_next)
velocity = diff.speed().km_per_s * 1000 #converts km to m
print("Velocity: ")
print(velocity)
adjusted_velocity = velocity
range1 = diff.distance().km
range2 = diff1.distance().km
change = (range1 - range2)*1000
direction = 1
if change >= 0:
direction = 1
else:
direction = -1
observed_freq = ((C/(C + (adjusted_velocity * direction))) * emitted_freq)
The dot product of two vectors is positive if they are pointing in the same direction, zero if they are at right angles, and negative if they are pointing away from each other. So I suspect you can tell an approaching from a receding satellite by computing the dot product of the relative position with the velocity and checking whether it is more or less than zero:
d = np.dot(velocity.km, diff.position.km)
if d > 0:
print('receding')
else:
print('approaching')
You can also toss in some division if you want to know how fast the range is changing:
https://stackoverflow.com/a/55226228/85360
For the following problem, I used a dictionary to track values while the provided answer used a list. Is there a quick way to determine the most efficient data structures for problems like these?
A robot moves in a plane starting from the original point (0,0). The
robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The
trace of robot movement is shown as the following: UP 5 DOWN 3 LEFT 3
RIGHT 2. The numbers after the direction are steps. Please write a
program to compute the distance from current position after a sequence
of movement and original point. If the distance is a float, then just
print the nearest integer. Example: If the following tuples are given
as input to the program: UP 5 DOWN 3 LEFT 3 RIGHT 2 Then, the output
of the program should be: 2
My answer uses a dictionary (origin["y"] for y and origin["x"] for x):
direction = 0
steps = 0
command = (direction, steps)
command_list = []
origin = {"x": 0, "y": 0}
while direction is not '':
direction = input("Direction (U, D, L, R):")
steps = input("Number of steps:")
command = (direction, steps)
command_list.append(command)
print(command_list)
while len(command_list) > 0:
current = command_list[-1]
if current[0] == 'U':
origin["y"] += int(current[1])
elif current[0] == 'D':
origin["y"] -= int(current[1])
elif current[0] == 'L':
origin["x"] -= int(current[1])
elif current[0] == 'R':
origin["x"] += int(current[1])
command_list.pop()
distance = ((origin["x"])**2 + (origin["y"])**2)**0.5
print(distance)
The provided answer uses a list (pos[0] for y, and pos[1] for x):
import math
pos = [0,0]
while True:
s = raw_input()
if not s:
break
movement = s.split(" ")
direction = movement[0]
steps = int(movement[1])
if direction=="UP":
pos[0]+=steps
elif direction=="DOWN":
pos[0]-=steps
elif direction=="LEFT":
pos[1]-=steps
elif direction=="RIGHT":
pos[1]+=steps
else:
pass
print int(round(math.sqrt(pos[1]**2+pos[0]**2)))
I'll offer a few points on your question because I strongly disagree with the close recommendations. There's much in your question that's not opinion.
In general, your choice of dictionary wasn't appropriate. For a toy program like this it doesn't make much difference, but I assume you're interested in best practice for serious programs. In production software, you wouldn't make this choice. Why?
Error prone-ness. A typo in future code, e.g. origin["t"] = 3 when you meant origin["y"] = 3 is a nasty bug, maybe difficult to find. t = 3 is more likely to cause a "fast failure." (In a statically typed language like C++ or Java, it's a sure compile-time error.)
Space overhead. A simple scalar variable requires essentially no space beyond the value itself. An array has a fixed overhead for the "dope vector" that tracks its location, current, and maximum size. A dictionary requires yet more extra space for open addressing, unused hash buckets, and fill tracking.
Speed.
Accessing a scalar variable is very fast: just a few processor instructions.
Accessing a tuple or array element when you know its index is also very fast, though not as fast as variable access. Extra instructions are needed to check array bounds. Adding one element to an array may take O(current array size) to copy current contents into a larger block of memory. The advantage of tuples and arrays is that you can access elements quickly based on a computed integer index. Scalar variables don't do this. Choose an array/tuple when you need integer index access. Favor tuples when you know the exact size and it's unlikely to change. Their immutability tends to make code more understandable (and thread safe).
Accessing a dictionary element is still more expensive because a hash value must be computed and buckets traversed with possible collision resolution. Adding a single element can also trigger a table reorganization, which is O(table size) with constant factor much bigger than list reorganization because all the elements must be rehashed. The big advantage of dictionaries is that accessing all stored pairs is likely to take the same amount of time. You should choose a dict only when you need that capability: to store a "map" from keys to values.
Conclude from all the above that the best choice for your origin coordinates would have been simple variables. If you later enhance the program in a way that requires passing (x, y) pairs to/from methods, then you'd consider a Point class.
I write a simple program in python which includes moving my mouse (I do his with PyUserInput).
However: It is only allowed to move the mouse in integer steps (say pixels).
So mouse.move(250.3,300.2) won't work.
I call the move function about 30 times in a second and move the mouse a few pixels. The speed with which I move the mouse varies from 0.5-2.5px/call. Rounding gives me 1-3 (move only want ints) which does not really represent the speed.
I search for a solution (maybe generator?) which takes my current speed (e.g. 0.7px) and gives me back a pattern (like a PWM Signal) out of 0 and 1 (e.g. 1,1,0,1,1,0...) which yields the 0.7px in average.
However this generator has to be adaptive because speed is constantly changing.
I am quite new to python and stuck with the last point: The variability of the generator function.
Here is what I have so far:
# for 0.75px/call
def getPWM(n):
nums = [1,0,1,1]
yield nums[n%4]
What you need to do is keep track of the previous position and the desired current position, and hand out the rounded coordinate. You could track the previous position in a function but it's much easier to do it in a class.
class pwm:
def __init__(self):
self.desired_position = 0.0
self.actual_position = 0
def nextPWM(self, speed):
self.desired_position += speed
movement = round(self.desired_position - self.actual_position)
self.actual_position += movement
return movement
I have a GL_QUAD which is basically a big field that the player is able to walk on. However, I want the player to have the abilty to 'jump,' meaning when he returns to his original y position he must stop falling. How do I access the world coordinates of a GL_QUAD so I can compare the y values of the quad and the player to determine whether he should stop falling?
I've got an array of data filled with "#" and "." for example it display something like this :
...........#############..............................
.........################..................#######....
........##################................#########...
.......####################..............###########..
........##################................#########...
.........################..................#######....
...........#############..............................
I want to create an algorithm that find the bigger ball and erase the smaller one.
I was thinking of using the longest sequence of "#" to know what is the diameter.
So i've got something like this :
x = 0
longest_line = 0
for i in range(0, nbLine) :
for j in range(0, nbRaw) :
if data[i, j] = red :
x = x+1
if data[i, j+1] != red:
And i don't know what to do next..
I would use some sort of a segmentation algorithm, and then simply count the number of pixels in each object. Then simply erase the smaller one, which should be easy as you have a tag of the object.
The segmentation algorithms typically work like this.
Perform a raster scan, starting upper left, working towards bottom right.
As you see a #, you know you have an object. Check it's neighbors.
If the neighbors have a previously assigned value, assign that value to it
If there there are multiple values, put that into some sort of a table, which after you are done processing, you will simplify.
So, for a very simple example:
...##...
.######.
...##...
Your processing will look like:
00011000
02111110
00011000
With a conversion such that:
2=>1
Apply the look up table, and all objects will be tagged with a 1 value. Then simply count the number of pixels, and you are done.
I'll leave the implementation to you;-)
Get your data into a nicer array structure
Perform connected component labelling
Count the number of elements with each label (ignoring the background label)
Choose the label with the largest number of elements
Do you olways have only 2 shapes like this? Because in this case, you could also use the python regular expression library. This code seems to do the trick for your example (I copied your little drawing in a file and named it "balls.txt"):
import re
f = open("balls.txt", "r")
for line in f :
balls = re.search("(\.+)(#+)(\.+)(#*)(\.+)", line)
dots1 = balls.groups()[0]
ball1 = balls.groups()[1]
dots2 = balls.groups()[2]
ball2 = balls.groups()[3]
dots3 = balls.groups()[4]
if len(ball1) < len(ball2):
ball1 = ball1.replace('#', '.')
else:
ball2 = ball2.replace('#', '.')
print "%s%s%s%s%s" % (dots1, ball1, dots2, ball2, dots3)
And this is what I get:
...........#############..............................
.........################.............................
........##################............................
.......####################...........................
........##################............................
.........################.............................
...........#############..............................
I hope this can give you some ideas for the resolution of your problem
Assuming the balls don't touch:
Assuming exactly two balls
Create two ball objects, (called balls 0 and 1) each owns a set of points. Points are x,y pairs.
scan each row from top to bottom, left to right within each line.
When you see the first #, assign it to ball 0 (add it’s x,y cords to the set owned by the ball 0 object).
When you see any subsequent #, add it to ball 0 if it is adjacent to any point already in ball 0; otherwise add it to ball 1. (If the new # is at x, y we just test (x+1,y) is in set, (x-1, y) is in set, (x, y+1) is in set, (x, y-1) is in set, and the diagonal neighbors)
When the scan is complete, the list sizes reveal the larger ball. You then have a list of the points to be erased in the other ball’s points set.