Strange pygame Rect glitch in python 3 - python

I'm currently making a game on pygame in Python 3. One part of my code is:
if (ballrect.bottom >= brick.top) and (ballrect.top <= brick.bottom) and (ballrect.left >= brick.right) and (ballrect.right <= left):
where ballrect and brick are pygame.Rect variables. When ran, the program crashes and I get the following:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "E:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 685, in runfile
execfile(filename, namespace)
File "E:\WinPython-64bit-3.4.3.4\python-3.4.3.amd64\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 85, in execfile
exec(compile(open(filename, 'rb').read(), filename, 'exec'), namespace)
File "E:/Comp_Sci/game-balls/pad_bounce_3.py", line 158, in <module>
if (ballrect.bottom >= brick.top) and (ballrect.top <= brick.bottom) and (ballrect.left >= brick.right) and (ballrect.right <= left):
NameError: name 'left' is not defined
and 'left' is supposed to be an attribute of the pygame.Rect class. Even more interestingly, I use the 'left' attribute several times in my code and it works fine...
What am I doing terribly wrong?
EDIT: I found the issue. What was happening is that, at times, ballrect would sometimes not be defined.

The variable 'left' at the end of the condition, is it defined? and (ballrect.right <= left): Did you mean brick.left? Try:
if (ballrect.bottom >= brick.top) and (ballrect.top <= brick.bottom) and (ballrect.left >= brick.right) and (ballrect.right <= brick.left):
From what I can tell it might be better to use brick.collidepoint(ballrect)

I found the issue. What was happening is that, at times, ballrect would sometimes not be defined.

Related

I got an Typing Error an I have when looking at the tutorial that I was watching and I can't find out what I misspelled [duplicate]

I want to my program to increase the pensize of Python's turtle when the Page UP key is pressed.
I tried the following:
#!/usr/bin/env python3
import turtle
wn=turtle.Screen()
wn.title('Control using first letter of desired action')
py=turtle.Turtle()
py.color('blue')
size=1
def front():
py.fd(90)
def back():
py.bk(90)
def right():
py.rt(45)
def left():
py.lt(45)
def increasize():
global size
while size>=1 and size<=20:
py.pensize+=1
def decreasize():
global size
while size>=1 and size<=20:
py.pensize-=1
wn.onkey(front,'w')
wn.onkey(back,'s')
wn.onkey(right,'d')
wn.onkey(left,'a')
wn.onkey(increasize,'Prior')
wn.onkey(decreasize,'Next')
wn.listen()
wn.mainloop()
But it gives an error. Full traceback:
Exception in Tkinter callback
Traceback (most recent call last):
File "c:\program files\python3\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "c:\program files\python3\lib\turtle.py", line 686, in eventfun
fun()
File "D:\Python\draw_straight_key.py", line 19, in increasize
py.pensize+=1
TypeError: unsupported operand type(s) for +=: 'method' and 'int'
Exception in Tkinter callback
Traceback (most recent call last):
File "c:\program files\python3\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "c:\program files\python3\lib\turtle.py", line 686, in eventfun
fun()
File "D:\Python\draw_straight_key.py", line 23, in decreasize
py.pensize-=1
TypeError: unsupported operand type(s) for -=: 'method' and 'int'
It looks like pensize() is a method (not a variable) and needs to be called: https://docs.python.org/2/library/turtle.html#turtle.pensize
Try this:
pensize = py.pensize()
pensize += 1
py.pensize(pensize)
You need to call the pensize method with the new size. A method reference cannot be added to
For example, in increasize
size += 1
py.pensize(size)
Also, unless you want the size to always be one size (20), then change the while loop to an if statement
while size>=1 and size<=20:

List or Tuple without Brackets not for printing

