help me please i have this code:
import sys, pygame
pygame.init()
size = width, height = 800, 600
speed = [2, 2]
black = 1, 1, 1
screen = pygame.display.set_mode(size)
ball = pygame.image.load("ball.bmp")
ballrect = ball.get_rect()
player1 = pygame.image.load("player1.png")
player1rect = player1.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
player1rect = player1rect.move(speed)
if player1rect.w < 0 or player1rect.s > heght:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect) (player1, player1rect)
pygame.display.flip()
and when i trying launch it it just saying:
Traceback (most recent call last):
File "C:\Users\User\Documents\Pong\pong.py", line 31, in <module>
screen.blit(ball, ballrect) (player1, player1rect)
TypeError: 'pygame.Rect' object is not callable
so is there anybody who can help me? and i have trying almost everything and it will not work and if there is something more wrong with my code so please write it.
(sorry for my bad english)
Replace line 31 with two lines that say:
screen.blit(ball, ballrect)
screen.blit(player1, player1rect)
This should fix your problem
Related
as for some background, my code is most likely a complete mess, mostly since I've only had a couple of hours scripting in my life.
For class im creating a solar system with all the standard planets and also the option for the user to input their own planet. Everything worked fine up until i tried letting the user spawn the planets with a button in the UI(an ugly button for now but a button nonetheless). If the user presses a button, say 'Sun', then the sun spawns, but only once, if he then decides to spawn sun again or any other planet for that matter, it gives an error stating that the module doesn't contain 'polycube or polysphere'. So basically, the button works once, then doesn't work anymore. If i call them from anywhere but the button, it works perfectly and indefinitely. I figured since he doesn't know polycube or polysphere, its almost as if i didn't import maya.cmds, so lets try recalling it. and low and behold that works.
So basically my question is as follows, does maya forget its imported libraries when you press a button? and How do i solve this without having to re-import maya.cmds in every function?
import maya.cmds as maya
class create_body:
def __init__(self, distance, radius, bonus_scale, r, g, b):
import maya.cmds as maya
self.radius = radius * bonus_scale / 1000
self.bonusScale = bonus_scale
self.distanceScene = distance
self.distanceMeter = distance*1000000000
maya.polyCube()
self.r = r
self.g = g
self.b = b
def color_body_custom(self):
import maya.cmds as maya
value = maya.colorEditor()
self.color = [float(i) for i in value.split()]
self.r = self.color[0]
self.g = self.color[1]
self.b = self.color[2]
def spawn_body(self):
import maya.cmds as maya
maya.polySphere(r = self.radius)
maya.move(self.distanceScene, moveZ = True)
maya.move(0, 0, 0, ".scalePivot", ".rotatePivot", absolute=True)
maya.polyColorPerVertex(rgb=(self.r,self.g,self.b), colorDisplayOption=True)
def animate_body(self):
import maya.cmds as maya
orbitTimeYears = self.get_orbital_time()*10
key = str(orbitTimeYears) + 'sec'
maya.setKeyframe(v=0, at='rotateY', t=['0sec'], itt = 'spline', ott = 'spline')
maya.setKeyframe(v=-360, at='rotateY', t=[key], itt = 'spline', ott = 'spline')
maya.selectKey(attribute='rotateY')
maya.setInfinity(pri='linear', poi='linear')
def get_orbital_time(self):
import math
orbitMeter = self.distanceMeter * 2 * math.pi
gravConst = 132690600000000000000 / self.distanceMeter
orbitSpeed = math.sqrt(gravConst)
orbitTimeSec = orbitMeter / orbitSpeed
orbitTimeYears = orbitTimeSec / 31556926
return orbitTimeYears
class create_ui:
def __init__(self, window_name):
self.myPlanetarySystem = window_name
# Make sure there's only one window open by deleting the window if it exists
self.delete_ui()
# Create the UI
self.myp = maya.window(self.myPlanetarySystem)
maya.rowColumnLayout(numberOfColumns=3, columnWidth=[(1, 150), (2, 75), (3, 75)], columnOffset=[(1, 'left', 5)])
maya.showWindow()
maya.window(self.myPlanetarySystem, e=True, title='TileGenerator', w=200, h=190)
maya.button(label = 'Sun', command = partial(self.body, 0, 695.510, 10, True, 1, 1, 0))
maya.button(label='Mercury', command = partial(self.body, 57.9, 2.439, 1000, False, 0.2, 0.2, 0))
#Sun = create_body(0, 695.510, 10, 1, 1, 0)
#Sun.spawn_body()
#Mercury = create_body(57.9, 2.439, 1000, 0.2, 0.2, 0)
#Mercury.spawn_body()
#Mercury.animate_body()
#Venus = create_body(108.2, 6.051, 1000, .5, 0.2, 0)
#Venus.spawn_body()
#Venus.animate_body()
#Earth = create_body(149.6, 6.971, 1000, 0, 0, 1)
#Earth.spawn_body()
#Earth.animate_body()
#Mars = create_body(227.9, 3.389, 1000, 0.6, 0.1, 0)
#Mars.spawn_body()
#Mars.animate_body()
#Jupiter = create_body(778.5, 69.911, 100, 0.9, 0.8, 0.5)
#Jupiter.spawn_body()
#Jupiter.animate_body()
#Saturn = create_body(1433.4, 58.232, 100, 0.8, 0.8, 0.7)
#Saturn.spawn_body()
#Saturn.animate_body()
#Uranus = create_body(2876.6, 25.362, 100, 0.7, 0.8, 1.0)
#Uranus.spawn_body()
#Uranus.animate_body()
#Neptune = create_body(4503.4, 24.622, 100, 0.3, 0.4, 0.7)
#Neptune.spawn_body()
#Neptune.animate_body()
def delete_ui(self):
if maya.window(self.myPlanetarySystem, exists=True):
maya.deleteUI(self.myPlanetarySystem, window=True)
def body(self, distance, radius, bonus_scale, is_sun, r = 0.5, g = 0.5, b = 0.5, *args):
obj = create_body(distance, radius, bonus_scale, r, g, b)
obj.spawn_body()
if not is_sun:
obj.animate_body()
create_ui('myPlanetarySystem')
Answer: apparently importing my maya.cmds in the shorter version: maya conflicted with the program, i should've seen this coming. In other words, there's no more issues if I just import maya.cmds as cmds.
Lets say I have class Truck. There are many instances of this class, on arrival to specific point instance should "unload" it's cargo - simply not move for N seconds, while other trucks should keep moving, unless they arrived to their unloading points.
I do the stop part by setting movement vector to (0,0) and then resetting it back to original.
But how to wait N seconds without freezing other cars? From what I've found so far I think I need to somehow apply pygame.time.set_timer, but it is really confusing for me.
Something along these lines should work: Stop the truck when the target is reached (truck.vel = Vector2(0, 0)) and then set its waiting_time and start_time attributes (I just do it in the __init__ method here).
import pygame as pg
from pygame.math import Vector2
class Truck(pg.sprite.Sprite):
def __init__(self, pos, waiting_time, *groups):
super().__init__(*groups)
self.image = pg.Surface((50, 30))
self.image.fill(pg.Color('steelblue2'))
self.rect = self.image.get_rect(center=pos)
self.vel = Vector2(0, 0)
self.pos = Vector2(pos)
self.waiting_time = waiting_time # In seconds.
self.start_time = pg.time.get_ticks()
def update(self):
current_time = pg.time.get_ticks()
# * 1000 to convert to milliseconds.
if current_time - self.start_time >= self.waiting_time*1000:
# If the time is up, start moving again.
self.vel = Vector2(1, 0)
self.pos += self.vel
self.rect.center = self.pos
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
truck = Truck((70, 70), 4, all_sprites)
truck2 = Truck((70, 300), 2, all_sprites)
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
all_sprites.update()
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
Here's the dt version:
import pygame as pg
from pygame.math import Vector2
class Truck(pg.sprite.Sprite):
def __init__(self, pos, waiting_time, *groups):
super().__init__(*groups)
self.image = pg.Surface((50, 30))
self.image.fill(pg.Color('steelblue2'))
self.rect = self.image.get_rect(center=pos)
self.vel = Vector2(0, 0)
self.pos = Vector2(pos)
self.waiting_time = waiting_time
def update(self, dt):
self.waiting_time -= dt
if self.waiting_time <= 0:
self.vel = Vector2(1, 0)
self.pos += self.vel
self.rect.center = self.pos
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
all_sprites = pg.sprite.Group()
truck = Truck((70, 70), 4, all_sprites)
truck2 = Truck((70, 300), 2, all_sprites)
done = False
while not done:
dt = clock.tick(30) / 1000
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
all_sprites.update(dt)
screen.fill((30, 30, 30))
all_sprites.draw(screen)
pg.display.flip()
if __name__ == '__main__':
pg.init()
main()
pg.quit()
I copy a code from a Web page to Python 2.7 but I didn't success.
The code is:
# Raspbery Pi Color Tracking Project
# Code written by Oscar Liang
# 30 Jun 2013
import cv2.cv as cv
import smbus
bus = smbus.SMBus(1)
address = 0x04
def sendData(value):
bus.write_byte(address, value)
# bus.write_byte_data(address, 0, value)
return -1
def readData():
state = bus.read_byte(address)
# number = bus.read_byte_data(address, 1)
return state
def ColorProcess(img):
# returns thresholded image
imgHSV = cv.CreateImage(cv.GetSize(img), 8, 3)
# converts BGR image to HSV
cv.CvtColor(img, imgHSV, cv.CV_BGR2HSV)
imgProcessed = cv.CreateImage(cv.GetSize(img), 8, 1)
# converts the pixel values lying within the range to 255 and stores it in the destination
cv.InRangeS(imgHSV, (100, 94, 84), (109, 171, 143), imgProcessed)
return imgProcessed
def main():
# captured image size, change to whatever you want
width = 320
height = 240
capture = cv.CreateCameraCapture(0)
# Over-write default captured image size
cv.SetCaptureProperty(capture,cv.CV_CAP_PROP_FRAME_WIDTH,width)
cv.SetCaptureProperty(capture,cv.CV_CAP_PROP_FRAME_HEIGHT,height)
cv.NamedWindow( “output”, 1 )
cv.NamedWindow( “processed”, 1 )
while True:
frame = cv.QueryFrame(capture)
cv.Smooth(frame, frame, cv.CV_BLUR, 3)
imgColorProcessed = ColorProcess(frame)
mat = cv.GetMat(imgColorProcessed)
# Calculating the moments
moments = cv.Moments(mat, 0)
area = cv.GetCentralMoment(moments, 0, 0)
moment10 = cv.GetSpatialMoment(moments, 1, 0)
moment01 = cv.GetSpatialMoment(moments, 0,1)
# Finding a big enough blob
if(area > 60000):
# Calculating the center postition of the blob
posX = int(moment10 / area)
posY = int(moment01 / area)
# check slave status and send coordinates
state = readData()
if state == 1:
sendData(posX)
sendData(posY)
print ‘x: ‘ + str(posX) + ‘ y: ‘ + str(posY)
# update video windows
cv.ShowImage(“processed”, imgColorProcessed)
cv.ShowImage(“output”, frame)
if cv.WaitKey(10) >= 0:
break
return;
if __name__ == “__main__”:
main()
I solved it. The right code is:
import cv2.cv as cv
import smbus
import cv2
bus = smbus.SMBus(1)
address = 0x04
def sendData(value):
bus.write_byte(address, value)
return -1
def readData():
state = bus.read_byte(address)
return state
def ColorProcess(img):
imgHSV = cv.CreateImage(cv.GetSize(img) ,8 ,3)
cv.CvtColor(img, imgHSV, cv.CV_BGR2HSV)
imgProcessed = cv.CreateImage(cv.GetSize(img) ,8 ,1)
cv.InRangeS(imgHSV, (100, 94, 84), (109, 171, 143), imgProcessed)
return imgProcessed
def main():
width = 320
height = 240
capture = cv.CreateCameraCapture(0)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, width)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, height)
cv.NamedWindow("output", 1)
cv.NamedWindow("processed", 1)
while True:
frame = cv.QueryFrame(capture)
cv.Smooth(frame, frame, cv.CV_BLUR, 3)
imgColorProcessed = ColorProcess(frame)
mat = cv.GetMat(imgColorProcessed)
moments = cv.Moments(mat, 0)
area = cv.GetCentralMoment(moments, 0, 0)
moment10 = cv.GetSpatialMoment(moments, 1, 0)
moment01 = cv.GetSpatialMoment(moments, 0, 1)
if (area > 60000):
posX = int(moment10/area)
posY = int(moment01/area)
ali = long(2000000)
state = readData()
if state == 1:
sendData(posX)
sendData(posY)
print 'x: ' + str(posX) + 'y: ' + str(posY)
cv.ShowImage("processed", imgColorProcessed)
cv.ShowImage("output", frame)
if cv.WaitKey(10) >= 0:
break
return;
if __name__ == "__main__":
main()
I have the code below and I want to modify it in many parts :
how can I use Raspbery Pi camera instead USB camera?
I will be grateful for anyone who gives me a hint or write the right code.
The code is :
import cv2.cv as cv
import smbus
import cv2
bus = smbus.SMBus(1)
address = 0x04
def sendData(value):
bus.write_byte(address, value)
return -1
def readData():
state = bus.read_byte(address)
return state
def ColorProcess(img):
imgHSV = cv.CreateImage(cv.GetSize(img) ,8 ,3)
cv.CvtColor(img, imgHSV, cv.CV_BGR2HSV)
imgProcessed = cv.CreateImage(cv.GetSize(img) ,8 ,1)
cv.InRangeS(imgHSV, (100, 94, 84), (109, 171, 143), imgProcessed)
return imgProcessed
def main():
width = 320
height = 240
capture = cv.CreateCameraCapture(0)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_WIDTH, width)
cv.SetCaptureProperty(capture, cv.CV_CAP_PROP_FRAME_HEIGHT, height)
cv.NamedWindow("output", 1)
cv.NamedWindow("processed", 1)
while True:
frame = cv.QueryFrame(capture)
cv.Smooth(frame, frame, cv.CV_BLUR, 3)
imgColorProcessed = ColorProcess(frame)
mat = cv.GetMat(imgColorProcessed)
moments = cv.Moments(mat, 0)
area = cv.GetCentralMoment(moments, 0, 0)
moment10 = cv.GetSpatialMoment(moments, 1, 0)
moment01 = cv.GetSpatialMoment(moments, 0, 1)
if (area > 60000):
posX = int(moment10/area)
posY = int(moment01/area)
ali = long(2000000)
state = readData()
if state == 1:
sendData(posX)
sendData(posY)
print 'x: ' + str(posX) + 'y: ' + str(posY)
cv.ShowImage("processed", imgColorProcessed)
cv.ShowImage("output", frame)
if cv.WaitKey(10) >= 0:
break
return;
if __name__ == "__main__":
main()
I will high appreciate any help.
Thanks.
Run this command in LX Terminal in Pi.It will take care of drivers.
sudo modprobe bcm2835-v4l2
I'm new to programming and my character goes out of the screen when I run the code. How can I make it stay inside the screen? Also, I have this wall.png which will work as the wall. How do I put the wall as the limit of the screen so it doesn't go away from the screen?
code:
import os, sys
import pygame
from pygame.locals import *
from ayuda import *
pygame.init
class PyManMain:
def __init__(self, width=600,height=600):
pygame.init()
self.width = width
self.height = height
self.screen = pygame.display.set_mode((self.width
, self.height))
def MainLoop(self):
self.LoadSprites();
pygame.key.set_repeat(500, 30)
self.background = pygame.Surface(self.screen.get_size())
self.background = self.background.convert()
self.background.fill((50,85,40))
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == KEYDOWN:
if ((event.key == K_RIGHT)
or (event.key == K_LEFT)
or (event.key == K_UP)
or (event.key == K_DOWN)):
self.snake.move(event.key)
lstCols = pygame.sprite.spritecollide(self.snake
, self.pellet_sprites
, True)
self.snake.pellets = self.snake.pellets + len(lstCols)
self.screen.blit(self.background, (0, 0))
self.pellet_sprites.draw(self.screen)
self.snake_sprites.draw(self.screen)
pygame.display.flip()
def LoadSprites(self):
self.snake = Snake()
self.snake_sprites = pygame.sprite.RenderPlain((self.snake))
nNumHorizontal = int(self.width/64)
nNumVertical = int(self.height/64)
self.pellet_sprites = pygame.sprite.Group()
for x in range(nNumHorizontal):
for y in range(nNumVertical):
self.pellet_sprites.add(Pellet(pygame.Rect(x*64, y*64, 64, 64)))
class Snake(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_image('personaje.png',-1)
self.pellets = 0
self.x_dist = 5
self.y_dist = 5
def move(self, key):
xMove = 0;
yMove = 0;
if (key == K_RIGHT):
xMove = self.x_dist
elif (key == K_LEFT):
xMove = -self.x_dist
elif (key == K_UP):
yMove = -self.y_dist
elif (key == K_DOWN):
yMove = self.y_dist
self.rect.move_ip(xMove,yMove);
class Pellet(pygame.sprite.Sprite):
def __init__(self, rect=None):
pygame.sprite.Sprite.__init__(self)
self.image, self.rect = load_image('cofrefront.png',-1)
if rect != None:
self.rect = rect
if __name__ == "__main__":
MainWindow = PyManMain()
MainWindow.MainLoop()
I think I know what your problem is. You would like your character (snake) to stay inside the screen when he reaches the edges of the window. To achieve this, you need to modify the move function of the Snake class :). My modifications would look like this:
def move(self, key):
xMove = 0;
yMove = 0;
if (key == K_RIGHT) and self.rect.right + self.x_dist <= 600 :
xMove = self.x_dist
elif (key == K_LEFT) and self.rect.left - self.x_dist >= 0:
xMove = -self.x_dist
elif (key == K_UP) and self.rect.top - self.y_dist >= 0:
yMove = -self.y_dist
elif (key == K_DOWN) and self.rect.bottom + self.y_dist <= 600:
yMove = self.y_dist
self.rect.move_ip(xMove,yMove);
Essentially what I did above, is before I let the character move left,right,up and down, I check whether he would be outside the visible screen. If after the movement he still is inside the screen, I let him move. If not, I block he's movement :)
Hope that helped,
Cheers!
Alex