Difficiating objects in a group - python

In a group called powerUpGroup, there are two objects: speedUp and jumpUP. The following code checks if the player object has collided with any objects in the group:
for eachPowerUp in powerUpGroup:
if pygame.sprite.spritecollide(eachPowerUp, playerGroup, False) :
eachPowerUp.kill()
Let's say I only want the program to print "Speed increased" when the player collides with speedUp object. Based on the code above, it will print the message if it either speedUp or jumpUP since they are in the same group. Without creating a new group, is there a way for python to identify that they are different objects run certain code?

If speedUp and jumpUp are different classes, you should implement their behaviour in their very classes (something something polymorphism):
The speepUp class should contain the code for speeding up (or whatever it does) and trigger secondary effects (like displaying stuff to the player and removing itself from the game), and the jumpUp class should do the same. Of course you could go down the abstraction rabbit hole but let's keep it simple.
Here's a litte example:
import pygame
from random import choice
class Actor(pygame.sprite.Sprite):
def __init__(self, color, pos, *grps):
super().__init__(*grps)
self.image = pygame.Surface((64, 64))
self.image.fill(color)
self.rect = self.image.get_rect(topleft=pos)
def update(self, events, dt):
pass
class Player(Actor):
def __init__(self, *grps):
super().__init__('dodgerblue', (400, 300), *grps)
self.pos = pygame.Vector2(self.rect.topleft)
self.dir = pygame.Vector2((0, 0))
self.speed = 300
def update(self, events, dt):
pressed = pygame.key.get_pressed()
self.dir.x, self.dir.y = (0, 0)
if pressed[pygame.K_d]: self.dir += ( 1, 0)
if pressed[pygame.K_a]: self.dir += (-1, 0)
if pressed[pygame.K_s]: self.dir += ( 0, 1)
if pressed[pygame.K_w]: self.dir += ( 0, -1)
if self.dir.length() > 0:
self.dir.normalize()
self.pos += self.dir * self.speed * dt
self.rect.topleft = self.pos
class PowerUp(Actor):
def __init__(self, color, pos, player, *grps):
super().__init__(color, pos, *grps)
self.player = player
def apply(self):
pass
def update(self, events, dt):
if pygame.sprite.collide_rect(self, self.player):
self.apply()
self.kill()
class SpeedUp(PowerUp):
def __init__(self, player, *grps):
super().__init__('yellow', (100, 100), player, *grps)
def apply(self):
print('Speed Up')
self.player.speed += 200
class ColorChange(PowerUp):
def __init__(self, player, *grps):
super().__init__('purple', (600, 300), player, *grps)
def apply(self):
print('ColorChange!')
self.player.image.fill(choice(['green', 'blue', 'yellow', 'grey']))
def main():
pygame.init()
screen = pygame.display.set_mode((800, 600))
clock, dt = pygame.time.Clock(), 0
sprites = pygame.sprite.Group()
player = Player(sprites)
SpeedUp(player, sprites)
ColorChange(player, sprites)
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
screen.fill('black')
sprites.draw(screen)
sprites.update(events, dt)
pygame.display.flip()
dt = clock.tick(120)/1000
if __name__ == '__main__':
main()

Use an if statement to check if the power-up is speedUp
for eachPowerUp in powerUpGroup:
if pygame.sprite.spritecollide(eachPowerUp, playerGroup, False):
if eachPowerUp == speedUp:
print("Speed increased")
eachPowerUp.kill()
Edit for second part of question:
Instead of checking if the power up is a certain object, you can check if it is a certain class.
Say you have a class called SpeedUp. You can check to see if eachPowerUp is a SpeedUp object and then print the message you wanted.
for eachPowerUp in powerUpGroup:
if pygame.sprite.spritecollide(eachPowerUp, playerGroup, False):
if type(eachPowerUp) == SpeedUp:
print("Speed increased")
eachPowerUp.kill()

The previous code was an equality test between two sprites, not a type of sprite. The variable speedUp is one of your powerUpGroup sprites. The if statement will only be true if the particular speedUp that the player is colliding with is the particular speedUp in that variable.
So I added a property.
In the constructor(That was not added in the OP), I have self.type = "multiShot" or self.type = "speed", depending on which type it is. Then, an if statement would now be something like:
for eachPowerUp in powerUpGroup:
if pygame.sprite.spritecollide(eachPowerUp, playerGroup, False) :
if eachPowerUp.type == "multiShot" :
...
elif eachPowerUp.type == "speed" :
...

Related

How to not initialize the def init every time