Im trying to make a bot using pyautogui. Im saving some important pixel with x , y location. There are some game cards on that locations. But I cant use them. Im using click funtion to click but i dont want to enter position everytime, i want to use same pixel location. Any help or idea appreciated.
from pyautogui import *
import pyautogui
import time
import keyboard
import random
import win32api, win32con
resimler = []
card1x = (833, 958, 1083)
card1y = (477, 622)
card2x =(809, 909, 1009, 1109)
card2y =(493, 609)
card3x =(833, 960, 1087)
card3y =(292, 464, 636, 808)
card4x =(809, 909, 1009, 1109)
card4y =(310, 470, 630, 790)
card5x =(809, 909, 1009, 1109)
card5y =(286, 418, 550, 682, 814)
cards =((card1x[0], card1y[0]),(card1x[1],card1y[0]),(card1x[2],card1y[0]),(card1x[0],card1y[1]),(card1x[1],card1y[1]),(card1x[2],card1y[1]),(card2x[0],card2y[0]),(card2x[1],card2y[0]),(card2x[2],card2y[0]),(card2x[3],card2y[0]),(card2x[0],card2y[1]),(card2x[1],card2y[1]),(card2x[2],card2y[1]),(card2x[3],card2y[1]))
When i print this, its printing
print(cards[5])
#(100,200)
but i need numbers for click funtion like this 100,200
Btw I will use like this
i=0
def click(x,y):
win32api.SetCursorPos((x,y))
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,0,0)
win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,0,0)
def list_islem(color):
global i
images.append(color)
if colorin images[:-1]:
print("bulundu")
click(cards[images.index(color)])
click(cards[i])
images.pop(images.index(color))
images.pop()
i-=1
print(images)
else:
print("bulunamadı")
print(images)
i+=1
when i use list_islem function i got this error
bulunamadı
[255]
bulundu
Traceback (most recent call last):
File "C:\Users\Gungor\Desktop\n11\bot.py", line 67, in <module>
list_islem(b)
File "C:\Users\Gungor\Desktop\n11\bot.py", line 44, in list_islem
click(cards[resimler.index(renk)])
TypeError: click() missing 1 required positional argument: 'y'
Think you're looking for the * tuple unpacking operator? Try the following
click(*cards[i]) # Using Tuple Unpacking
click(cards[i][0], cards[i][1]) # Which is equivalent to this

Space Invaders: Loading Images

