Constructing Rectangular with Python - python

Is there any way to make area() refer to check()?
Currently, codes of check() is the same in area().
class Rectangle:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
def check(self): #Checking this rectangle
if abs(self.x1-self.x2) == 0 or abs(self.y1-self.y2)==0:
return False
else :
return True
def area(self): #Calculating width
if abs(self.x1-self.x2) == 0 or abs(self.y1-self.y2)==0:
return False
else :
area = abs(self.x1-self.x2)*abs(self.y1-self.y2)
return area

In your check(self) method, you don't need any if nor abs().
You can just do:
def check(self):
return self.x1 != self.x2 and self.y1 != self.y2
About the area(self) method, you could just do:
def area(self):
if not self.check():
return False
else:
return abs(self.x1-self.x2)*abs(self.y1-self.y2)
Now your code should be cleaner.

Related

How should I fix code where the rectangle I created with tkinter doesn't move with the arrow keys?

I am trying to create a program that draws a rectangle in the center of the canvas. The rectangle is supposed to get wider when the right arrow key is pressed, and narrower when the left arrow key is pressed. I seem to have the rectangle, but there is no movement.
So far, the code I have is:
from tkinter import *
root = Tk()
canvas = Canvas(root, width=400, height=300, bg="#000000")
canvas.pack()
x1 = 150
y1 = 100
x2 = 250
y2 = 200
class ResizeRect:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.rect = canvas.create_rectangle(0,0,1,1)
def draw(self):
canvas.delete(self.rect)
self.rect = canvas.create_rectangle(x1, y1, x2, y2,
outline="#00B000", width=2)
def narrower(self):
self.x1 = self.x1 + 5
self.x2 = self.x2 - 5
def wider(self):
self.x1 = self.x1 - 5
self.x2 = self.x2 + 5
r = ResizeRect(150, 100, 250, 200)
r.draw()
def left():
r.narrower()
def right():
r.wider()
canvas.bind_all('<KeyPress-Left>', left)
canvas.bind_all('<KeyPress-Right>', right)
WHen I run this code, a rectangle appears but does not move when I press the arrow keys. How can I fix this without altering my original code too much?
You have two problems. First, left and right will automatically be passed an object representing the event. You need to make sure that these functions accept this parameter even if you don't use it.
def left(event):
r.narrower()
def right(event):
r.wider()
Second, simply setting the coordinate won't cause the rectangle to move. You must configure the rectangle with new coordinates using the coords method if you want the coordinates of the actual object to change.
def narrower(self):
self.x1 = self.x1 + 5
self.x2 = self.x2 - 5
canvas.coords(self.rect, self.x1, self.y1, self.x2, self.y2)
def wider(self):
self.x1 = self.x1 - 5
self.x2 = self.x2 + 5
canvas.coords(self.rect, self.x1, self.y1, self.x2, self.y2)

Tkinter Rectangle connected to Keypress

The following program draws a rectangle in the center of the canvas. The rectangle is supposed to get wider when the right arrow key is pressed, and narrower when the left arrow key is pressed.
Here's the code:
from tkinter import *
root = Tk()
canvas = Canvas(root, width=400, height=300, bg="#000000")
canvas.pack()
x1 = 150
y1 = 100
x2 = 250
y2 = 200
class ResizeRect:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.rect = canvas.create_rectangle(0,0,1,1)
def draw(self):
canvas.delete(self.rect)
self.rect = canvas.create_rectangle(x1, y1, x2, y2,
outline="#00B000", width=2)
def narrower(self):
self.x1 = self.x1 + 5
self.x2 = self.x2 - 5
def wider(self):
self.x1 = self.x1 - 5
self.x2 = self.x2 + 5
r = ResizeRect(150, 100, 250, 200)
r.draw()
def left(event):
r.narrower()
r.draw()
def right(event):
r.wider()
r.draw()
canvas.bind_all('<KeyPress-Left>', left)
canvas.bind_all('<KeyPress-Right>', right)
My teacher told me that I need to add the 'self' keyword to the parameters in the draw function but I don't know what he means. (I can't ask him more because he's in a bad mood right now.). Any help is much appreciated.

Why is turtle not drawing in Python 3 in Line class?

