using the sum function to add points on a caretsian plane - python-3.x

The code is giving me an error. It's supposed to add points on a Cartesian plane.
class Cluster(object):
def __init__(self, x, y):
self.center = Point(x, y)
self.points = []
def update(self):
sum_ = sum(self.points, Point(0, 0))
len_ = float(len(self.points))
self.center = Point(sum_.x/len_, sum_.y/len_)
self.points = []
def add_point(self, point):
self.points.append(point)
sum_ = sum(self.points, Point(0, 0))

The sum() function only only works for types which support addition. A class can implement addition using the __add__ function. If this is indeed the problem you are facing, define in your Point class a function like:
class Point:
# ...
def __add__(self, other):
return Point(self.x + other.x, self.y + other.y)

Related

Class definition

My questions are the code I am running keeps giving me points has no argument, below is my code, please help check
class Point:
def _init_(self, x, y):
self.x = x
self.y = y
def draw(self):
print(f"Point ({self.x}, {self.y})")
point = Point(1, 2)
point.draw(point)

How can I access methods of a class that is passed as argument to another class in python

I want to create a class(say, LockedAttributes) to access(READ/WRITE) some attributes safely by multiple threads.I want to pass those attributes that I want to share as a list to the LockedAttributes class. Some of the list elements are itself class objects with it's own setter and getter.
How can i access those setter/getter from a LockedAttribute class obj?
My use of getattr() setattr() might be wrong.
sample code:
class Coord:
def __init__(self, x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
def set_coordinator(self, x, y, z):
self.x = x
self.y = y
self.z = z
def get_coordinator(self):
return self.x, self.y, self.z
class LockedAttributes(object):
def __init__(self, obj):
self.__obj = obj
self.__lock = RLock()
def getmyPosition(self):
with self.__lock:
return self.__obj[0]
def getmySpeed(self):
with self.__lock:
return self.__obj[1]
def getcolPosition(self):
with self.__lock:
return self.__obj[2]
def getDistfromCol(self):
with self.__lock:
getattr(self, self.__obj[3])
def setDistfromCol(self, value):
with self.__lock:
setattr(self, self.__obj[3], value)
def getcolactivationFlag(self):
with self.__lock:
getattr(self, self.__obj[4])
def setcolactivationFlag(self, value):
with self.__lock:
setattr(self, self.__obj[3], value)
class OBU():
def __init__(self):
pos = Coord()
speed = Coord()
colpos = Coord()
distance_from_accident = 0.0
Flag = False
self.shared_attributes = LockedAttributes([ pos, speed, colpos, distance_from_accident, Flag])
mypos= self.shared_attributes.getmyPosition()
mypos.get_coordinator() # Not workinh
The __init__ method of the LockedAttributes class should take an argument so that you can actually pass a list object to it.
Change:
class LockedAttributes(object):
def __init__(self):
self.__obj = object
self.__lock = RLock()
To:
class LockedAttributes(object):
def __init__(self, obj):
self.__obj = obj
self.__lock = RLock()

Creating a default

I have a point class which has 2-d point instances. I also have a magnitude function inside which returns the magnitude of said points. Below is my code...
class Point:
# """2-D Point objects."""
def __init__(self, x, y):
# """Initialize the Point instance"""
self.x = x
self.y = y
def get_magnitude(self):
# """Return the magnitude of vector from (0,0) to self."""
return math.sqrt(self.x ** 2 + self.y ** 2)
def __str__(self):
return 'Point at ({}, {})'.format(self.x,self.y)
def __repr__(self):
return "Point(x={},y={})".format(self.x,self.y)
point = Point(x=3, y=4)
print(str(point))
print(repr(point))
print(point)
...After doing all of this, the final part of this is to implement a default point of (0,0). Any suggestions on how to do this? It should work like this...
point2 = Point()
print(point2)
Point(x=0, y=0)
point3 = Point(y=9)
print(point3)
Point(x=0, y=9)
You can pass in default arguments to an initializer, just like you would any other function.
def __init__(self, x=0, y=0):
# """Initialize the Point instance"""
self.x = x
self.y = y

How to change a normal method into a property method

I have the below code which is working.
class Point:
# """2-D Point objects."""
def __init__(self, x=0, y=0):
# """Initialize the Point instance"""
self.x = x
self.y = y
def get_magnitude(self):
# """Return the magnitude of vector from (0,0) to self."""
return math.sqrt(self.x ** 2 + self.y ** 2)
def __str__(self):
return 'Point at ({}, {})'.format(self.x,self.y)
def __repr__(self):
return "Point(x={},y={})".format(self.x,self.y)
point = Point(x=3, y=4)
print(str(point))
print(repr(point))
print(point)
point2 = Point()
print(point2)
point3 = Point(y=9)
print(point3)
I want to change the get_magnitude method into a property method named magnitude which works as shown below.
point = Point(3, 4)
point
Point(x=3, y=4)
point.magnitude
5.0
point3 = Point(y=9)
point3.magnitude
9.0
How would I do this?
import math
class Point:
"""2-D Point objects."""
def __init__(self, x=0, y=0):
"""Initialize the Point instance"""
self.x = x
self.y = y
#property
def magnitude(self):
"""Return the magnitude of vector from (0,0) to self."""
return math.sqrt(self.x ** 2 + self.y ** 2)
def __str__(self):
return 'Point at ({}, {})'.format(self.x,self.y)
def __repr__(self):
return "Point(x={},y={})".format(self.x,self.y)
point = Point(3, 4)
print(point)
print(point.magnitude)
point3 = Point(y=9)
print(point3.magnitude)
Prints:
Point at (3, 4)
5.0
9.0

Python-Pygame sprite bounces when gravity is used

I am making a 8bit style platformer. The player falls and gains speed because of the pseudo gravity but he will fall a few pixels into the ground level. Without gravity he will land on the ground and not fall though but it is a constant fall speed.When in the ground you can go up but he will fall when you let up. He will not got down so that is not an issue for now. Any help would be appreciated.
The player class/file.
import pygame,sys
from pygame.locals import *
class Player:
x=0
y=0
offset = 5
L=False
R=False
U=False
D=False
image = None
gravity = .25
velocity = offset
objectDict = None #this si the list of the current objects so that collision can be check with every
#object.. get updated every loop to keep a accurate check of locations
rect = None
grav = True #TODO use this to check if we are paying attention to the gravity
def __init__(self,x,y):
self.x = x
self.y = y
self.image = pygame.image.load('Resources/Pics/player.png')
def draw(self,DISPLAY):
#print('draw will go here')
imgRect = self.image.get_rect()
imgRect.midleft = (self.x,self.y)
self.rect = imgRect
DISPLAY.blit(self.image, imgRect)
#and now im here
def checkCollide(self,otherRect):
return self.rect.colliderect(otherRect)
def checkCollideAll(self):
if(self.objectDict != None):
# print(len(self.objectDict))
# for x in range(1,len(self.objectDict)):
# newb = self.checkCollide(self.objectDict[x].getRect())
# print(self.objectDict[x].getRect())
# if(newb):
# return True
# return False
collideNum = self.rect.collidelist(self.objectDict)
if(collideNum == -1):
return False
else:
return True
def willCollideBelow(self):
if(self.objectDict):
checkRect = (self.x,(self.y),self.image.get_size())
collideNum = self.rect.collidelist(self.objectDict)
if collideNum == -1:
return False
else:
return True
def objUpdate(self,dict):
self.objectDict = dict
def getRect(self):
return self.rect
def update(self):
# while(self.checkCollideAll()):
# print('while happened')
# self.y -= self.offset
# imgRect = self.image.get_rect()
# imgRect.midleft = (self.x,self.y)
# self.rect = imgRect
# print(self.willCollideBelow())
if not self.willCollideBelow():
self.D = True
# print('will fall')
else:
self.D = False
if self.U == True:
self.y -= self.offset
if self.D == True:
self.y += self.velocity
if not self.velocity >= 9.8:
self.velocity += self.gravity
else:
self.velocity = self.offset
if self.L == True:
self.x -= self.offset
if self.R == True:
self.x += self.offset
You didn't provide a running example and your code is hard to read (pascal case, a lot of unnecessary parenthesis), but here's my guess:
In your willCollideBelow function, you check if you hit an object beneath the player:
def willCollideBelow(self):
if(self.objectDict):
checkRect = (self.x,(self.y),self.image.get_size())
collideNum = self.rect.collidelist(self.objectDict)
if collideNum == -1:
return False
else:
return True
instead of just returning True or False, return the object (or the index of the object) you actually collide with:
def will_collide_below(self):
if(self.objectDict):
# using 'collidelistall' would be better, but that's another topic
return self.rect.collidelist(self.objectDict)
Now that you know which object the player collides with, you can adjust the vertical position of the player:
ground_i = self.will_collide_below()
if ground_i:
ground = self.objectDict[ground_i]
self.velocity = 0
self.rect.bottom = ground.top # or self.y = ground.top
You'll get the idea.
Some more notes:
You use different variables to store the position of the player (I see x, y, rect and imgRect). It would make you code a lot simpler if you would just use a single Rect to store the position:
class Player:
...
def __init__(self,x,y):
self.image = pygame.image.load('Resources/Pics/player.png')
self.rect = self.image.get_rect(midleft=(x,y))
def draw(self, display):
display.blit(self.image, self.rect)
def update(self):
...
if self.L: # no need to check == True
self.rect.move_ip(-self.offset)
if self.R: # simply use move_ip to alter the position
self.rect.move_ip(self.offset)
You also use a bunch of class variables where you really should use instance variables, like rect, L, R, U and D.

Resources