I'm trying to make Space Invaders as a project, I've watched videos on creating it and I have done quite a bit.
I've played around with it a lot, but there's always that one thing that goes wrong which messes up the entire thing.
This is my first post here, I'm not quite sure how to do this... let's see...
I keep facing this error, and it's not budging:
C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py:198: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
pygame.draw.rect(window, (0, 255, 0), (
Traceback (most recent call last):
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 415, in <module>
main_menu()
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 410, in main_menu
main()
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 377, in main
boss.shoot()
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 90, in shoot
laser = Laser(self.x - 20, self.y, self.laser_img)
File "C:/Users/Dell/PycharmProjects/Tutorial(2)/main.py", line 109, in __init__
self.mask = pygame.mask.from_surface(self.img)
TypeError: argument 1 must be pygame.Surface, not None
Can anyone help me fix it? I'm not sure what to do here.
Look at this line here
boss = Boss(random.randrange(340, 360), random.randrange(-700, -100))
This is how you are instantiating your Boss
Now look at how you defined the init of your Boss class
def __init__(self, x, y, health=200):
self.x = x
self.y = y
self.health = health
self.ship_img = None
self.laser_img = None
self.lasers = []
self.cool_down_counter = 0
Notice that self.laser_img = None.
Now notice the error you have:
laser = Laser(self.x - 20, self.y, self.laser_img)
Your 3rd argument is None. Now look at the next part of your error:
self.mask = pygame.mask.from_surface(self.img)
self.img is actually None that is why you are getting an error.

Having a difficult time resolving "TypeError: 'list' object is not callable" issue

Error:
Traceback (most recent call last): File
"/root/PycharmProjects/Capstone2/main", line 207, in
for paramIndex in range(0, 4): TypeError: 'list' object is not callable
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"/root/PycharmProjects/Capstone2/main", line 249, in
print('stream ending') File "/usr/lib/python3/dist-packages/picamera/camera.py", line 758, in
exit
self.close() File "/usr/lib/python3/dist-packages/picamera/camera.py", line 737, in
close
self.stop_recording(splitter_port=port) File "/usr/lib/python3/dist-packages/picamera/camera.py", line 1198, in
stop_recording
encoder.close() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 431, in
close
self.stop() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 815, in
stop
super(PiVideoEncoder, self).stop() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 419, in
stop
self._close_output() File "/usr/lib/python3/dist-packages/picamera/encoders.py", line 349, in
_close_output
mo.close_stream(output, opened) File "/usr/lib/python3/dist-packages/picamera/mmalobj.py", line 371, in
close_stream
stream.flush() ValueError: flush of closed file
Relevant Code:
angle = []
distance = []
speed = []
current = []
timestamp = []
parameterList = []
parameterList.extend((angle, distance, speed, current, timestamp))
for paramIndex in range(0, 4): # LINE 207
# Select Range
range = getRange(index, paramIndex + 5)
cell_list = sheet.range(range[0], range[1], range[2], range[3])
cellIndex = 0
for cell in cell_list:
try:
cell.value = parameterList[paramIndex][cellIndex]
except:
print("PI: " + str(paramIndex))
print("CI: " + str(cellIndex))
print("PL LEN: " + str(len(parameterList)))
print("P LEN: " + str(len(parameterList[paramIndex])))
My Thoughts:
The error makes me think that paramIndex is a list and not an integer but the code executes fine for the first four iterations. This makes me think that there is something wrong with my last list (timestamp). The only thing that I can imagine being wrong with my last list is some sort of index out of bounds issue but...
The except block is never hit
The largest value cellIndex reaches is 30 (expected)
The length of parameterList is 5 (expected)
The length of timestamp is 31 (expected)
I am stumped. If anyone can offer some help that would be greatly appreciated.
paramIndex is fine but you need to avoid calling variables the same name as your functions. In this case, range() is a standard python function but you create a variable called 'range'. Thereafter if you tried to use the range function you'd get an 'object is not callable' error because it's trying to use your range object as the standard range function.
If you insist on wanting to keep the range object name then use xrange() instead of range() where you define your for loop and you shouldn't get any conflicts.

Decryption function: 'int' object is not callable

I've written code for a function that executes decryption of individual characters. I received this error message: 'int' object is not callable, but I don't know which object this is referring to and how exactly I'm illegally calling something. What did I do wrong? Thanks.
def affine_cipher_decryption(ch,N,alphabet):
M = len(alphabet)
A = get_smallest_co_prime(M)
A_inverse = multiplicative_inverse(A,M)
counter = -1
for element in alphabet:
if element == ch:
counter += 1
index = counter
break
else:
counter += 1
cipher_index = A_inverse(index-N) % M
cipher_ch = alphabet[cipher_index]
return cipher_ch
Here is the error traceback message:
Traceback (most recent call last):
File "", line 1, in
runfile('/Users/brandononeil/Documents/SS18proj04.py', wdir='/Users/brandononeil/Documents')
File
"/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py",
line 880, in runfile
execfile(filename, namespace)
File
"/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py",
line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "/Users/brandononeil/Documents/SS18proj04.py", line 161, in
main()
File "/Users/brandononeil/Documents/SS18proj04.py", line 148, in
main
decr_ch1 = affine_cipher_decryption(ch, rotation, ALPHA_NUM)
File "/Users/brandononeil/Documents/SS18proj04.py", line 101, in
affine_cipher_decryption
cipher_index = multiplicative_inverse(A,M)(index-N) % M
TypeError: 'int' object is not callable
Also, here are the contents of multiplicative_inverse:
def multiplicative_inverse(A,M):
for x in range(M):
if (A*x)%M == 1:
return x
I've already tried renaming A_inverse, and I've tried writing the contents of the multiplicative_inverse function inside of affine_cipher_decryption (so I wouldn't have to call multiplicative_inverse) to no avail.
Any ideas of what else could be wrong?
Your problem is these two lines:
A_inverse = multiplicative_inverse(A,M)
cipher_index = A_inverse(index-N) % M
A_inverse is set to the result of multiplicative_inverse which I'm assuming returns an int. The second line tries to call a function named A_inverse but the local variable shadows the function in the scope.
You can fix it by renaming either the local variable or the function.

Categories

Resources