How to draw rectangle and circles in Pygame environment - python

I am trying to create a pygame environment with various shapes of sprites but my code seems not working. Here is what I have:
class Object(pygame.sprite.Sprite):
def __init__(self, position, color, size, type):
# create square sprite
pygame.sprite.Sprite.__init__(self)
if type == 'agent':
self.image = pygame.Surface((size, size))
self.image.fill(color)
self.rect = self.image.get_rect()
else:
red = (200,0,0)
self.image = pygame.display.set_mode((size, size))
self.image.fill(color)
self.rect = pygame.draw.circle(self.image, color,(), 20)
# initial conditions
self.start_x = position[0]
self.start_y = position[1]
self.state = np.asarray([self.start_x, self.start_y])
self.rect.x = int((self.start_x * 500) + 100 - self.rect.size[0] / 2)
self.rect.y = int((self.start_y * 500) + 100 - self.rect.size[1] / 2)
Does anyone notice any issues with the Object class?

You have to create a pygame.Surface, instead of creating a new window (pygame.display.set_mode).
The pixel format of the Surface must include a per-pixel alpha (SRCALPHA). The center point of the circle must be the center of the Surface. The radius
must be half the size of the Surface:
self.image = pygame.Surface((size, size), pygame.SRCALPHA)
radius = size // 2
pygame.draw.circle(self.image, color, (radius, radius), radius)
Class Object:
class Object(pygame.sprite.Sprite):
def __init__(self, position, color, size, type):
# create square sprite
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((size, size), pygame.SRCALPHA)
self.rect = self.image.get_rect()
if type == 'agent':
self.image.fill(color)
else:
radius = size // 2
pygame.draw.circle(self.image, color, (radius, radius), radius)
# initial conditions
self.start_x = position[0]
self.start_y = position[1]
self.state = np.asarray([self.start_x, self.start_y])
self.rect.x = int((self.start_x * 500) + 100 - self.rect.size[0] / 2)
self.rect.y = int((self.start_y * 500) + 100 - self.rect.size[1] / 2)

Related

How can i get the first element from a sprite group in pygame

I create the sprite group land. For that, i use the class Landschaft and the while loop
How can i get from first sprite in the sprite group land rect.x , rect.y rect.w and rect.h ?
class Landschaft(pygame.sprite.Sprite):
def __init__(self,image):
pygame.sprite.Sprite.__init__(self)
self.image = image
#self.mask = pygame.mask.from_surface(self.image )
self.rect = self.image.get_rect()
#pygame.draw.ellipse(self.image, red, [self.rect.x,self.rect.y,self.rect.width,self.rect.height],3)
x=random.randrange(0, breite -60)
y=random.randrange(200, hoehe - 200)
self.rect.center = (x,y)
land = pygame.sprite.Group()
while len(land) < anzahl_gegenstaende:
ii = len(land)
img = pygame.image.load(f"Bilder/Gegenstaende/geg{ii}.png")
if ii == 0:
img = pygame.transform.scale(img,(breite))
else:
zb,zh = img.get_rect().size
scale_hoehe =100
scale_breite = int(100 * zb / zh)
#img = img.convert_alpha()
img = pygame.transform.scale(img,(scale_breite,scale_hoehe))
m = Landschaft(img)
if not pygame.sprite.spritecollide(m, land, False):
land.add(m)
A list of sprites from a pygame.sprite.Group can be obtained with the sprites() method:. Therefore the first sprite in the Group is:
first_sprite = group.sprites()[0]
Problem?
Your land = pygame.sprite.Group() prevents you from getting the first element from a sprite group in pygame. This is a fairly common problem. To get it you have to use sprites() as you did, but in a different way. You approached the solution with your code. You came close.
You have to write, as a solution to your problem, group.sprites() (with [0]) (not pygame.sprite.Group ()) to get from first sprite in the sprite group land rect.x, rect.y rect.w and rect.h
Solution?
The solution to your problem is:
class Landschaft(pygame.sprite.Sprite):
def __init__(self,image):
pygame.sprite.Sprite.__init__(self)
self.image = image
#self.mask = pygame.mask.from_surface(self.image )
self.rect = self.image.get_rect()
#pygame.draw.ellipse(self.image, red, [self.rect.x,self.rect.y,self.rect.width,self.rect.height],3)
x=random.randrange(0, breite -60)
y=random.randrange(200, hoehe - 200)
self.rect.center = (x,y)
land = group.sprites()[0]
while len(land) < anzahl_gegenstaende:
ii = len(land)
img = pygame.image.load(f"Bilder/Gegenstaende/geg{ii}.png")
if ii == 0:
img = pygame.transform.scale(img,(breite))
else:
zb,zh = img.get_rect().size
scale_hoehe =100
scale_breite = int(100 * zb / zh)
#img = img.convert_alpha()
img = pygame.transform.scale(img,(scale_breite,scale_hoehe))
m = Landschaft(img)
if not pygame.sprite.spritecollide(m, land, False):
land.add(m)

