For my homework I have to create a program that maps dots to a Tkinter window, and creates a serpenstky triangle out of it. I can create it easily with lines, but I dont understand how I am supposed to get the math to work with dots.
My main question is how would I create a full object with dots using math in python for Tkinter?
from Tkinter import *
from random import randint
# the 2D point class
class Point(object):
def __init__(self,x = 0.0 ,y = 0.0):
self._x = float(x)
self._y = float(y)
#property
def x(self):
return self._x
#x.setter
def x(self):
self._x = x
#property
def y(self):
return self._y
#y.setter
def y(self):
self._y = y
#parts from previous program that I left in here just in case
def __str__(self):
return '(' + str(self.x) + ',' + str(self.y) + ')'
def dist(self,other):
return ((self.x - other.x)**2 + (self.y - other.y)**2)**0.5
def midpt(self,other):
x=float((self.x + other.x)/2)
y=float((self.y + other.y)/2)
return Point(x,y)
# the coordinate system class: (0,0) is in the top-left corner
# inherits from the Canvas class of Tkinter
class chaosGame(Canvas):
def __init__(self, master):
Canvas.__init__(self, master, bg="white")
self.colors = ["black"]
self.radius = 0
self.pack(fill=BOTH, expand=1)
def plotPoints(self, n):
min_x = 10
min_y = 0
k=1
max_x = 600
max_y = 520
mid_x = (min_x + max_x)/2
mid_y = (min_y + max_y)/2
x1 = 3**k-1
y1 = 3**k-1
for i in range(n):
point = Point((x1), (y1))
self.plot(point.x, point.y)
k+= 1
def vertPoints(self, n):
topPoint = Point((300), (0))
leftPoint = Point((0), (510))
rightPoint = Point((590), (510))
self.vplot(topPoint.x, topPoint.y)
self.vplot(leftPoint.x, leftPoint.y)
self.vplot(rightPoint.x, rightPoint.y)
def vplot(self, x, y):
color = self.colors[randint(0, len(self.colors) - 1)]
self.create_oval(x, y, x + 10, y + 10, fill= "red")
def plot(self, x, y):
color = self.colors[randint(0, len(self.colors) - 1)]
self.create_oval(x, y, x + self.radius, y + self.radius, fill=color)
##########################################################
WIDTH = 600
HEIGHT = 520
# the number of points to plot
NUM_POINTS = 50000
# create the window
window = Tk()
window.geometry("{}x{}".format(WIDTH, HEIGHT))
window.title("Triangles")
# create the coordinate system as a Tkinter canvas inside the window
s = chaosGame(window)
# plot some random points
s.plotPoints(NUM_POINTS)
s.vertPoints(3)
# wait for the window to close
window.mainloop()
I am implementing a big circle class,which does operations like computes area,compares two circle,compares a circle and square etc,but i am having trouble with this small snippet.
class Circle(Point):
def __init__(self, x=0, y=0, r=0):
self.X = x
self.Y = y
self.R = r
self.area = math.pi*r*r
def __str__(self):
return ("A Circle which has centre at " + "(" + "%0.6f" % (self.X) + ", "
+ "%0.6f" % (self.Y) + ")" + "and its radius " + "%0.6f" % (self.R))
def getX(self):
return self.X
def getY(self):
return self.Y
def getR(self):
return self.R
def setR(self):
pass
def area(self):
return math.pi * self.R * self.R
def main():
x = float(input("Enter x coordinate of first circle's centre: "))
y = float(input("Enter y coordinate of the first circle's centre: "))
r = float(input("Enter first circle's radius: "))
pointx1 = x
pointy1 = y
radius1 = r
first_circle = Circle(x, y, r)
print(first_circle)
print("\nArea of first circle is %0.6f" % (first_circle, first_circle.area())
main()
However i get the following error on executing the below code:
print("\nArea of first circle is %0.6f" % (first_circle, first_circle.area))
TypeError: float argument required, not instance
How do i get rid of this.I have calculated self.area in constructor as because i am using it later(haven't shown the code here) to compare two circle's areas which are being sent as argument.Please help.
Remove the first argument in your string format:
print("\nArea of first circle is %0.6f" % (first_circle.area()))
I'm not sure why you put first_circle as an argument since %0.6f is the only part of the string requiring an argument.
Also you need to either rename self.area or rename the method area() because it causes conflicts if they have the same name.
I have an issue I need some help with. When colliding I have an issue, the image is off-centered to the side as when it is blitted it doesn't do it from the centre, so when the sprite collides on one side it goes inwards more than it does on the other side when I just want it to be the same for both sides. It is sort of hard to explain in words. the reason this is an issue and I can't just divide the numbers in the blit command by 2 is because I am using a camera system I found here on stack overflow
this is the key bit in the code that im getting stuck with. I have included all the camera stuff as it may be needed to help
camera.update(player)
for e in lay3:
screen.blit(e.image, camera.apply(e))
# update player, draw everything else
player.update(up, down, left, right, running, platforms)
for e in lay2:
screen.blit(e.image, camera.apply(e))
for e in lay:
screen.blit(e.image, camera.apply(e))
for e in entities:
if e not in lay and e not in lay2 and e not in lay3:
screen.blit(e.image, camera.apply(e))
pygame.display.update()
class Camera(object):
def __init__(self, camera_func, width, height):
self.camera_func = camera_func
self.state = Rect(0, 0, width, height)
def apply(self, target):
return target.rect.move(self.state.topleft)
def update(self, target):
self.state = self.camera_func(self.state, target.rect)
def simple_camera(camera, target_rect):
l, t, _, _ = target_rect
_, _, w, h = camera
return Rect(-l+HALF_WIDTH, -t+HALF_HEIGHT, w, h)
def complex_camera(camera, target_rect):
l, t, _, _ = target_rect
_, _, w, h = camera
l, t, _, _ = -l+HALF_WIDTH, -t+HALF_HEIGHT, w, h
l = min(0, l) # stop scrolling at the left edge
l = max(-(camera.width-WIN_WIDTH), l) # stop scrolling at the right edge
t = max(-(camera.height-WIN_HEIGHT), t) # stop scrolling at the bottom
t = min(0, t) # stop scrolling at the top
return Rect(l, t, w, h)
if this is still not enough to solve this is all of the code.
#! /usr/bin/python
import pygame
from pygame import *
WIN_WIDTH = 800
WIN_HEIGHT = 640
HALF_WIDTH = int(WIN_WIDTH / 2)
HALF_HEIGHT = int(WIN_HEIGHT / 2)
idlecount = 0
DISPLAY = (WIN_WIDTH, WIN_HEIGHT)
DEPTH = 32
FLAGS = 0
CAMERA_SLACK = 30
pygame.init()
screen = pygame.display.set_mode(DISPLAY, FLAGS, DEPTH)
SAI = [pygame.image.load("samusIdle0.png").convert_alpha(),pygame.image.load("samusIdle1.png").convert_alpha(),pygame.image.load("samusIdle2.png").convert_alpha(),pygame.image.load("samusIdle3.png").convert_alpha(),pygame.image.load("samusIdle0.png").convert_alpha()]
SAIL = [pygame.image.load("Samus0.png").convert_alpha(),pygame.image.load("Samus1.png").convert_alpha(),pygame.image.load("Samus2.png").convert_alpha(),pygame.image.load("Samus3.png").convert_alpha(),pygame.image.load("Samus0.png").convert_alpha()]
def main():
global cameraX, cameraY
global bg
global entities
timer = pygame.time.Clock()
up = down = left = right = running = False
bg = Surface((32,32))
bg.convert()
bg.fill(Color("#000000"))
entities = pygame.sprite.Group()
player = Player(32, 32)
platforms = []
x = y = 0
level = [
"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxij",
"x ij",
"xg ij",
"x ij",
"x ij",
"x ij",
"x ij",
"x ij",
"x ij",
"x ij",
"x ij",
"x ij",
"x ij",
"x ij",
"x ij",
"x ij",
"xf ij",
"x ij",
"x Hh",
"x ",
"x ",
"x ",
"PPPPPPPPPPPPPPPPPPPPPV ",
"KMKMKMKMKMKMKMKMKMKMKQ APPPPPPPPPPPPPPPPP",
"MKMKMKMKMKMKMKMKMKMKMSPPPPPPPPPPPPPPPPPPPPPPZMKMKMKMKMKMKMKMKM",]
# build the level
global tile
for row in level:
for col in row:
if col == "P":
tile = 1
p = Platform(x, y)
platforms.append(p)
entities.add(p)
if col == "A":
tile = 13
q = Platform(x, y)
platforms.append(q)
entities.add(q)
if col == "Z":
tile = 14
q = Platform(x, y)
platforms.append(q)
entities.add(q)
if col == "Q":
tile = 2
q = Platform(x, y)
platforms.append(q)
entities.add(q)
if col == "V":
tile = 3
q = Platform(x, y)
platforms.append(q)
entities.add(q)
if col == "S":
tile = 4
q = Platform(x, y)
platforms.append(q)
entities.add(q)
if col == "K":
tile = 5
q = Platform(x, y)
platforms.append(q)
entities.add(q)
if col == "M":
tile = 6
q = Platform(x, y)
platforms.append(q)
entities.add(q)
if col == "h":
tile = 7
q = Platform(x, y)
platforms.append(q)
entities.add(q)
if col == "H":
tile = 8
q = Platform(x, y)
platforms.append(q)
entities.add(q)
if col == "i":
tile = 9
q = Platform(x, y)
platforms.append(q)
entities.add(q)
if col == "j":
tile = 10
q = Platform(x, y)
platforms.append(q)
entities.add(q)
if col == "x":
tile = 11
q = Platform(x, y)
platforms.append(q)
entities.add(q)
if col == "f":
tile = 12
q = Platform(x, y)
entities.add(q)
if col == "g":
tile = 0
q = Platform(x, y)
entities.add(q)
eee = q
print (entities)
if col == "E":
e = ExitBlock(x, y)
platforms.append(e)
entities.add(e)
x += 32
y += 32
x = 0
total_level_width = len(level[0])*32
total_level_height = len(level)*32
camera = Camera(complex_camera, total_level_width, total_level_height)
entities.add(player)
global idlecount
global direction
direction = 'right'
while 1:
timer.tick(60)
idlecount = idlecount + 0.05
if direction == 'right':
player.image = SAIL[int(idlecount)]
if direction == 'left':
player.image = SAI[int(idlecount)]
if idlecount > 4:
idlecount = 0
for e in pygame.event.get():
if e.type == QUIT: raise SystemExit, "QUIT"
if e.type == KEYDOWN and e.key == K_ESCAPE:
raise SystemExit, "ESCAPE"
if e.type == KEYDOWN and e.key == K_UP:
up = True
down = False
if e.type == KEYDOWN and e.key == K_DOWN:
downk = True
if e.type == KEYDOWN and e.key == K_LEFT:
direction = 'left'
left = True
if e.type == KEYDOWN and e.key == K_RIGHT:
right = True
direction = 'right'
if e.type == KEYDOWN and e.key == K_SPACE:
running = True
if e.type == KEYUP and e.key == K_UP:
up = False
down = True
if e.type == KEYUP and e.key == K_DOWN:
downk = False
if e.type == KEYUP and e.key == K_RIGHT:
right = False
if e.type == KEYUP and e.key == K_LEFT:
left = False
# draw background
for y in range(32):
for x in range(32):
screen.blit(bg, (x * 32, y * 32))
camera.update(player)
for e in lay3:
screen.blit(e.image, camera.apply(e))
# update player, draw everything else
player.update(up, down, left, right, running, platforms)
for e in lay2:
screen.blit(e.image, camera.apply(e))
for e in lay:
screen.blit(e.image, camera.apply(e))
for e in entities:
if e not in lay and e not in lay2 and e not in lay3:
screen.blit(e.image, camera.apply(e))
pygame.display.update()
class Camera(object):
def __init__(self, camera_func, width, height):
self.camera_func = camera_func
self.state = Rect(0, 0, width, height)
def apply(self, target):
return target.rect.move(self.state.topleft)
def update(self, target):
self.state = self.camera_func(self.state, target.rect)
def simple_camera(camera, target_rect):
l, t, _, _ = target_rect
_, _, w, h = camera
return Rect(-l+HALF_WIDTH, -t+HALF_HEIGHT, w, h)
def complex_camera(camera, target_rect):
l, t, _, _ = target_rect
_, _, w, h = camera
l, t, _, _ = -l+HALF_WIDTH, -t+HALF_HEIGHT, w, h
l = min(0, l) # stop scrolling at the left edge
l = max(-(camera.width-WIN_WIDTH), l) # stop scrolling at the right edge
t = max(-(camera.height-WIN_HEIGHT), t) # stop scrolling at the bottom
t = min(0, t) # stop scrolling at the top
return Rect(l, t, w, h)
class Entity(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
class Player(Entity):
def __init__(self, x, y):
global lay
global lay2
global lay3
global idlecount
Entity.__init__(self)
self.xvel = 0
self.yvel = 0
self.onGround = False
self.image = Surface((32,72))
self.image = SAIL[int(idlecount)]
lay = pygame.sprite.LayeredUpdates()
lay.add(self)
lay2 = pygame.sprite.LayeredUpdates()
lay3 = pygame.sprite.LayeredUpdates()
self.image.convert()
self.rect = Rect(x, y, 32, 72)
def update(self, up, down, left, right, running, platforms):
if up:
# only jump if on the ground
if self.onGround: self.yvel -= 14
if down:
self.yvel += 0.5
if running:
self.xvel = 12
if left:
self.xvel = -8
if right:
self.xvel = 8
if not self.onGround:
# only accelerate with gravity if in the air
down = False
self.yvel += 0.5
# max falling speed
if self.yvel > 100: self.yvel = 100
if not(left or right):
self.xvel = 0
# increment in x direction
self.rect.left += self.xvel
# do x-axis collisions
self.collide(self.xvel, 0, platforms)
# increment in y direction
self.rect.top += self.yvel
# assuming we're in the air
self.onGround = False;
# do y-axis collisions
self.collide(0, self.yvel, platforms)
def collide(self, xvel, yvel, platforms):
for p in platforms:
if pygame.sprite.collide_rect(self, p):
if isinstance(p, ExitBlock):
pygame.event.post(pygame.event.Event(QUIT))
if xvel > 0:
self.rect.right = p.rect.left
print "collide right"
if xvel < 0:
self.rect.left = p.rect.right
print "collide left"
if yvel > 0:
self.rect.bottom = p.rect.top
self.onGround = True
self.yvel = 0
if yvel < 0:
self.rect.top = p.rect.bottom
down = True
for q in platforms:
if pygame.sprite.collide_rect(self, p):
if isinstance(p, ExitBlock):
pygame.event.post(pygame.event.Event(QUIT))
if xvel > 0:
self.rect.right = p.rect.left
print "collide right"
if xvel < 0:
self.rect.left = p.rect.right
print "collide left"
if yvel > 0:
self.rect.bottom = p.rect.top
self.onGround = True
self.yvel = 0
if yvel < 0:
self.rect.top = p.rect.bottom
class Platform(Entity):
global tile
def __init__(self, x, y):
Entity.__init__(self)
self.image = Surface((32, 32))
self.image.convert()
if tile == 1:
self.image = pygame.image.load('tile8.png').convert()
elif tile == 2:
self.image = pygame.image.load('tile7.png').convert()
elif tile == 3:
self.image = pygame.image.load('tile5.png').convert()
elif tile == 4:
self.image = pygame.image.load('tile6.png').convert()
elif tile == 5:
self.image = pygame.image.load('tileA1.png').convert()
elif tile == 6:
self.image = pygame.image.load('tileA2.png').convert()
elif tile == 7:
self.image = pygame.image.load('tile10.png').convert()
elif tile == 8:
self.image = pygame.image.load('tile9.png').convert()
elif tile == 9:
self.image = pygame.image.load('tile11.png').convert()
elif tile == 10:
self.image = pygame.image.load('tile12.png').convert()
elif tile == 11:
self.image = pygame.image.load('tile00.png').convert_alpha()
elif tile == 0:
self.image = pygame.image.load('sky.png').convert_alpha()
lay3.add(self)
elif tile == 12:
self.image = pygame.image.load('samusShip.png').convert_alpha()
lay2.add(self)
elif tile == 13:
self.image = pygame.image.load('tile13.png').convert()
elif tile == 14:
self.image = pygame.image.load('tile14.png').convert()
self.rect = Rect(x, y, 32, 32)
def update(self):
pass
class ExitBlock(Platform):
def __init__(self, x, y):
Platform.__init__(self, x, y)
self.image.fill(Color("#0033FF"))
if __name__ == "__main__":
main()
Thank you for your time,
EDIT:
I should probably mention that the sprites for the player are 52x72 pixels, this creates overhang when touching a wall and I need the overhang to be the same on both sides
You can give the Player class a draw method in which you add an arbitrary offset to the coordinates.
def draw(self, screen, rect):
x, y = rect.topleft
screen.blit(self.image, (x-10, y)) # -10 because the rect is 20 px smaller than the image.
In the main function before pygame.display.update() add the line:
player.draw(screen, camera.apply(player))
Edit: You need to remove the for e in lay: loop which blits the player sprite, otherwise it gets blitted twice.
When Running the below code, I receive an AssertionError in the Main Function, assert len(args) > 1. Any idea where in the code the issue occurs?
K-Means clustering implementation
import numpy as np
from math import sqrt
import csv
import sys
====
Define a function that computes the distance between two data points
GAP = 2
MIN_VAL = 1000000
def get_distance(point1, point2):
dis = sqrt(pow(point1[0] - point2[0],2) + pow(point1[1] - point2[1],2))
return dis
====
Define a function that reads data in from the csv
def csvreader(data_file):
sampleData = []
global Countries
with open(data_file, 'r') as csvfile:
read_data = csv.reader(csvfile, delimiter=' ', quotechar='|')
for row in read_data:
print ', '.join(row)
if read_data <> None:
for f in read_data:
values = f.split(",")
if values[0] <> 'Countries':
sampleData.append([values[1],values[2]])
return sampleData
====
Write the initialisation procedure
def cluster_dis(centroid, cluster):
dis = 0.0
for point in cluster:
dis += get_distance(centroid, point)
return dis
def update_centroids(centroids, cluster_id, cluster):
x, y = 0.0, 0.0
length = len(cluster)
if length == 0:
return
for item in cluster:
x += item[0]
y += item[1]
centroids[cluster_id] = (x / length, y / length)
====
Implement the k-means algorithm, using appropriate looping
def kmeans(data, k):
assert k <= len(data)
seed_ids = np.random.randint(0, len(data), k)
centroids = [data[idx] for idx in seed_ids]
clusters = [[] for _ in xrange(k)]
cluster_idx = [-1] * len(data)
pre_dis = 0
while True:
for point_id, point in enumerate(data):
min_distance, tmp_id = MIN_VAL, -1
for seed_id, seed in enumerate(centroids):
distance = get_distance(seed, point)
if distance < min_distance:
min_distance = distance
tmp_id = seed_id
if cluster_idx[point_id] != -1:
dex = clusters[cluster_idx[point_id]].index(point)
del clusters[cluster_idx[point_id]][dex]
clusters[tmp_id].append(point)
cluster_idx[point_id] = tmp_id
now_dis = 0.0
for cluster_id, cluster in enumerate(clusters):
now_dis += cluster_dis(centroids[cluster_id], cluster)
update_centroids(centroids, cluster_id, cluster)
delta_dis = now_dis - pre_dis
pre_dis = now_dis
if delta_dis < GAP:
break
print(centroids)
print(clusters)
return centroids, clusters
def main():
args = sys.argv[1:]
assert len(args) > 1
data_file, k = args[0], int(args[1])
data = csvreader(data_file)
kmeans(data, k)
if __name__ == '__main__':
main()
I need to make the balls in this code move around randomly. I am not sure what I am doing wrong. I am new to programming and this may be badly coded so any help would be appreciated. Right now the code makes a character in the middle of the screen that you can move up or down and it makes one ball in the top left corner of the screen that does not move. I want multiple balls on the screen and eventually I want the balls to be moving around randomly and if they collide with the character you lose this simple game.
from pygame import *
import random
class Ball(sprite.Sprite):
def __init__(self, numballs, balls = []):
sprite.Sprite.__init__(self)
self.image = image.load('ball.png')
self.rect = self.image.get_rect()
self.numballs = numballs
self.balls = balls
def multipleBalls(self):
for count in range(self.numballs):
self.balls.append(dict)
self.balls[count] = {'x': 0, 'y': 0, 'xmove': random.randint(1,2), 'ymove':random.randint(1,2)}
def ballMove(self):
for count in range(self.numballs):
self.balls[count]['x'] = self.balls[count]['x'] + self.balls[count]['xmove']
self.balls[count]['y'] = self.balls[count]['y'] + self.balls[count]['ymove']
def ballsOnScreen(self):
for count in range(self.numballs):
self.screen.blit(self.image, (self.balls[count]['x'], self.balls[count]['y']))
def ballBarrier(self):
for count in range(self.numballs):
if self.balls[count]['x'] > 620:
self.balls[count]['xmove'] = random.randint(-2, 0)
if self.balls[count]['x'] < -10:
self.balls[count]['xmove'] = random.randint(0, 2)
if self.balls[count]['y'] > 470:
self.balls[count]['ymove'] = random.randint(-2, 0)
if self.balls[count]['y'] < -10:
self.balls[count]['ymove'] = random.randint(0, 2)
def manageBall(self):
self.multipleBalls()
self.ballsOnScreen()
self.ballMove()
self.ballBarrier()
class Character(sprite.Sprite):
def __init__(self, xy):
sprite.Sprite.__init__(self)
self.image = image.load('character.png')
self.rect = self.image.get_rect()
self.rect.centerx, self.rect.centery = xy
self.movementspeed = 1
self.velocity = 0
def down(self):
self.velocity += self.movementspeed
def up(self):
self.velocity -= self.movementspeed
def characterMove(self, dy):
if self.rect.bottom + dy > 480:
self.rect.bottom = 480
elif self.rect.top + dy < 0:
self.rect.top = 0
else:
self.rect.y += dy
def update(self):
self.characterMove(self.velocity)
class Game(object):
def __init__(self):
init()
key.set_repeat(1, 30)
self.screen = display.set_mode((640, 480))
self.clock = time.Clock()
display.set_caption('Game')
event.set_allowed([QUIT, KEYDOWN, KEYUP])
self.background = Surface((640, 480))
self.background.fill((0,0,0))
self.screen.blit(self.background, (0,0))
display.flip()
self.sprites = sprite.RenderUpdates()
self.character = Character((320, 240))
self.sprites.add(self.character)
self.ball = Ball(5)
self.sprites.add(self.ball)
def run(self):
running = True
while running == True:
self.clock.tick(60)
running = self.handleEvents()
display.set_caption('game %d fps' % self.clock.get_fps())
for sprite in self.sprites:
sprite.update()
self.sprites.clear(self.screen, self.background)
dirty = self.sprites.draw(self.screen)
display.update(dirty)
self.ball.manageBall()
def handleEvents(self):
for e in event.get():
if e.type == QUIT:
return False
elif e.type == KEYDOWN:
if e.key == K_ESCAPE:
return False
if e.key == K_UP:
self.character.up()
if e.key == K_DOWN:
self.character.down()
return True
def main():
game = Game()
game.run()
main()
I've never used the Sprite class before so this was a good exercise. :)
I fixed your code, just change the image paths back to your icon locations and you should be good to go. The print statements might need reformatting if you're running an older version of Python.
I take out the forced call to the Sprite init method in the Ball and Character classes, it won't let me add them to the game.sprites render group. Not sure why.
I'm running Python 3.2.2 and Pygame 1.9.2pre so YMMV. :)
Controls:
UP / DOWN = Move your dude.
R = add a new, random ball.
from pygame import *
import random
SCREEN_WIDTH = 640
SCREEN_HEIGHT = 480
FPS = 60
class Ball(sprite.Sprite):
def __init__(self, xy = (0,0), xm = 0, ym = 0):
sprite.Sprite.__init__(self)
self.img_load('evil_balloon_32x32.png')
self.rect.centerx, self.rect.centery = xy
self.xmove = xm
self.ymove = ym
def update(self):
self.move()
self.ballBarrier()
def move(self):
self.rect.x += self.xmove
self.rect.y += self.ymove
def img_load(self, filename):
self.image = image.load(filename)
self.rect = self.image.get_rect()
def ballBarrier(self):
"""
Checks to make sure ball is within bounds, adjusts movement speed if it's not
"""
if self.rect.right > SCREEN_WIDTH:
self.xmove = random.randint(-2, 0)
if self.rect.left < 0:
self.xmove = random.randint(0, 2)
if self.rect.bottom > SCREEN_HEIGHT:
self.ymove = random.randint(-2, 0)
if self.rect.top < 0:
self.ymove = random.randint(0, 2)
class ball_manager():
def __init__(self, numballs = 5, balls = []):
self.blist = balls
if numballs > 0:
self.multipleBalls(numballs) # moved this here so balls get init'd only once
def update(self):
"""
Update position of all balls
"""
for ball in self.blist:
self.ballMove(ball)
def add_ball(self, xy = (0,0), xm = 0, ym = 0):
self.blist.append(Ball(xy, xm, ym)) # appends a random ball
def multipleBalls(self, numballs):
for i in range(numballs):
self.add_ball((random.randint(0, SCREEN_WIDTH),
random.randint(0, SCREEN_HEIGHT)),
random.randint(-2,2),
random.randint(-2,2))
class Character(sprite.Sprite):
def __init__(self, xy):
sprite.Sprite.__init__(self)
self.img_load()
self.rect.centerx, self.rect.centery = xy
self.movementspeed = 1
self.velocity = 0
def down(self):
self.velocity += self.movementspeed
def up(self):
self.velocity -= self.movementspeed
def characterMove(self, dy):
if self.rect.bottom + dy > SCREEN_HEIGHT:
self.rect.bottom = SCREEN_HEIGHT
self.velocity = 0
elif self.rect.top + dy < 0:
self.rect.top = 0
self.velocity = 0
else:
self.rect.y += dy
def update(self):
self.characterMove(self.velocity)
def img_load(self):
self.image = image.load("scary_clown_32x32.png")
self.rect = self.image.get_rect()
class Game(object):
def __init__(self):
init()
key.set_repeat(1, 30)
self.screen = display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
self.clock = time.Clock()
display.set_caption('Game')
event.set_allowed([QUIT, KEYDOWN, KEYUP])
self.background = Surface((SCREEN_WIDTH, SCREEN_HEIGHT))
self.background.fill((0,0,0))
self.screen.blit(self.background, (0,0))
display.flip()
self.sprites = sprite.RenderUpdates()
self.character = Character((SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2))
self.sprites.add(self.character)
self.balls = ball_manager(5)
for ball in self.balls.blist:
self.sprites.add(ball)
def run(self):
running = True
while running == True:
self.clock.tick(FPS)
running = self.handleEvents()
display.set_caption('game %d fps' % self.clock.get_fps())
self.sprites.clear(self.screen, self.background)
for sprite in self.sprites:
sprite.update()
dirty = self.sprites.draw(self.screen)
display.update(dirty)
def handleEvents(self):
for e in event.get():
if e.type == QUIT:
return False
elif e.type == KEYDOWN:
if e.key == K_ESCAPE:
return False
if e.key == K_UP:
self.character.up()
if e.key == K_DOWN:
self.character.down()
if e.key == K_r:
self.sprites.add(Ball((random.randint(0, SCREEN_WIDTH),
random.randint(0, SCREEN_HEIGHT)),
random.randint(-2,2),
random.randint(-2,2)))
return True
def main():
game = Game()
game.run()
quit()
main()
sys.exit()