I have the below image. I want to determine how many yellow(ish) pixels there are and the percentage of pixels in within the country that are yellow.
So, i need to disregard the sea, france and southern ireland.
Here is my attempt, but I have no idea how to disregard the stuff outside of the country
Also, how can we determine the size in Miles of each Pixel?
from PIL import Image
im = Image.open('covvv.png')
fiveg = 0
other = 0
sea = 0
for p in im.getdata():
if p[0] > 150 and p[1] > 150 and p[2] < 150:
fiveg += 1
elif p[0] == 170 and p[1] > 218 and p[2] < 255:
sea += 1
else:
other += 1
print('5g=' + str(fiveg)+', other='+str(other) + ', sea = 0' + str(sea))
print('%coverage= ' + str((fiveg/other)*100))
Related
For an university programming course final project me and my team are building a platfromer. I'm responsible for making a collisions system. Even though I was able to code one I'm not satisfied with the outcome due to its imperfection.
The problem is that occasionally when character is falling after reaching the platform the player and the block overlap with each other for one frame. Of course, they don't stay like that forever. I've made it so the character teleports back on top of the platform. However, that action is excecuted only in the second frame. For whoever plays this game it will seem like the character is glitching. I believe that the problem lies somewhere in the collision detection. Sadly I couldn't find it.
Any help would be appreciated.
Also I hope that this question won't be perceived as me begging someone else to complete my homework. I'm just striving for an advice :)
Collision detection function:
def Collision_Occurs(Block,Block_Length):
global Character, Max_Y_Speed
if(((Character.x <= Block.x + Block_Length and Character.x >= Block.x) or
(Character.x + 100 <= Block.x + Block_Length and Character.x + 100 >= Block.x)) and
(Character.y + 100 <= Block.y + Max_Y_Speed + 1 and Character.y + 100 >= Block.y)):
return True
return False
Entire game code:
import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((1000,650))
pygame.display.set_caption("The Game")
Block1 = pygame.Rect(250,500,500,50)
Block2 = pygame.Rect(100,250,250,50)
Block3 = pygame.Rect(650,250,250,50)
clock = pygame.time.Clock()
Character = pygame.Rect(200,100,100,100)
Moving_X = False
X_Speed = 0
Max_X_Speed = 5
Y_Speed = 0
Max_Y_Speed = 15
Collisions_Off_Timer = 0
Jump_Count = 0
Time_Since_Last_Jump = 60
'''
-------------------------------------------------------------
Collision Detection
-------------------------------------------------------------
'''
def Collision_Occurs(Block,Block_Length):
global Character, Max_Y_Speed
if(((Character.x <= Block.x + Block_Length and Character.x >= Block.x) or
(Character.x + 100 <= Block.x + Block_Length and Character.x + 100 >= Block.x)) and
(Character.y + 100 <= Block.y + Max_Y_Speed + 1 and Character.y + 100 >= Block.y)):
return True
return False
'''
-------------------------------------------------------------
Teleportation back on the platform
-------------------------------------------------------------
'''
def Teleport_Back_Up(Block):
global Character
Character.bottom = Block.top
'''
-------------------------------------------------------------
Game loop
-------------------------------------------------------------
'''
while True:
for event in pygame.event.get():
if(event.type == pygame.QUIT):
pygame.quit()
exit()
screen.fill((0,0,0))
pygame.draw.rect(screen,'Red',Block1)
pygame.draw.rect(screen,'Red',Block2)
pygame.draw.rect(screen,'Red',Block3)
pygame.draw.rect(screen,'Blue',Character)
'''
-------------------------------------------------------------
Input
-------------------------------------------------------------
'''
keys = pygame.key.get_pressed()
if(keys[pygame.K_DOWN]):
Collisions_Off_Timer = 5
if(keys[pygame.K_UP] and Jump_Count < 2 and Time_Since_Last_Jump >= 30):
Y_Speed = -20
Collisions_Off_Timer = 20
Jump_Count += 1
Time_Since_Last_Jump = 0
if(keys[pygame.K_RIGHT]):
Moving_X = True
if(X_Speed<Max_X_Speed):
X_Speed+=1
if(keys[pygame.K_LEFT]):
Moving_X = True
if(X_Speed>Max_X_Speed*(-1)):
X_Speed-=1
'''
-------------------------------------------------------------
Friction
-------------------------------------------------------------
'''
if not(Moving_X):
if X_Speed > 0:
X_Speed -= 1
if X_Speed < 0:
X_Speed += 1
Moving_X = False
if not(Y_Speed>Max_Y_Speed):
Y_Speed += 1
'''
-------------------------------------------------------------
Checking for collisions
-------------------------------------------------------------
'''
if(Y_Speed > 0 and Collisions_Off_Timer <=0):
if Collision_Occurs(Block1,500):
Teleport_Back_Up(Block1)
Y_Speed = 0
Jump_Count = 0
if Collision_Occurs(Block2,250):
Teleport_Back_Up(Block2)
Y_Speed = 0
Jump_Count = 0
if Collision_Occurs(Block3,250):
Teleport_Back_Up(Block3)
Y_Speed = 0
Jump_Count = 0
'''
-------------------------------------------------------------
Teleport back to the middle when vertical bounds are crossed
-------------------------------------------------------------
'''
if Character.y >=1500:
Character.x = 450
Character.y = 350
Y_Speed = 0
Collisions_Off_Timer -= 1
Time_Since_Last_Jump +=1
Character.x +=X_Speed
Character.y +=Y_Speed
pygame.display.update()
clock.tick(60)
Just do the move before collision detection. This corrects the y-position of the player (Teleport_Back_Up) after the player has been moved and before the display is updated:
while True:
# [...]
Character.x +=X_Speed # <--- INSERT
Character.y +=Y_Speed
'''
-------------------------------------------------------------
Checking for collisions
-------------------------------------------------------------
'''
if(Y_Speed > 0 and Collisions_Off_Timer <=0):
if Collision_Occurs(Block1,500):
Teleport_Back_Up(Block1)
Y_Speed = 0
Jump_Count = 0
if Collision_Occurs(Block2,250):
Teleport_Back_Up(Block2)
Y_Speed = 0
Jump_Count = 0
if Collision_Occurs(Block3,250):
Teleport_Back_Up(Block3)
Y_Speed = 0
Jump_Count = 0
# [...]
Collisions_Off_Timer -= 1
Time_Since_Last_Jump +=1
# Character.x +=X_Speed <--- DELETE
# Character.y +=Y_Speed
I have to arrange and/or fit 2d tiles into a 2d square or rectangular plane with AI algorithm using python program. Each tile has a length and width. For example if a plane is 4x3 and set of tiles is
S={(2,3),(1,2),(2,2)}
these tiles can be rotated 90 degrees in order to fit the matrix.
input
first line contains length and width of the plane
second line number of tiles
and then the length,width of the subsequent tiles
but the inputs should be tab seperated
for eg
4 3
3
2 3
1 2
2 2
output
for eg
1 1 2 2
1 1 3 3
1 1 3 3
I have trouble solving this as i have to use only standard libraries in python no NumPy and no CSP library
~Edit 2`
my code so far I cant figure out how to add algorithm without csp library or to generate grid
from sys import stdin
a = stdin.readline()
x = a.split()
rectangular_plane = [[0] * int(x[0]) for i in range(int(x[1]))]
num_of_rectangles = stdin.readline()
r_widths = []
r_lengths= []
for l in range(int(num_of_rectangles)):
b = stdin.readline()
y = b.split()
r_lengths.insert(l,y[0])
r_widths.insert(l,y[1])
I've solved task with backtracking approach and without any non-standard modules.
Try it online!
import sys
nums = list(map(int, sys.stdin.read().split()))
pw, ph = nums[0:2]
ts = list(zip(nums[3::2], nums[4::2]))
assert len(ts) == nums[2]
if sum([e[0] * e[1] for e in ts]) != pw * ph:
print('Not possible!')
else:
def Solve(*, it = 0, p = None):
if p is None:
p = [[0] * pw for i in range(ph)]
if it >= len(ts):
for e0 in p:
for e1 in e0:
print(e1, end = ' ')
print()
return True
for tw, th in [(ts[it][0], ts[it][1]), (ts[it][1], ts[it][0])]:
zw = [0] * tw
ow = [it + 1] * tw
for i in range(ph - th + 1):
for j in range(pw - tw + 1):
if all(p[k][j : j + tw] == zw for k in range(i, i + th)):
for k in range(i, i + th):
p[k][j : j + tw] = ow
if Solve(it = it + 1, p = p):
return True
for k in range(i, i + th):
p[k][j : j + tw] = zw
return False
if not Solve():
print('Not possible!')
Example input:
4 3
3
2 3
1 2
2 2
Output:
1 1 2 2
1 1 3 3
1 1 3 3
I am trying to plot a vertical line which represents depth. On different depths different types of soil are present and I would like to indicate these with different colors.
I have received data which is stored in a class. Based on a friction number I want to color the vertical line in three different colors. However, I don't know how I can achieve this.
The data is stored in ds1 (I have many different files (ds2, ds3, .. ds29) so making this work is convenient for me). ds1.depth calls the depth array, ds1.frictionnumber the friction number etc.
Due to the large amount of data and soil changes I don't know how to do this. It would be nice if something like below would work but I cannot get my head around it.
UPDATE: I found some code here -> http://abhay.harpale.net/blog/python/how-to-plot-multicolored-lines-in-matplotlib/
I adjusted my code and I get quite reasonable results, however something still goes wrong. In my data I've got 4 NaN values at the end (friction did not get measured). In the image below this should be from the horizontal line down, however that's not the case. How can I solve this, or what is going wrong?
UPDATE 2: The height of the line apparantly also scales with linewidth. Now I only need to find another way of plotting a wider line. Any suggestions are welcome.
def find_contiguous_colors(colors):
# finds the continuous segments of colors and returns those segments
segs = []
curr_seg = []
prev_color = ''
for c in colors:
if c == prev_color or prev_color == '':
curr_seg.append(c)
else:
segs.append(curr_seg)
curr_seg = []
curr_seg.append(c)
prev_color = c
segs.append(curr_seg) # the final one
return segs
def plot_multicolored_lines(x,y,colors):
segments = find_contiguous_colors(colors)
plt.figure(figsize=(12,8))
start= 0
for seg in segments:
end = start + len(seg)
l, = plt.gca().plot(x[start:end],y[start:end],lw=50,c=seg[0])
start = end
plt.axhline(-5.8988)
plt.axis('equal')
x = np.full(len(ds1.depth), 1)
y = ds1.depth
# color segments
colors = ['red']*len(ds1.depth)
for i in range(len(ds1.depth)):
if 0 < ds1.wrijvingsgetal[i] <= 1:
colors[i] = 'blue'
elif 1 < ds1.wrijvingsgetal[i] <= 2:
colors[i] = 'green'
elif ds1.wrijvingsgetal[i] > 2:
colors[i] = 'yellow'
else:
colors[i] = 'magenta'
Vertical soil profile
It's not efficient at all but I get the results I want. If someone knows how I could fix this by using stacked bargraph that is appreciated (for some reason I can't get it to work). My fix is presented below:
ds1 = read_gef(filepath)
def find_contiguous_colors(colors):
# finds the continuous segments of colors and returns those segments
segs = []
curr_seg = []
prev_color = ''
for c in colors:
if c == prev_color or prev_color == '':
curr_seg.append(c)
else:
segs.append(curr_seg)
curr_seg = []
curr_seg.append(c)
prev_color = c
segs.append(curr_seg)
return segs
def plot_multicolored_lines(x, y, colors):
segments = find_contiguous_colors(colors)
plt.figure(figsize=(12,8))
start= 0
for seg in segments:
end = start + len(seg)
l, = plt.gca().plot(x[start:end], y[start:end], lw=2, c=seg[0])
start = end
#plt.axhline(-5.8988, -1, 1)
x = np.full((len(ds1.depth), 2), 0)
y = np.array(ds1.depth)
# color segments
colors = ['red']*len(ds1.depth)
handle = [0] * 3
for i in range(len(ds1.depth)):
if 0 < ds1.wrijvingsgetal[i] <= 2:
colors[i] = 'yellow'
sandplt = plt.axhline(y[i], color=colors[i])
# elif 1 < ds1.wrijvingsgetal[i] <= 2:
# colors[i] = 'green'
# peatplt = plt.axhline(y[i], color=colors[i])
elif ds1.wrijvingsgetal[i] > 2:
colors[i] = 'green'
clayplt = plt.axhline(y[i], color=colors[i])
else:
colors[i] = 'magenta'
nanplt = plt.axhline(y[i], color=colors[i])
ratioxl = 1/5
plt.xlim(0, ratioxl*(ds1.depth[-1]-ds1.depth[0]))
plt.axis('scaled')
plt.ylabel('Depth w.r.t. groundlevel [m]')
plt.title('Vertical soil profile ' + str(Path(filepath).stem))
plt.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False) # labels along the bottom edge are off
plt.legend(handles = (sandplt, clayplt, nanplt), labels=['Sand', 'Clay', 'Nan'], loc=[1.01, 0.78])
plt.savefig(os.path.join(wd, '..', '03data', '20190711-Wiertsema', 'VN72650-1_GEF', 'afbeeldingen') + '\VSP_' + str(Path(filepath).stem))
plt.show()
Values including height = 10, number = 2, and bounciness = 6 should come to 25.6 feet, but I'm getting 23.2 feet. Can someone help me understand where my logic is screwed up please?
import math
# User inputs are set up
height = int(input("Enter the height of the ball: "))
number = int(input("Enter the number of bounces of the ball: "))
bounciness = int(input("Enter the height for each successive bounce: "))
count = 0
# Calculation
for count in range(bounciness):
count = (height * bounciness)/100
distance = height + count
bounceSum = number * bounciness
total = count + distance + bounceSum
# Results
print("The ball has traveled a total distance of", total, "feet.")
If you look at the calculation in the for loop, this is what happens in the first iterations (and ones after that too):-
count = 10*6/100 = 0.6
distance = 10 + 0.6 = 10.6 (count is 0.6 here because of the line above)
bounceSum = 2*12 = 12
total = 0.6 + 10.6 + 12 = 23.2
The problem with the logic in your code is the variable count. There are 3 different definitions of it and they keep overwriting the other:
count = 0 above the for loop
count which ranges from 0 to bounciness-1
count = (height*bounciness)/100
I think I fixed it...
import math
# User inputs are set up
height = int(input("Hello, please enter the height of the ball: "))
number = int(input("Next, enter the number of bounces of the ball: "))
bounciness = int(input("Now enter the height for each successive bounce: "))
index = 0
# Calculation
for index in range(bounciness):
index = bounciness * 0.6
distance = height + (bounciness * number)
total = index + distance
# Results
print("The ball has traveled a total distance of", total, "feet.")
print("Good bye")
So, I have this exercise where I have to find the nearest pharmacy from the coordinate inputted by the user, but i don't know how to.
I have a file with the coodinates from each pharmacy, like this:
300 200
10 56
25 41
90 18
70 90
100 50
And when the user input his coordinate ("20 88" in the example) i should tell him the coordinate from the nearest one. I'll write what I already have, but my codes are in Brazilian Portuguese, so i hope you can help me.
# Sub-programa
def fazTudo():
dados = open("texto.txt", "r")
linha = dados.readline()
if linha == "":
return "Arquivo de Farmácias está vazio!!!"
else:
for i in range(6):
distancia = []
vetor = dados.readline()
x, y = vetor.split()
distanciaX = x
distanciaY = y
distancia = distanciaX, distanciaY
# Programa Principal
entrada = (input().split(" "))
fazTudo()
It seems that the current stage you're at is reading the distances from the file.
From there, what you would want to do is find compare the users inputted location to the location of each pharmacy. Finding the smallest displacement in both the X and Y co-ordinates should get you the closest pharmacy. But since you want distance, you would want to convert the displacement value to distance by getting the absolute.
Here is a solution that I thought of:
# Find the closest distance to the pharmacies from a text file.
def closest_distance(raw_input_location):
nearest_pharmacy = [0, 0]
user_x_y = raw_input_location.split(" ")
with open("filename.txt") as f:
locations = f.read().splitlines()
if not locations:
return "Pharmacy list is empty!!!"
else:
for index, row in enumerate(locations):
x_y = row.split(" ")
delta_x = abs(int(user_x_y[0]) - int(x_y[0]))
delta_y = abs(int(user_x_y[1]) - int(x_y[1]))
if index == 0:
nearest_pharmacy[0] = delta_x
nearest_pharmacy[1] = delta_y
elif delta_x < nearest_pharmacy[0] & delta_y < nearest_pharmacy[0]:
nearest_pharmacy[0] = delta_x
nearest_pharmacy[1] = delta_y
# Returns the distance required to goto the closest pharmacy
return str(nearest_pharmacy[0]) + " " + str(nearest_pharmacy[1])
# Prints out the closest distance from the inputted location
print(closest_distance("20 88"))