Change color of Pygame Surface

I've made a Rectangle class:
class Rectangle(pygame.sprite.Sprite):
def __init__(self, len, x, y, color):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((len, len), flags=pygame.SRCALPHA)
# self.image.set_colorkey(Constants.WHITE)
self.image.fill(color)
self.rect = self.image.get_rect()
self.rect.center = (x + len / 2, y + len / 2)
self.is_blocked = False
self.x_pos = x
self.y_pos = y
self.x = math.floor((x - Constants.PADTOPBOTTOM) / Constants.CELL_SIZE)
self.y = math.floor((y - Constants.PADLEFTRIGHT) / Constants.CELL_SIZE)
def update(self):
if self.is_blocked:
print("is update working?") # it is working.
self.image.fill(Constants.GREEN)
And when update() is called I want to change the color of the rectangle to green but it doesn't work.
I'm new to pygame and I don't know what to do.
Your problem is that you keep creating new sprites every frame, so when you change the color of one Rectangle to green, it will be covered by a white one.
You do this by calling the fill function (which creates new Rectangle instances) inside the drawGrid function.

Pygame Gun Rotating Up sight Down On The Left Side Problem

so I have this gun here where it rotates towards my mouse x, and mouse y position but the problem (VIDEO) is the gun turns upside down. Is there a way I could make the image of my gun not upside down and do the same movement as my gun facing the right side? Like the gun for the left side is upside down for some reason and I don't have an idea on how to do this at all
Gun Image:
my gun draw(self)
def draw(self,drawX,drawY):
self.rect.topleft = (drawX,drawY)
# the gun's hitbox
# rotating the gun
dx = self.look_at_pos[0] - self.rect.centerx
dy = self.look_at_pos[1] - self.rect.centery
angle = (180/math.pi) * math.atan2(-dy, dx)
gun_size = self.image.get_size()
pivot = (8, gun_size[1]//2)
blitRotate(window, self.image, self.rect.center, pivot, angle)
def lookAt( self, coordinate ):
self.look_at_pos = coordinate
my full gun class
class handgun():
def __init__(self,x,y,height,width,color):
self.x = x
self.y = y
self.height = height
self.width = width
self.color = color
self.rect = pygame.Rect(x,y,height,width)
# LOL THESE IS THE HAND
self.shootsright = pygame.image.load("hands.png")
self.image = self.shootsright
self.rect = self.image.get_rect(center = (self.x, self.y))
self.look_at_pos = (self.x, self.y)
self.isLookingAtPlayer = False
self.look_at_pos = (x,y)
self.hitbox = (self.x + -18, self.y, 46,60)
def draw(self,drawX,drawY):
self.rect.topleft = (drawX,drawY)
# the gun's hitbox
# rotating the gun
dx = self.look_at_pos[0] - self.rect.centerx
dy = self.look_at_pos[1] - self.rect.centery
angle = (180/math.pi) * math.atan2(-dy, dx)
gun_size = self.image.get_size()
pivot = (8, gun_size[1]//2)
blitRotate(window, self.image, self.rect.center, pivot, angle)
def lookAt( self, coordinate ):
self.look_at_pos = coordinate
this is where the rotation happens like how my gun will rotate:
def blitRotate(surf, image, pos, originPos, angle):
# calcaulate the axis aligned bounding box of the rotated image
w, h = image.get_size()
sin_a, cos_a = math.sin(math.radians(angle)), math.cos(math.radians(angle))
min_x, min_y = min([0, sin_a*h, cos_a*w, sin_a*h + cos_a*w]), max([0, sin_a*w, -cos_a*h, sin_a*w - cos_a*h])
# calculate the translation of the pivot
pivot = pygame.math.Vector2(originPos[0], -originPos[1])
pivot_rotate = pivot.rotate(angle)
pivot_move = pivot_rotate - pivot
# calculate the upper left origin of the rotated image
origin = (pos[0] - originPos[0] + min_x - pivot_move[0], pos[1] - originPos[1] - min_y + pivot_move[1])
# get a rotated image
rotated_image = pygame.transform.rotate(image, angle)
# rotate and blit the image
surf.blit(rotated_image, origin)
my full code: script
andy help is appreciated thank you!
You need to mirror the gun image once it turns past 90 degrees anti-clockwise from the positive x-axis.
You can do this using pygame.transform.flip() which takes in three parameters:
The surface objects (In this case, your gun image)
Whether the image should be flipped horizontally (No)
Whether the image should be flipped vertically (Yes)
So you'll want to have a variable which indicates where the gun is facing:
gunDirection = "right"
And also code which will flip the image whenever the gun changes direction:
if(angle > 90 and gunDirection != "left"):
gunDirection = "left"
self.image = pygame.transform.flip(self.image, False, True)
if(angle < 90 and gunDirection != "right"):
gunDirection = "right"
self.image = pygame.transform.flip(self.image, False, True)
This should all be in the gun class, if you're using radians the angle would be 0.5pi

Sprite Is Not Rotating Towards The Player Properly How Do I Fix This? [duplicate]

This question already has answers here:
How do I rotate an image around its center using Pygame?
(6 answers)
How do I make my player rotate towards mouse position?
(1 answer)
Closed 2 years ago.
I am trying to make my sprites rotate towards the player, but the rotation is out of place. Here is a video of the behaviour.
I am not sure how to fix this,
Sprite class
#-------------------------------- enemy shoots left and right
shotsright = pygame.image.load("canss.png")
class enemyshoot:
def __init__(self,x,y,height,width,color):
self.x = x
self.y =y
self.height = height
self.width = width
self.color = color
self.rect = pygame.Rect(x,y,height,width)
self.health = 10
self.hitbox = (self.x + -20, self.y + 30, 31, 57)
#-------------------------------------------------------
# Make a Reference Copy of the bitmap for later rotation
self.shootsright = pygame.image.load("canss.png")
self.shootsright = pygame.transform.scale(self.shootsright,(self.shootsright.get_width()-150,self.shootsright.get_height()-150))
self.image = self.shootsright
self.rect = self.image.get_rect()
self.position = pygame.math.Vector2( (200, 180) )
self.isLookingAtPlayer = False
def draw(self):
self.rect.topleft = (self.x,self.y)
window.blit(self.image, self.rect)
self.hits = (self.x + 20, self.y, 28,60)
pygame.draw.rect(window, (255,0,0), (self.hitbox[0], self.hitbox[1] - 60, 100, 10)) # NEW
pygame.draw.rect(window, (0,255,0), (self.hitbox[0], self.hitbox[1] - 60, 100 - (5 * (10 - self.health)), 10))
self.hitbox = (self.x + 200, self.y + 200, 51, 65)
def lookAt( self, coordinate ):
# Rotate image to point in the new direction
delta_vector = coordinate - self.position
radius, angle = delta_vector.as_polar()
self.image = pygame.transform.rotate(self.shootsright, -angle)
# Re-set the bounding rectangle and position since
# the dimensions and centroid will have (probably) changed.
current_pos = self.rect.center
self.rect = self.image.get_rect()
self.rect.center = current_pos
black = (0,0,0)
enemyshooting = []
platformGroup = pygame.sprite.Group
platformList = []
level = [" p p p p p ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",
" ",]
for iy, row in enumerate(level):
for ix, col in enumerate(row):
if col == "p":
new_platforms = enemyshoot(ix*10, iy*50, 10,10,(255,255,255))
enemyshooting.append(new_platforms)
this is the rotating part
class enemyshoot:
def __init__(self,x,y,height,width,color):
# [................]
#-------------------------------------------------------
# Make a Reference Copy of the bitmap for later rotation
self.shootsright = pygame.image.load("canss.png")
self.shootsright = pygame.transform.scale(self.shootsright,(self.shootsright.get_width()-150,self.shootsright.get_height()-150))
self.image = self.shootsright
self.rect = self.image.get_rect()
self.position = pygame.math.Vector2( (200, 180) )
def lookAt( self, coordinate ):
# Rotate image to point in the new direction
delta_vector = coordinate - pygame.math.Vector2(self.rect.center)
radius, angle = delta_vector.as_polar()
self.image = pygame.transform.rotate(self.shootsright, -angle)
# Re-set the bounding rectangle and position since
# the dimensions and centroid will have (probably) changed.
current_pos = self.rect.center
self.rect = self.image.get_rect()
self.rect.center = current_pos
This is where I call the LookAt function to face the player:
# so instead of this
for enemyshoot in enemyshooting:
if not enemyshoot.isLookingAtPlayer:
enemyshoot.lookAt((playerman.x, playerman.y))
The rotation is out of place, and I can't figure out how to fix it. I am trying to make the mouth of the cannon rotate towards the player because that's where the bullets will append from.
I concur with everything #Rabbid76 says in the above answer.
I suspect part of your problem may be that the "human readable" part of the bitmap is not centered around the bitmap's centroid. Thus when rotated, it "sweeps" through an arc, rather than being rotated "around itself". (The preserving of the centre co-ordinate is an important step here to maintain a smooth rotation about the centroid of the object).
Consider the two bitmaps (the image on the right has a large 3/4 transparent section top-left):
Both are rotated around their centroid, but since the visible part on the 2nd image is not centred, it rotates weirdly.
So ensure your actual bitmap is centred within itself.
Reference Code:
import pygame
import random
# Window size
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 400
WINDOW_SURFACE = pygame.HWSURFACE|pygame.DOUBLEBUF|pygame.RESIZABLE
DARK_BLUE = ( 3, 5, 54 )
class RotationSprite( pygame.sprite.Sprite ):
def __init__( self, image, x, y, ):
pygame.sprite.Sprite.__init__(self)
self.original = image
self.image = image
self.rect = self.image.get_rect()
self.rect.center = ( x, y )
# for maintaining trajectory
self.position = pygame.math.Vector2( ( x, y ) )
self.velocity = pygame.math.Vector2( ( 0, 0 ) )
def lookAt( self, co_ordinate ):
# Rotate image to point in the new direction
delta_vector = co_ordinate - self.position
radius, angle = delta_vector.as_polar()
self.image = pygame.transform.rotozoom( self.original, -angle, 1 )
# Re-set the bounding rectagle
current_pos = self.rect.center
self.rect = self.image.get_rect()
self.rect.center = current_pos
### initialisation
pygame.init()
pygame.mixer.init()
window = pygame.display.set_mode( ( WINDOW_WIDTH, WINDOW_HEIGHT ), WINDOW_SURFACE )
pygame.display.set_caption( "Rotation Example" )
### Missiles!
rotation_sprites = pygame.sprite.Group()
rotation_image1 = pygame.image.load( 'rot_offcentre_1.png' )
rotation_image2 = pygame.image.load( 'rot_offcentre_2.png' )
rotation_sprites.add( RotationSprite( rotation_image1, WINDOW_WIDTH//3, WINDOW_HEIGHT//2 ) )
rotation_sprites.add( RotationSprite( rotation_image2, 2*( WINDOW_WIDTH//3 ), WINDOW_HEIGHT//2 ) )
### Main Loop
clock = pygame.time.Clock()
done = False
while not done:
# Handle user-input
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
done = True
elif ( event.type == pygame.MOUSEBUTTONUP ):
# On mouse-click
pass
# Record mouse movements for positioning the paddle
mouse_pos = pygame.mouse.get_pos()
for m in rotation_sprites:
m.lookAt( mouse_pos )
rotation_sprites.update()
# Update the window, but not more than 60 FPS
window.fill( DARK_BLUE )
rotation_sprites.draw( window )
pygame.display.flip()
# Clamp FPS
clock.tick_busy_loop(60)
pygame.quit()
self.position is set in the constructor, but it is not updated. Use the self.rect.center to compute the direction vector:
delta_vector = coordinate - pygame.math.Vector2(self.rect.center)
Use math.atan2 to compute the angle of rotation:
(See How do I make my player rotate towards mouse position?)
angle = (180 / math.pi) * math.atan2(-delta_vector.x, -delta_vector.y)
Setting the rectangle position in draw struggles with rotating the sprite in lookAt. Note the size of the rotated rectangle is enlarged. See How do I rotate an image around its center using Pygame?.
I recommend to set the look-at position in lookAt and to compute the rotated image in draw:
class enemyshoot:
def __init__(self,x,y,height,width,color):
# [...]
self.look_at_pos = (x, y)
def draw(self):
self.rect = self.shootsright.get_rect(topleft = (self.x, self.y))
dx = self.look_at_pos[0] - self.rect.centerx
dy = self.look_at_pos[1] - self.rect.centery
angle = (180 / math.pi) * math.atan2(-dx, -dy)
self.image = pygame.transform.rotate(self.shootsright, angle)
self.rect = self.image.get_rect(center = self.rect.center)
window.blit(self.image, self.rect)
self.hits = (self.x + 20, self.y, 28,60)
pygame.draw.rect(window, (255,0,0), (self.hitbox[0], self.hitbox[1] - 60, 100, 10)) # NEW
pygame.draw.rect(window, (0,255,0), (self.hitbox[0], self.hitbox[1] - 60, 100 - (5 * (10 - self.health)), 10))
self.hitbox = (self.x + 200, self.y + 200, 51, 65)
def lookAt(self, coordinate):
self.look_at_pos = coordinate

Enemy doesn't follow player (pygame) [duplicate]

This question already has answers here:
How to make smooth movement in pygame
(2 answers)
How can i make a block follow another block in pygame [duplicate]
(2 answers)
Closed 2 years ago.
So I followed the answers in another question asked on StackOverflow but it seems that I have missed something. I went ahead after reading the answer and copied the code and adjusted it to my variables and class names.
The following is the error code that Idle gives me:
Traceback (most recent call last):
File "D:\Programme (x86)\Python\Games\Zombie Game\Zombie Game_Test1.py", line 133, in <module>
Zombie.move_towards_Char(Char)
TypeError: move_towards_Char() missing 1 required positional argument: 'Char'
This is where I looked:
How to make an enemy follow the player in pygame?
import pygame
import turtle
import time
import math
import random
import sys
import os
pygame.init()
WHITE = (255,255,255)
GREEN = (0,255,0)
RED = (255,0,0)
BLUE = (0,0,255)
BLACK = (0,0,0)
BGColor = (96,128,56)
ZColor = (225,0,0)
PColor = (0,0,255)
MOVE = 2.5
size = (1920, 1080)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Zombie Game")
class Char(pygame.sprite.Sprite):
def __init__(self, color, pos, radius, width):
super().__init__()
self.image = pygame.Surface([radius*2, radius*2])
self.image.fill(WHITE)
self.image.set_colorkey(WHITE)
pygame.draw.circle(self.image, color, [radius, radius], radius, width)
self.rect = self.image.get_rect()
def moveRightP(self, pixels):
self.rect.x += pixels
pass
def moveLeftP(self, pixels):
self.rect.x -= pixels
pass
def moveUpP(self, pixels):
self.rect.y -= pixels
pass
def moveDownP(self, pixels):
self.rect.y += pixels
pass
class Zombie(pygame.sprite.Sprite):
def __init__(self2, color, pos, radius, width):
super().__init__()
self2.image = pygame.Surface([radius*2, radius*2])
self2.image.fill(WHITE)
self2.image.set_colorkey(WHITE)
pygame.draw.circle(self2.image, color, [radius, radius], radius, width)
self2.rect = self2.image.get_rect()
self2.rect.center = pos
def move_towards_Char(self2, Char):
dx, dy = self2.rect.x - Char.rect.x, self2.rect.y - Char.rect.y
dist = math.hypot(dx, dy)
dx, dy = dx / dist, dy / dist
self2.rect.x += dx * self2.speed
self2.rect.y += dy * self2.speed
def moveRightZ(self2, pixels):
self2.rect.x += pixels
pass
def moveLeftZ(self2, pixels):
self2.rect.x -= pixels
pass
def moveUpZ(self2, pixels):
self2.rect.y -= pixels
pass
def moveDownZ(self2, pixels):
self2.rect.y += pixels
pass
all_sprites_list = pygame.sprite.Group()
playerChar = Char(PColor, [0, 0], 15, 0)
playerChar.rect.x = 960
playerChar.rect.y = 505
all_sprites_list.add(playerChar)
carryOn = True
clock = pygame.time.Clock()
zombie_list = []
zombie_rad = 15
zombie_dist = (200, 900)
next_zombie_time = pygame.time.get_ticks() + 10000
zombie_list = []
zombie_rad = 15
zombie_dist = (200, 900)
next_zombie_time = 10000
while carryOn:
for event in pygame.event.get():
if event.type==pygame.QUIT:
carryOn=False
elif event.type==pygame.KEYDOWN:
if event.key==pygame.K_x:
carryOn=False
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
playerChar.moveLeftP(MOVE)
if keys[pygame.K_d]:
playerChar.moveRightP(MOVE)
if keys[pygame.K_w]:
playerChar.moveUpP(MOVE)
if keys[pygame.K_s]:
playerChar.moveDownP(MOVE)
current_time = pygame.time.get_ticks()
if current_time > next_zombie_time:
next_zombie_time = current_time + 2000
on_screen_rect = pygame.Rect(zombie_rad, zombie_rad, size[0]-2*zombie_rad, size[1]-2*zombie_rad)
zombie_pos = (-1, -1)
while not on_screen_rect.collidepoint(zombie_pos):
dist = random.randint(*zombie_dist)
angle = random.random() * math.pi * 2
p_pos = (playerChar.rect.centerx, playerChar.rect.centery)
zombie_pos = (p_pos[0] + dist * math.sin(angle), p_pos[1] + dist * math.cos(angle))
new_pos = (random.randrange(0, size[0]), random.randrange(0, size[1]))
new_zombie = Zombie(RED, zombie_pos, zombie_rad, 0)
zombie_list.append(new_zombie)
screen.fill(BGColor)
screen.blit(playerChar.image,playerChar.rect)
for zombie in zombie_list:
screen.blit(zombie.image,zombie.rect)
pygame.display.flip()
clock.tick(60)
pygame.quit()
The major issue is, that you do the zombie movement calculations with integral data types. If the movement of a zombie is 1 pixel and the movement is diagonal, then the x and y component of the movement is < 1. Using an integral data type, this may results in 0 movement, because of truncating to int. Note the members of pygame.Rect are integral values.
You've to switch to floating point values to solve the issue. Use pygame.math.Vector2 to do the calculations.
Add a member pos of type Vector2 to the class Zombie which stores the floating point position of the zombie:
class Zombie(pygame.sprite.Sprite):
def __init__(self2, color, pos, radius, width):
super().__init__()
self2.image = pygame.Surface([radius*2, radius*2])
self2.image.fill(WHITE)
self2.image.set_colorkey(WHITE)
pygame.draw.circle(self2.image, color, [radius, radius], radius, width)
self2.rect = self2.image.get_rect()
self2.speed = 1
self2.pos = pygame.Vector2(pos[0], pos[1])
# [...]
Add a new method draw to the class Zombie, which draws (blit) a zombie at the position pos:
class Zombie(pygame.sprite.Sprite):
# [...]
def draw(self2):
self2.rect.center = (int(round(self2.pos.x)), int(round(self2.pos.y)))
screen.blit(self2.image, self2.rect)
Do the calculation of the movement of the zombie based on Vector2. Ensure that the distance between the player and the zombie is greater than 0 and that the zombie does not step over of the position of the player (min(len, self2.speed)):
class Zombie(pygame.sprite.Sprite):
# [...]
def move_towards_Char(self2, Char):
deltaVec = pygame.Vector2(Char.rect.center) - self2.pos
len = deltaVec.length()
if len > 0:
self2.pos += deltaVec/len * min(len, self2.speed)
Call the methods move_towards_Char and draw for each zombie, in the main loop of the application:
while carryOn:
for event in pygame.event.get():
if event.type==pygame.QUIT:
carryOn=False
elif event.type==pygame.KEYDOWN:
if event.key==pygame.K_x:
carryOn=False
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
playerChar.moveLeftP(MOVE)
if keys[pygame.K_d]:
playerChar.moveRightP(MOVE)
if keys[pygame.K_w]:
playerChar.moveUpP(MOVE)
if keys[pygame.K_s]:
playerChar.moveDownP(MOVE)
current_time = pygame.time.get_ticks()
if current_time > next_zombie_time:
next_zombie_time = current_time + 2000
on_screen_rect = pygame.Rect(zombie_rad, zombie_rad, size[0]-2*zombie_rad, size[1]-2*zombie_rad)
zombie_pos = (-1, -1)
while not on_screen_rect.collidepoint(zombie_pos):
dist = random.randint(*zombie_dist)
angle = random.random() * math.pi * 2
p_pos = (playerChar.rect.centerx, playerChar.rect.centery)
zombie_pos = (p_pos[0] + dist * math.sin(angle), p_pos[1] + dist * math.cos(angle))
new_pos = (random.randrange(0, size[0]), random.randrange(0, size[1]))
new_zombie = Zombie(RED, zombie_pos, zombie_rad, 0)
zombie_list.append(new_zombie)
# update all the positions of the zombies
for zombie in zombie_list:
zombie.move_towards_Char(playerChar)
screen.fill(BGColor)
screen.blit(playerChar.image,playerChar.rect)
# draw all the zombies
for zombie in zombie_list:
zombie.draw()
pygame.display.flip()
clock.tick(60)
L{Zombie.move_towards_Char} is a self method. You need to create object of Zombie class passing the required args mentioned in L{Zombie.init}.
Something like below:
zm = Zombie(color=<color>, pos=<pos>, radius=<radius>, width=<width>)
zm.move_towards_Char(Char)

Categories

Resources