this code is by tech with tim but i am trying to tweak it, i am trying to make the rotation velocity vary everytime.
import pygame
import time
import math
from utility import scale_image, blit_rotate_center
rotation_speed=2
Joystickx=0
GRASS = scale_image(pygame.image.load("Sprites/grass.png"),2.5)
TRACK = scale_image(pygame.image.load("Sprites/track.png"),0.7)
TRACK_BORDER = scale_image(pygame.image.load("Sprites/track-border.png"),0.7)
Car = scale_image(pygame.image.load("Sprites/F1.xcf"),0.1)
FINISH=pygame.image.load("Sprites/finish.png")
WIDTH, HEIGHT= TRACK.get_width(), TRACK.get_height()
WIN = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption("F1")
FPS = 60
class AbstractCar:
def __init__(self,max_vel,rotation_vel):
self.img=self.IMG
self.max_vel=max_vel
self.vel = 0
self.rotation_vel = rotation_vel
self.angle = 90
self.x, self.y = self.START_POS
def rotate(self, left=False, right=False):
if left:
self.angle += self.rotation_vel
print(self.angle)
elif right:
self.angle -= self.rotation_vel
print(self.angle)
def draw(self):
blit_rotate_center(WIN, self.img,(self.x, self.y), self.angle)
class PlayerCar(AbstractCar):
IMG = Car
START_POS = (180,200)
def draw(win,images, player_car):
for img, pos in images:
win.blit(img,pos)
player_car.draw()
pygame.display.update()
run=True
clock = pygame.time.Clock()
images = [(GRASS, (0,0)),(TRACK,(0,0))]
def rotate():
global rotation_speed
global Joystickx
rotation_speed+=2*Joystickx
rotation_speed*=0.9
while run:
clock.tick(FPS)
rotate()
player_car = PlayerCar(4, rotation_speed)
draw(WIN, images, player_car)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
break
keys = pygame.key.get_pressed()
if keys[pygame.K_a]:
player_car.rotate(left=True)
Joystickx=-1
elif keys[pygame.K_d]:
player_car.rotate(right=True)
Joystickx=1
else:
Joystickx=0
pygame.quit()
however, every time the class is ran, the code will set self.angle to 90, i do not want that to happen, what can i do to not let the def init run as that will set the self.angle to 94 instead remembering the last self.angle
This is OOP (Object Oriented Programming) thing. I really suggest you to look it up, it's not an easy topic at first, but it's also not that hard to understand everything in it, it's just the first time is hard.
So, the __init__ is the constructor of your AbstractCar class. This will always run when you make a new object from this class.
The simple way to fix this is to place the line where you define your car a bit above, outside the while loop and to keep the rotation_vel updated, we make a new method in the AbstractCar class and call it instead:
class AbstractCar:
def set_rotation_vel(self, new_rotation_vel):
self.rotation_vel = new_rotation_vel
[...]
player_car = PlayerCar(4, rotation_speed)
while run:
clock.tick(FPS)
rotate()
player_car.set_rotation_vel(rotation_speed)
draw(WIN, images, player_car)

Class inheritance in python with pygame

So I'm working on a hobby game, and i'm not able to get one class to inherit another properly. The file structure is as shown below:
main.py
Enemy
|walker.py
|genericEnemy.py
main.py calls walker.py, whose main class inherits from genericEnemy.py. Both of their contents are below:
walker.py
import pygame
from .genericEnemy import generic
class walker(generic):
pass
genericEnemy.py
'''
This class controls generic capabilities for all enemies.
Specific abilities are in the enemy type's class in the superfolder
'''
import pygame
class generic:
def __init__(self, speed, pos, size):
'''
speed - The entity speed, an int greater than 0
pos - The (x,y) position of the entity, a list of length 2
size - The entity hitbox, a list with length 2
'''
#Movement Variables
self.speed = speed
self.currDir = 1
self.isMoving = True
#Drawing Variables
self.pos = pos
self.size = size
#Gravity Variables
self.isJumping = False
self.fallCounter = 0
self.gravityTimer = 0
#==================================================
def draw(self, surface):
pygame.draw.rect(surface, (255, 0, 0), (self.pos[0], self.pos[1], self.size[0], self.size[1]))
#==================================================
def updateGravity(self):
self.fallCounter += 1
if self.fallCounter == 8:
self.fallCounter = 0
self.gravityTimer += 1
#==================================================
def walk(self):
if self.isMoving:
self.pos[0] += self.speed * self.currDir
The issue I'm having is that in main when I say:
SCREEN = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
ENEMY = walker(6, [120, 1000], [10, 30])
and then later on
ENEMY.draw(SCREEN)
I get the error: AttributeError: 'walker' object has no attribute 'draw'
Any help would be greatly appreciated, like I said this is a hobbyist project, so i'm fairly inexperienced in python/pygame
User Barmar was correct. I, as an absolute walnut, had my functions indented too far.
Use class generic(pygame.sprite.Sprite):
and
all_sprites = pygame.sprite.Group()
all_sprites.add(ENEMY)
all_sprites.draw(SCREEN)
pygame sprite group has
draw function
And maybe it need sprite.image!
It can be surface
self.image = pygame.Surface([self.size[0], self.size[1]])
self.image.fill((255, 0, 0))
or image file
self.image = pygame.transform.scale(pygame.image.load(imgname).convert_alpha(), (self.size[0], self.size[1]))