I am writing a Line class to draw a line given the coordinates of two points. However, when I run this program, the turtle does not draw anything. Is there an error in the way I defined my Draw() method or called it? I'm not very familiar with Python3 and classes. Here is my code:
from turtle import *
g = Turtle()
class Line():
def __init__(self, x1, y1, x2, y2):
self.X1 = x1
self.Y1 = y1
self.X2 = x2
self.Y2 = y2
self.Draw(x1, y1, x2, y2)
def getX1():
return self.X1
def getY1():
return self.Y1
def getX2():
return self.X2
def getY2():
return self.Y2
def Draw(self, x1, y1, x2, y2):
g.penup()
g.goto(x1, y1)
g.pendown()
g.goto(x2, y2)
def main():
theLine = Line(0, 0, 100, 100)
theLine.Draw()
The function Draw you defined takes 5 arguments (self, x1, y1, x2, y2). But what you want is to get the coordinates information from the Line object.
That's why the self parameter exists. The self parameter is the object itself, so instead of using x1, y1, x2 and y2, you want to use the values stored in the object, like so:
self.x1, self.y1, self.x2 and self.y2. after you change the these, you should also remove the unnecessary arguments of the function (everything except self)
Final code
def Draw(self): # Removed the arguments
g.penup()
g.goto(self.X1, self.Y1) # Go to the starting point stored in the object
g.pendown()
g.goto(self.X2, self.Y2) # Go to the endpoint stored in the object

How can I use a class' variables in another class?

I have a Drone class and a Building class. The Building class has two attributes named x0 and y0. I want to use these two variables' values in the Drone class, but I haven't been able to wrap my head around how that would be done.
Here's the code for Building:
class Building(Agent):
def __init__(self, pos, x0, y0, model, request=False):
# Buildings won't have requests initially (set to false)
super().__init__(pos, model)
self.pos = pos
self.x0 = x0
self.y0 = y0
self.model = model
self.request = request
And Drone:
class Drone(Agent):
grid = None
x = None
y = None
moore = True
def __init__(self, name, model, x, y, speed, battery, heading, moore=True):
super().__init__(name, model)
self.name = name
self.model = model
self.x = x
self.y = y
self.speed = speed
self.battery = battery
self.heading = heading
self.moore = moore
def step(self):
if self.name == 1:
if self.x < Building.x0:
self.x += 1
new_pos = self.x, self.y
self.model.grid.move_agent(self, new_pos)
elif self.x > Building.x0:
self.x -= 1
new_pos = self.x, self.y
self.model.grid.move_agent(self, new_pos)
if self.y < Building.y0:
self.y += 1
new_pos = self.x, self.y
self.model.grid.move_agent(self, new_pos)
elif self.y > Building.y0:
self.y -= 1
new_pos = self.x, self.y
self.model.grid.move_agent(self, new_pos)
I don't believe you understand the philosophy of object-oriented programming. If they both require the same information (x0, y0), then they should be the same object, or x0 and y0 should be established on the object they inherit from so that the child classes already have the data. E.g.
agent.x0 = x0
agent.y0 = y0
so that both the building and the drone have this information on creation. But really, should consider refactoring.
class Building:
def __init__(self, x0, y0):
self.x0 = x0
self.y0 = y0
class Drone:
x = None
y = None
def __init__(self, x, y):
self.x = x
self.y = y
def step(self, building):
if self.x < building.x0:
etc
Your Building class doesn't have a class variable x0, y0. The instances of the Building class do. Thus your code of Building.x0 doesn't make sense.
building1 = Building(x_bldg, y_bldg)
drone1 = Drone(x_drn, y_drn)
drone1.step(building1)

How can I see if an x and y are on the edge or inside of the rectangle? How to define my method contains point?

How can I see if an x and y are on the edge or inside of the rectangle? Does anyone have any ideas of how to go about that?
I have tried to create a method that will do this called contains point but I am sure I have done this incorrectly
my code:
class Rectangle: # creates class Rectangle
def __init__(self, rX, rY, rW, rH): # initialized so we can call our variables
self.x = rX # x coord
self.y = rY # y coord
self.w = rW # width
self.h = rH # heigh
def __str__(self): # will return string
return 'Rectangle(' + str(self.x) + ',' + str(self.y) + ',' + str(self.w) + ',' + str(self.h)+')'
def right(self): # will check right edge
return self.x + self.w # returns right edge
def bottom(self):
return self.y + self.h
def size(self): # Method Size will obtain size of rectangle
return self.w, self.h
def position(self): # Method will show coords
return self.x, self.y
def area(self): # method will return area of rectangle
return self.w * self.h
def expand(self, offset): # expand will take in an offset value and apply it to a new rectangle
newX = self.x - offset
newY = self.y - offset
newW = self.w + (offset * 2)
newH = self.h + (offset * 2)
newRectangle = Rectangle(newX, newY, newW, newH)
return newRectangle
def contains_point(self, x, y): # contains point will take in 2 coords
# and check to see if they are in the rectangle
if x <= self.x and y <= self.y:
return True
else:
return False
r = Rectangle(30, 40, 100, 110)
print(r.expand(-5), r)
print(r.contains_point(0, 0))
If you have x1, x2 and y1, y2 defining the outer corners of your rectangle, then you can test a point.x, point.y by checking if point.x is between x1 and x2, and point.y is between y1 and y2.
def contains_point(self, x, y): # contains point will take in 2 coords
# and check to see if they are in the rectangle
if (self.x <= x <= self.right() and
self.y <= y <= self.bottom()):
return True
else:
return False

Categories