I am making a pacman style game in pygame using python and i am trying to make it so that when the player collides with an enemy sprite (monster) the score gets reduced by 1. The code for the monster and player are below and also the code i have tried to minus the score. Any help would be appreciated. I can post the whole game code if this will help.
The code i have tried to minus the player lives when colliding with a monster is below.
for monster in group:
if player.rect.colliderect(monster.rect):
player.lives -= 1
I suspect the problem is that you only create livestext at the beginning. The should be re-created each time you print it on the screen.
You seem to be drawing the text right at the end, after the game (why then?). So move the livestext=... line to before the blit. The lives may well be doing what you want, but perhaps you can't see it?
Also, I'd recommend making lives an instance member:
Do self.lives=5 in the __init__
and use self.lives instead of lives every time it occurs.
Related
I'm working on a simple platformer game in Arcade with a player and an enemy.
If the player collides with the enemy, I would like the game to start over from scratch.
However, with my current code, I call setup() and the game resets, but I am unable to move my player and the enemy doesn't move either. Please help!
if len(arcade.check_for_collision_with_list(self.zombie, self.enemies)) > 0:
self.game_over = True
if self.game_over:
self.score = 0
self.setup()
self.update()
Did you remember to set self.game_over = False after restarting?
You didn't provide enough information, but the problem should be that some variables didn't reset when you called setup(). So that's what you need to do
I am trying to create a game that places a cat which I can move left and right at the bottom of the screen.
Then I make a ball appear at a random position on the top of the screen and fall down the screen at a steady rate.
If the cat catches the ball by colliding with it, I make the ball disappear.
Meanwhile, I make a new ball each time the cat catches the ball or whenever the ball disappears off the bottom of the screen.
My question is: how do I make the ball disappear after being caught by the cat and then create a new ball over and over?
Currently I can think of two approaches to this problem:
First, I create a single ball. Once the cat catches the ball, I write some codes to make THAT ball disappear. Then, write some codes to create a new ball. Put these codes in a loop somehow to keep a ball disappear and reappear over and over. The problem is, I am not sure which codes to write to make a ball disappear and then create a new one.
Second approach is, I create a group of balls balls = Group() using pygame.sprite. I let those balls drop one after another. When a cat catches a ball, I remove that ball from the group of balls. Then let another ball in the group drop.
for ball in balls.copy():
if cat.rect.colliderect(ball.rect):
balls.remove(ball)
This second approach has somehow created another problem. When I wanted to specify the collision between the cat and each ball, I sometimes received the error message saying that either the name "ball" is not define or the name "balls" is not defined. Plus, I don't know whether it is really necessary to use a for loop whenever I want to specify a cat-ball collision. I feel that there has to be a more straight-forward and efficient way than this.
Would the first approach be better? If yes, please let me know how to make a ball disappear and to create a new ball immediately afterwards. THANK YOU SO MUCH!!
Probably the easiest way is to create a sprite with the following template:
class Ball(pygame.sprite.Sprite):
""" falls and restarts the ball position when ball hits the cat or the ground"""
def __init__(self):
""" setting up the ball image, rect, caught_by_cat flag etc. """
def update(self):
if self.hits_the_ground():
self.reset()
elif self.caught_by_cat:
self.reset()
else:
self.fall()
def reset(self):
""" randomize the ball position and set the ball rect to this position and resets the caught_by_cat flag """
def hits_the_ground(self):
""" checks whether ball hits the bottom of the board """
def fall(self):
""" move the ball rectangle with a steady speed """
and then after the initialization and adding it to the pygame.sprite.Group, in the game event loop simply:
sprite_group.update()
sprite_group.draw(screen)
Check for collision
if cat_collides_with_ball:
ball.caught_by_cat = True
This way you don't need to create many ball objects, you just need to restart the ball rect attribute to draw it in other place.
so I am trying to make my enemy not scroll with my camera when it moves left and right
I someone helped me make a function to stop my enemy from scrolling all it suppose to do is not make my enemy scroll example vid
def onscroll(enemying, delta_scroll):
for enemys in enemying:
enemys.position = (enemys.position[0] - delta_scroll, enemys.position[1])
then on my main loop I called that function so my enemy doesnt scroll with my screen
# camera left and right movement
if playerman.y < 250:
playerman.y += 1
for enemys in enemying:
enemys.y += delta_scroll
but for some reason I keep getting the same error
name 'delta_scroll' is not defined
Enemy Class
my full code
Quick tip- there are a TON of pg.image.load("myImg.png") commands. here is a better way of doing it:
standingright = []
for i in range(1, 16):
imgPath = "d"+str(i)+".png"
img = pg.image.load(imgPath)
standingright.append(img)
This is a much more concise way of loading the images. It will result in the exact same list of images in the exact same order, but I thought I would mention it to you because it will make your code much neater.
About the issue at hand: I searched your code for mentions of delta_scroll, and found it being used, but never defined. Also I saw you defined the function "onscroll", but never used it. Are you getting these two mixed up perhaps?
I am trying to copy from the app store in pygame for practice, i have set up a system where if you beat the current high score it will write it into the file so that it can be saved for later so the user can try and beat their score.
def player_death(player_score): # What happens when the player dies
end_font = pygame.font.Font('freesansbold.ttf', 50)
print("You have died") # For debugging
score_file = open('data/score.txt', 'a') # Don't think this is related
score_file.write(str(player_score)) # Don't think this is related
score_file.close() # Don't think this is related
b_score_file = open('data/score_best.txt', 'r')
score_read = int(b_score_file.read())
b_score_file.close()
if player_score >= score_read:
b_score_file = open('data/score_best.txt', 'w')
b_score_file.write(str(player_score))
b_score_file.close()
print("New best score!") # For debugging
print(score_read) # For debugging
return best_score2
Every time the player collides with a Rect it adds to the score, in the main game loop that is then passed as 'player_score' to be used in the death screen, there is a loop and other stuff in the function, but i think i have narrowed it down to this part. If more code is need i can add. The thing is it works completely fine if the high score saved in the score_best.txt is higher than the score you just got. In the main loop of code i have it so if you collide with the rect either at the top or the bottom of the screen it will run the function above. If any more information is needed, feel free to ask, as i am running out of ideas.
When the player hits either of the parts that run this function it still detects it and runs the "you have died" print statement but then the actual screen which has been drawn through this function (not shown in the pasted code) doesn't show and just makes the player hit the ground and bounce off.
I removed the line
return best_score2
This fixed the issues.
I am currently working on a 2D game in which the player has to sneak up on a still person within a certain amount of time. There are various crates in the way (depending on which level it is), and I would like to make it so that the player can hide behind crates to sneak up on the still person.
I thought that I could use a cone-type vision for the person looking, but I'm not exactly sure how I would accomplish that. The player doesn't have to see the vision cone of the person looking either.
A similar effect to what I would like is in this sample code on github.
NOTE: The player cannot pass through the crates, and the people and crates are sprites.
You have to calculate the if the player is in line with the person, if it is you can check for every box if the 3 objects are ate the same position, if not you are in vision field person_looking. concidere player and person a list with coords.
def isInLine(player, person):
deltaX = person[0] - player[0]
deltaY = person[1] - player[1]
if (person[0] == player[0]) or (person[1] == player[1]) or (abs(deltaX) == abs(deltaY)):
return true
Like in a chess game, imagine you ahve to check if the king is in check by a queen. Its the same logic here.
I think you can create an invisible projectile of a size of one pixel which you launch at desired angle towards player. You make it have some travel speed (say 2 pixels at a time) but instead of actually allowing the projectile to travel every frame you just loop for its travel untill it collides with something (either player or crate or end of level). So the whole emmision and collision process is done outside of while True main game loop in some function. You can emit it every second or something instead of every frame. And also you can emmit it in a cone shape either by scailing it's size every loop or emiting new one at different angle. If any of those collide with player mask or rect -> you have established a line of sight. This idea actually came to me right now out of the blue...
;)
On the second thought... maybe not 1 pixel size projectile but just collidepoint function. Just move your point from emmision origin to target at desired resolution.