Updates to elements of list are applied to the whole list python

I am trying to write just a simple program to simulate an N-Body system using python (and pygame for GUI just because I have more experience than tk). The issue I am running into is I made a body class that is a subclass from a sprite. I have an adaptable list size of n that appends that many bodies into the list. To start I just decided to have updates be performed in a double for loop with a final for loop that passes the updates after they have been calculated (I know this is not efficient, not the point). My issue is that when I pass an update to an element of this list, the update is applied to every thing in that list. What is going on here? Why are these completely separate elements tied together? Necessary code below
Body class
class Body(Sprite):
vel = Vector2(0,0)
acc = Vector2(0,0)
def __init__(self, x, y, size, mass, init_val = True, color=(255,255,0)):
super().__init__()
self.rect = Rect(x-size[0]/2,y-size[1]/2,size[0],size[1])
self.mass = mass
self.pos = Vector2(x,y)
#self.vel = Vector2(random(),random())
if init_val:
self.acc = Vector2(random(),random())
self.image = Surface(size)
self.image.fill((255,255,255))
self.image.set_colorkey((255,255,255))
draw_circle(self.image,color,(size[0]/2,size[1]/2),size[0]/2)
def update(self, force):
self.acc += force
self.vel += self.acc
self.rect.move_ip(self.vel)
Sim loop
class nbody:
def __init__(self, n = 3, screensize=(1366,768)):
self.win = pg.display.set_mode(screensize)
self.clock = pg.time.Clock()
self.bodies = Group()
sareax = [int(screensize[0]/4), int(screensize[0]*3/4)]
sareay = [int(screensize[1]/4), int(screensize[1]*3/4)]
c = [(255,0,0), (0,255,0), (0,0,255)]
self.bodies = []
for i in range(n):
mass = 5 + random()*5
size = [mass*2]*2
self.bodies.append(Body(randint(sareax[0], sareax[1]),randint(sareay[0],sareay[1]),size,mass, init_val=False, color=c[i]))
def run_sim(self, time=None, fps = 0.5):
run = True
while run:
self.clock.tick(fps)
self.win.fill((0,0,0))
for e in pg.event.get():
if e.type == pg.QUIT:
pg.quit()
quit()
elif e.type == pg.KEYDOWN:
if e.key == pg.K_ESCAPE:
run = False
elif e.type == pg.KEYUP:
NotImplemented
updates = []
for b1,i in zip(self.bodies,range(len(self.bodies))):
df = Vector2(0,0)
for b2,j in zip(self.bodies,range(len(self.bodies))):
if i != j:
temp = newton(GRAV_CONSTANT, b1, b2)
mag = Vector2(b2.rect.centerx-b1.rect.centerx, b2.rect.centery-b1.rect.centery)
mag.scale_to_length(temp)
df += temp*mag
#print("Body {} has force {} to body {}".format(i,temp*mag,j))
if pg.sprite.collide_mask(b1,b2):
b1.kill()
b2.kill()
updates.append(df)
print(updates)
for bnum,up in zip(range(len(updates)),updates):
print("Before:", self.bodies[bnum].rect.center, self.bodies[bnum].vel, self.bodies[bnum].acc)
self.bodies[bnum].update(up)
print("Change:", up)
print("After:", self.bodies[bnum].rect.center, self.bodies[bnum].vel, self.bodies[bnum].acc)
pg.draw.line(self.win, (255,255,0), self.bodies[bnum].rect.center, (20*up.normalize())+self.bodies[bnum].rect.center, width=2)
self.win.blit(self.bodies[bnum].image,self.bodies[bnum].rect)
pg.display.flip()
return
See Class and Instance Variables:
Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class.
Since val and acc are class attributes they are shared by all Body objects and as you mentioned in your question: "these completely separate elements tied together".
vel and acc have to be instance attribute instead of class attributes:
class Body(Sprite):
def __init__(self, x, y, size, mass, init_val = True, color=(255,255,0)):
super().__init__()
self.rect = Rect(x-size[0]/2,y-size[1]/2,size[0],size[1])
self.mass = mass
self.pos = Vector2(x,y)
self.vel = Vector2(0,0)
self.acc = Vector2(0,0)
if init_val:
self.acc = Vector2(random(),random())
self.image = Surface(size)
self.image.fill((255,255,255))
self.image.set_colorkey((255,255,255))
draw_circle(self.image,color,(size[0]/2,size[1]/2),size[0]/2)

How to make a wave timer in pygame

So, I'm totally new to programming (been doing it for a couple of months) and decided to try coding a game.
On that note, a big thanks to Chris Bradfield for his series of tutorials in pygame coding, they are absolutely great!
However, now that I'm done with the tutorials and need to work on my own, I've come across a problem. I'm making a top-down shooter and making it wave-based. So, when zombies in one wave die, I want to show a timer that counts down until the next wave begins. I THINK I'm down the right path atm, let me show you what I'm working with.
def new(self)
'''
self.timer_flag = False
self.x = threading.Thread(target=self.countdown, args=(TIME_BETWEEN_WAVES,))
'''
def countdown(self, time_between_waves):
self.wave_timer = time_between_waves
for i in range(TIME_BETWEEN_WAVES):
while self.timer_flag:
self.wave_timer -=
time.sleep(1)
def update(self)
'''
self.countdown_has_run = False
if len(self.mobs) == 0:
self.timer_flag = True
if not self.countdown_has_run:
self.countdown_has_run = True
self.x.start()
'''
Now, I also draw my timer when the timer_flag is True, but it doesn't decrement, so I assume the problem lies somewhere in calling/starting the threaded countdown function?
Also, it's my first time posting here, so please let me know what to do to format better etc for you to be able to help
Don't bother with threads. No need to make your live complicated.
Usually, you use a Clock anyway in your game (if not, you should start using it) to limit the framerate, and to ensure that your world moves at a constant rante (if not, you should start doing it).
So if you want to trigger something in, say, 5 seconds, just create a variable that holds the value 5000, and substract the time it took to process your last frame (which is returned by Clock.tick):
clock = pygame.time.Clock()
dt = 0
timer = 5000
while True:
...
timer -= dt
if timer <= 0:
do_something()
dt = clock.tick(60)
I hacked together a simple example below. There, I use a simple class that is also a Sprite to draw the remaining time to the screen. When the timer runs out, it calls a function that creates a new wave of zombies.
In the main loop, I check if there's no timer running and no zombies, and if that's the case, a new timer is created.
Here's the code:
import pygame
import pygame.freetype
import random
# a dict that defines the controls
# w moves up, s moves down etc
CONTROLS = {
pygame.K_w: ( 0, -1),
pygame.K_s: ( 0, 1),
pygame.K_a: (-1, 0),
pygame.K_d: ( 1, 0)
}
# a function that handles the behaviour a sprite that
# should be controled with the keys defined in CONTROLS
def keyboard_controlled_b(player, events, dt):
# let's see which keys are pressed, and create a
# movement vector from all pressed keys.
move = pygame.Vector2()
pressed = pygame.key.get_pressed()
for vec in (CONTROLS[k] for k in CONTROLS if pressed[k]):
move += vec
if move.length():
move.normalize_ip()
move *= (player.speed * dt/10)
# apply the movement vector to the position of the player sprite
player.pos += move
player.rect.center = player.pos
# a function that let's a sprite follow another one
# and kill it if they touch each other
def zombie_runs_to_target_b(target):
def zombie_b(zombie, events, dt):
if target.rect.colliderect(zombie.rect):
zombie.kill()
return
move = target.pos - zombie.pos
if move.length():
move.normalize_ip()
move *= (zombie.speed * dt/10)
zombie.pos += move
zombie.rect.center = zombie.pos
return zombie_b
# a simple generic sprite class that displays a simple, colored rect
# and invokes the given behaviour
class Actor(pygame.sprite.Sprite):
def __init__(self, color, pos, size, behavior, speed, *grps):
super().__init__(*grps)
self.image = pygame.Surface(size)
self.image.fill(color)
self.rect = self.image.get_rect(center=pos)
self.pos = pygame.Vector2(pos)
self.behavior = behavior
self.speed = speed
def update(self, events, dt):
self.behavior(self, events, dt)
# a sprite class that displays a timer
# when the timer runs out, a function is invoked
# and this sprite is killed
class WaveCounter(pygame.sprite.Sprite):
font = None
def __init__(self, time_until, action, *grps):
super().__init__(grps)
self.image = pygame.Surface((300, 50))
self.image.fill((3,2,1))
self.image.set_colorkey((3, 2, 1))
self.rect = self.image.get_rect(topleft=(10, 10))
if not WaveCounter.font:
WaveCounter.font = pygame.freetype.SysFont(None, 32)
WaveCounter.font.render_to(self.image, (0, 0), f'new wave in {time_until}', (255, 255, 255))
self.timer = time_until * 1000
self.action = action
def update(self, events, dt):
self.timer -= dt
self.image.fill((3,2,1))
WaveCounter.font.render_to(self.image, (0, 0), f'new wave in {int(self.timer / 1000) + 1}', (255, 255, 255))
if self.timer <= 0:
self.action()
self.kill()
def main():
pygame.init()
screen = pygame.display.set_mode((600, 480))
screen_rect = screen.get_rect()
clock = pygame.time.Clock()
dt = 0
sprites_grp = pygame.sprite.Group()
zombies_grp = pygame.sprite.Group()
wave_tm_grp = pygame.sprite.GroupSingle()
# the player is controlled with the keyboard
player = Actor(pygame.Color('dodgerblue'),
screen_rect.center,
(32, 32),
keyboard_controlled_b,
5,
sprites_grp)
# this function should be invoked once the timer runs out
def create_new_wave_func():
# let's create a bunch of zombies that follow the player
for _ in range(15):
x = random.randint(0, screen_rect.width)
y = random.randint(-100, 0)
Actor((random.randint(180, 255), 0, 0),
(x, y),
(26, 26),
zombie_runs_to_target_b(player),
random.randint(2, 4),
sprites_grp, zombies_grp)
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
# no timer, no zombies => create new timer
if len(wave_tm_grp) == 0 and len(zombies_grp) == 0:
WaveCounter(5, create_new_wave_func, sprites_grp, wave_tm_grp)
sprites_grp.update(events, dt)
screen.fill((80, 80, 80))
sprites_grp.draw(screen)
pygame.display.flip()
dt = clock.tick(60)
if __name__ == '__main__':
main()
It looks to me you are lacking the mechanism to check how many mobs are left on screen. I imagine it could be something like this:
class CountdownClock:
def __init__(self):
self.start_no = 1
self.time_between_waves = 5
self.t = threading.Thread(target=self.check_mobs_left)
self.t.start()
def check_mobs_left(self):
self.mobs = ["mob" for _ in range(randint(2, 7))] #generate 2-7 mobs per level
print (f"Wave {self.start_no} : Total {len(self.mobs)} mobs found!")
while self.mobs:
print (f"Still {len(self.mobs)} mobs left!")
time.sleep(1)
del self.mobs[-1] #simulate mob kill - remove this line from your actual setting
self.next_wave(self.time_between_waves)
self.time_between_waves +=2 #increased time for each wave
def next_wave(self,time_between_waves):
self.time_left = time_between_waves
print(f"Wave {self.start_no} cleared!")
self.start_no += 1
while self.time_left:
print (f"Next wave in...{self.time_left}")
self.time_left -=1
time.sleep(1)
self.t = threading.Thread(target=self.check_mobs_left)
self.t.start()
a = CountdownClock()
You will have this up constantly without the need to call the method every round and set flag and stuff.

atan2 isn't providing me with the angle I want

I'm trying to write a game in pygame, involving a moving object with a "turret" that swivels to follow a mouse. As of now, I'm mostly trying to expand upon examples, so the code's not entirely mine (credit to Sean J. McKiernan for his sample programs); however, this portion is. Below is my code; I use the center of rect (the "base" shape and the point around which the "turret" swivels) as the base point, and the position of the mouse as the other point. By subtracting the mouse's displacement from the displacement of the "center," I effectively get a vector between the two points and find the angle between that vector and the x-axis with atan2. Below is the code I use to do that:
def get_angle(self, mouse):
x_off = (mouse[0]-self.rect.centerx)
y_off = (mouse[1]-self.rect.centery)
self.angle = math.degrees(math.atan2(-y_off, x_off) % 2*math.pi)
self.hand = pg.transform.rotate(self.original_hand, self.angle)
self.hand_rect = self.hand.get_rect(center=self.hand_rect.center)
According to multiple tutorials I've reviewed, this SHOULD be the correct code; however, I discovered later that those tutorials (and, in fact, this tutorial) were all for Python 2.7, while I am trying to write in Python 3.6. I don't think that should make a difference in this scenario, though. As it stands, the view appears to depend entirely upon the "character's" position on the screen. If the "character" is in one corner, the reaction of the "turret" is different than the reaction if the "character" is in the middle of the screen. However, this shouldn't matter; the position of the "character" relative to the mouse is the exact same no matter where on the screen they are. Any ideas, or do I need to supply more code?
Edit: Apparently, more code is required. Rather than attempt to extricate only the entirely necessary parts, I've provided the entire code sample, so everyone can run it. As a side note, the "Bolt" things (intended to fire simple yellow blocks) don't work either, but I'm just trying to get the arm working before I start in on debugging that.
Edit the second: I have discovered that the "Bolt" system works within a certain distance of the origin (0,0 in the window coordinate system), and that the arm also works within a much lesser distance. I added the line Block(pg.Color("chocolate"), (0,0,100,100)) under the "walls" grouping as a decision point, and the block was positioned in the top left corner. I've corrected Bolt by changing screen_rect to viewport in the control loop; however, I don't know why the "arm" swinging is dependent on adjacency to the origin. The positions of the mouse and "character" SHOULD be absolute. Am I missing something?
"""
Basic moving platforms using only rectangle collision.
-Written by Sean J. McKiernan 'Mekire'
Edited for a test of "arms"
"""
import os
import sys
import math
import pygame as pg
CAPTION = "Moving Platforms"
SCREEN_SIZE = (700,700)
BACKGROUND_COLOR = (50, 50, 50)
COLOR_KEY = (255, 255, 255)
class _Physics(object):
"""A simplified physics class. Psuedo-gravity is often good enough."""
def __init__(self):
"""You can experiment with different gravity here."""
self.x_vel = self.y_vel = 0
self.grav = 0.4
self.fall = False
def physics_update(self):
"""If the player is falling, add gravity to the current y velocity."""
if self.fall:
self.y_vel += self.grav
else:
self.y_vel = 0
class Player(_Physics, object):
def __init__(self,location,speed):
_Physics.__init__(self)
HAND = pg.image.load("playertst2.png").convert()
HAND.set_colorkey(COLOR_KEY)
self.image = pg.image.load('playertst.png').convert()
self.rect = self.image.get_rect(topleft=location)
self.speed = speed
self.jump_power = -9.0
self.jump_cut_magnitude = -3.0
self.on_moving = False
self.collide_below = False
self.original_hand = HAND
self.fake_hand = self.original_hand.copy()
self.hand = self.original_hand.copy()
self.hand_rect = self.hand.get_rect(topleft=location)
self.angle = self.get_angle(pg.mouse.get_pos())
def check_keys(self, keys):
"""Find the player's self.x_vel based on currently held keys."""
self.x_vel = 0
if keys[pg.K_LEFT] or keys[pg.K_a]:
self.x_vel -= self.speed
if keys[pg.K_RIGHT] or keys[pg.K_d]:
self.x_vel += self.speed
def get_position(self, obstacles):
"""Calculate the player's position this frame, including collisions."""
if not self.fall:
self.check_falling(obstacles)
else:
self.fall = self.check_collisions((0,self.y_vel), 1, obstacles)
if self.x_vel:
self.check_collisions((self.x_vel,0), 0, obstacles)
def check_falling(self, obstacles):
"""If player is not contacting the ground, enter fall state."""
if not self.collide_below:
self.fall = True
self.on_moving = False
def check_moving(self,obstacles):
"""
Check if the player is standing on a moving platform.
If the player is in contact with multiple platforms, the prevously
detected platform will take presidence.
"""
if not self.fall:
now_moving = self.on_moving
any_moving, any_non_moving = [], []
for collide in self.collide_below:
if collide.type == "moving":
self.on_moving = collide
any_moving.append(collide)
else:
any_non_moving.append(collide)
if not any_moving:
self.on_moving = False
elif any_non_moving or now_moving in any_moving:
self.on_moving = now_moving
def check_collisions(self, offset, index, obstacles):
"""
This function checks if a collision would occur after moving offset
pixels. If a collision is detected, the position is decremented by one
pixel and retested. This continues until we find exactly how far we can
safely move, or we decide we can't move.
"""
unaltered = True
self.rect[index] += offset[index]
self.hand_rect[index] += offset[index]
while pg.sprite.spritecollideany(self, obstacles):
self.rect[index] += (1 if offset[index]<0 else -1)
self.hand_rect[index] += (1 if offset[index]<0 else -1)
unaltered = False
return unaltered
def check_above(self, obstacles):
"""When jumping, don't enter fall state if there is no room to jump."""
self.rect.move_ip(0, -1)
collide = pg.sprite.spritecollideany(self, obstacles)
self.rect.move_ip(0, 1)
return collide
def check_below(self, obstacles):
"""Check to see if the player is contacting the ground."""
self.rect.move_ip((0,1))
collide = pg.sprite.spritecollide(self, obstacles, False)
self.rect.move_ip((0,-1))
return collide
def jump(self, obstacles):
"""Called when the user presses the jump button."""
if not self.fall and not self.check_above(obstacles):
self.y_vel = self.jump_power
self.fall = True
self.on_moving = False
def jump_cut(self):
"""Called if player releases the jump key before maximum height."""
if self.fall:
if self.y_vel < self.jump_cut_magnitude:
self.y_vel = self.jump_cut_magnitude
def get_angle(self, mouse):
x_off = (mouse[0]-self.rect.centerx)
y_off = (mouse[1]-self.rect.centery)
self.angle = math.degrees(math.atan2(-y_off, x_off) % (2*math.pi))
self.hand = pg.transform.rotate(self.original_hand, self.angle)
self.hand_rect = self.hand.get_rect(center=self.hand_rect.center)
"""
offset = (mouse[1]-self.hand_rect.centery, mouse[0]-self.hand_rect.centerx)
self.angle = math.atan2(-offset[0], offset[1]) % (2 * math.pi)
self.angle = math.degrees(self.angle)
self.hand = pg.transform.rotate(self.original_hand, self.angle)
self.hand_rect = self.hand.get_rect(center=self.rect.center)
self.angle = 135-math.degrees(math.atan2(*offset))
self.hand = pg.transform.rotate(self.original_hand, self.angle)
self.hand_rect = self.hand.get_rect(topleft=self.rect.topleft)
"""
def pre_update(self, obstacles):
"""Ran before platforms are updated."""
self.collide_below = self.check_below(obstacles)
self.check_moving(obstacles)
def update(self, obstacles, keys):
"""Everything we need to stay updated; ran after platforms update."""
self.check_keys(keys)
self.get_position(obstacles)
self.physics_update()
def get_event(self, event, bolts):
if event.type == pg.MOUSEBUTTONDOWN and event.button == 1:
bolts.add(Bolt(self.rect.center))
elif event.type == pg.MOUSEMOTION:
self.get_angle(event.pos)
def draw(self, surface):
"""Blit the player to the target surface."""
surface.blit(self.image, self.rect)
surface.blit(self.hand, self.hand_rect)
class Bolt(pg.sprite.Sprite):
def __init__(self, location):
pg.sprite.Sprite.__init__(self)
"""self.original_bolt = pg.image.load('bolt.png')"""
"""self.angle = -math.radians(angle-135)"""
"""self.image = pg.transform.rotate(self.original_bolt, angle)"""
"""self.image = self.original_bolt"""
self.image=pg.Surface((5,10)).convert()
self.image.fill(pg.Color("yellow"))
self.rect = self.image.get_rect(center=location)
self.move = [self.rect.x, self.rect.y]
self.speed_magnitude = 5
"""self.speed = (self.speed_magnitude*math.cos(self.angle), self.speed_magnitude*math.sin(self.angle))"""
"""self.speed = (5,0)"""
self.done = False
def update(self, screen_rect, obstacles):
self.move[0] += self.speed_magnitude
"""self.move[1] += self.speed[1]"""
self.rect.topleft = self.move
self.remove(screen_rect, obstacles)
def remove(self, screen_rect, obstacles):
if not self.rect.colliderect(screen_rect):
self.kill()
class Block(pg.sprite.Sprite):
"""A class representing solid obstacles."""
def __init__(self, color, rect):
"""The color is an (r,g,b) tuple; rect is a rect-style argument."""
pg.sprite.Sprite.__init__(self)
self.rect = pg.Rect(rect)
self.image = pg.Surface(self.rect.size).convert()
self.image.fill(color)
self.type = "normal"
class MovingBlock(Block):
"""A class to represent horizontally and vertically moving blocks."""
def __init__(self, color, rect, end, axis, delay=500, speed=2, start=None):
"""
The moving block will travel in the direction of axis (0 or 1)
between rect.topleft and end. The delay argument is the amount of time
(in miliseconds) to pause when reaching an endpoint; speed is the
platforms speed in pixels/frame; if specified start is the place
within the blocks path to start (defaulting to rect.topleft).
"""
Block.__init__(self, color, rect)
self.start = self.rect[axis]
if start:
self.rect[axis] = start
self.axis = axis
self.end = end
self.timer = 0.0
self.delay = delay
self.speed = speed
self.waiting = False
self.type = "moving"
def update(self, player, obstacles):
"""Update position. This should be done before moving any actors."""
obstacles = obstacles.copy()
obstacles.remove(self)
now = pg.time.get_ticks()
if not self.waiting:
speed = self.speed
start_passed = self.start >= self.rect[self.axis]+speed
end_passed = self.end <= self.rect[self.axis]+speed
if start_passed or end_passed:
if start_passed:
speed = self.start-self.rect[self.axis]
else:
speed = self.end-self.rect[self.axis]
self.change_direction(now)
self.rect[self.axis] += speed
self.move_player(now, player, obstacles, speed)
elif now-self.timer > self.delay:
self.waiting = False
def move_player(self, now, player, obstacles, speed):
"""
Moves the player both when on top of, or bumped by the platform.
Collision checks are in place to prevent the block pushing the player
through a wall.
"""
if player.on_moving is self or pg.sprite.collide_rect(self,player):
axis = self.axis
offset = (speed, speed)
player.check_collisions(offset, axis, obstacles)
if pg.sprite.collide_rect(self, player):
if self.speed > 0:
self.rect[axis] = player.rect[axis]-self.rect.size[axis]
else:
self.rect[axis] = player.rect[axis]+player.rect.size[axis]
self.change_direction(now)
def change_direction(self, now):
"""Called when the platform reaches an endpoint or has no more room."""
self.waiting = True
self.timer = now
self.speed *= -1
"""class Spell(pg.sprite.Sprite):
def __init__(self, location, angle)"""
class Control(object):
"""Class for managing event loop and game states."""
def __init__(self):
"""Initalize the display and prepare game objects."""
self.screen = pg.display.get_surface()
self.screen_rect = self.screen.get_rect()
self.clock = pg.time.Clock()
self.fps = 60.0
self.keys = pg.key.get_pressed()
self.done = False
self.player = Player((50,875), 4)
self.viewport = self.screen.get_rect()
self.level = pg.Surface((1000,1000)).convert()
self.level_rect = self.level.get_rect()
self.win_text,self.win_rect = self.make_text()
self.obstacles = self.make_obstacles()
self.bolts = pg.sprite.Group()
def make_text(self):
"""Renders a text object. Text is only rendered once."""
font = pg.font.Font(None, 100)
message = "You win. Celebrate."
text = font.render(message, True, (100,100,175))
rect = text.get_rect(centerx=self.level_rect.centerx, y=100)
return text, rect
def make_obstacles(self):
"""Adds some arbitrarily placed obstacles to a sprite.Group."""
walls = [Block(pg.Color("chocolate"), (0,980,1000,20)),
Block(pg.Color("chocolate"), (0,0,20,1000)),
Block(pg.Color("chocolate"), (980,0,20,1000))]
static = [Block(pg.Color("darkgreen"), (250,780,200,100)),
Block(pg.Color("darkgreen"), (600,880,200,100)),
Block(pg.Color("darkgreen"), (20,360,880,40)),
Block(pg.Color("darkgreen"), (950,400,30,20)),
Block(pg.Color("darkgreen"), (20,630,50,20)),
Block(pg.Color("darkgreen"), (80,530,50,20)),
Block(pg.Color("darkgreen"), (130,470,200,215)),
Block(pg.Color("darkgreen"), (20,760,30,20)),
Block(pg.Color("darkgreen"), (400,740,30,40))]
moving = [MovingBlock(pg.Color("olivedrab"), (20,740,75,20), 325, 0),
MovingBlock(pg.Color("olivedrab"), (600,500,100,20), 880, 0),
MovingBlock(pg.Color("olivedrab"),
(420,430,100,20), 550, 1, speed=3, delay=200),
MovingBlock(pg.Color("olivedrab"),
(450,700,50,20), 930, 1, start=930),
MovingBlock(pg.Color("olivedrab"),
(500,700,50,20), 730, 0, start=730),
MovingBlock(pg.Color("olivedrab"),
(780,700,50,20), 895, 0, speed=-1)]
return pg.sprite.Group(walls, static, moving)
def update_viewport(self):
"""
The viewport will stay centered on the player unless the player
approaches the edge of the map.
"""
self.viewport.center = self.player.rect.center
self.viewport.clamp_ip(self.level_rect)
def event_loop(self):
"""We can always quit, and the player can sometimes jump."""
for event in pg.event.get():
if event.type == pg.QUIT or self.keys[pg.K_ESCAPE]:
self.done = True
elif event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE:
self.player.jump(self.obstacles)
elif event.type == pg.KEYUP:
if event.key == pg.K_SPACE:
self.player.jump_cut()
elif event.type == pg.MOUSEMOTION or event.type == pg.MOUSEBUTTONDOWN:
self.player.get_event(event, self.bolts)
def update(self):
"""Update the player, obstacles, and current viewport."""
self.keys = pg.key.get_pressed()
self.player.pre_update(self.obstacles)
self.obstacles.update(self.player, self.obstacles)
self.player.update(self.obstacles, self.keys)
self.update_viewport()
self.bolts.update(self.screen_rect, self.obstacles)
def draw(self):
"""
Draw all necessary objects to the level surface, and then draw
the viewport section of the level to the display surface.
"""
self.level.fill(pg.Color("lightblue"))
self.obstacles.draw(self.level)
self.level.blit(self.win_text, self.win_rect)
self.player.draw(self.level)
self.bolts.draw(self.level)
self.screen.blit(self.level, (0,0), self.viewport)
def display_fps(self):
"""Show the programs FPS in the window handle."""
caption = "{} - FPS: {:.2f}".format(CAPTION, self.clock.get_fps())
pg.display.set_caption(caption)
def main_loop(self):
"""As simple as it gets."""
while not self.done:
self.event_loop()
self.update()
self.draw()
pg.display.update()
self.clock.tick(self.fps)
self.display_fps()
if __name__ == "__main__":
os.environ['SDL_VIDEO_CENTERED'] = '1'
pg.init()
pg.display.set_caption(CAPTION)
pg.display.set_mode(SCREEN_SIZE)
PLAYERIMG = pg.image.load("playertst.png").convert()
PLAYERIMG.set_colorkey(COLOR_KEY)
run_it = Control()
run_it.main_loop()
pg.quit()
sys.exit()
The % 2*pi unnecessary, and your get_angle function has no return value, but you do an assignment to self.angle = self.get_angle, but that is not the issue. The issue is that the mouse position is relative to the screen (i.e. clicking in the top right area of your game screen will always yield (0,480) if your screen is 640x480), while the position of the (character) rectangle is given in your game play area, which is larger than the screen, ergo if you move the character and thus the view shifts, you are getting coordinates in two different coordinate systems. You will have to keep track of where the view is in your game play area and add the offset to the mouse coordinates.

Categories