Pygame Snake Game Issue [duplicate] - python

This question already has an answer here:
Python pygame need help disabling multiple keypresses at once [duplicate]
(1 answer)
Closed 2 years ago.
I am working on a pygame version of the game snake. The problem I am having so far is that I don't want to allow diagonal movement but currently there is. Any help would be much appreciated. Thanks in advance 🙂
import pygame
class Snake:
def __init__(self):
self.x = 250
self.y = 250
self.x_change = 0
self.y_change = 0
self.width = 25
self.height = 25
self.win = pygame.display.set_mode((500,500))
self.clock = pygame.time.Clock()
self.run = True
pygame.init()
pygame.display.set_caption('Snake')
def gameLoop(self):
while self.run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.x_change = -10
elif event.key == pygame.K_RIGHT:
self.x_change = 10
elif event.key == pygame.K_UP:
self.y_change = -10
elif event.key == pygame.K_DOWN:
self.y_change = 10
self.x += self.x_change
self.y += self.y_change
self.win.fill((76, 66, 53))
pygame.draw.rect(self.win, (145, 255, 51), (self.x, self.y, self.width, self.height))
pygame.display.update()
self.clock.tick(3)
pygame.quit()
p1 = Snake()
p1.gameLoop()

You can reset the change for the other axis back to 0. This way only one direction is changed per key press
def gameLoop(self):
while self.run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.x_change = -10
self.y_change = 0
elif event.key == pygame.K_RIGHT:
self.x_change = 10
self.y_change = 0
elif event.key == pygame.K_UP:
self.y_change = -10
self.x_change = 0
elif event.key == pygame.K_DOWN:
self.y_change = 10
self.x_change = 0
self.x += self.x_change
self.y += self.y_change
self.win.fill((76, 66, 53))
pygame.draw.rect(self.win, (145, 255, 51), (self.x, self.y, self.width, self.height))
pygame.display.update()
self.clock.tick(3)
pygame.quit()

Related

My player isn't showing when I run my Pygame project

I was programming player movement for my game and I'm not getting errors but the code isn't working correctly. The game is just presenting a black screen, if your able to help, please do that would be greatly appreciated! I've tried resetting my browser and such, but nothings working anyone able to help? (I'm using repl.it)
import pygame, sys
WIDTH, HEIGHT = 400, 400
TITLE = "DarkRoom"
pygame.init()
win = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption(TITLE)
clock = pygame.time.Clock()
class Player:
def __init__(self, x, y):
self.rect = pygame.Rect(x, y, 32, 32)
self.x = int(x)
self.y = int(y)
self.color = (255, 255, 255)
self.velX = 0
self.velY = 0
self.left_pressed = False
self.right_pressed = False
self.up_pressed = False
self.down_pressed = False
self.speed = 4
def draw(self, win):
pygame.draw.rect(win, self.color, self.rect)
def update(self):
self.velX = 0
self.velY = 0
if self.left_pressed and not self.right_pressed:
self.velX = -self.speed
if self.right_pressed and not self.left_pressed:
self.velX = self.speed
if self.up_pressed and not self.down_pressed:
self.velY = -self.speed
if self.down_pressed and not self.up_pressed:
self.velY = self.speed
self.x += self.velX
self.y += self.velY
self.rect = pygame.Rect(self.x, self.y, 32, 32)
player = Player(WIDTH/2, HEIGHT/2)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
player.left_pressed = True
if event.key == pygame.K_RIGHT:
player.right_pressed = True
if event.key == pygame.K_UP:
player.up_pressed = True
if event.key == pygame.K_DOWN:
player.down_pressed = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
player.left_pressed = False
if event.key == pygame.K_RIGHT:
player.right_pressed = False
if event.key == pygame.K_UP:
player.up_pressed = False
if event.key == pygame.K_DOWN:
player.down_pressed = False
win.fill((12, 24, 36))
player.draw(win)
player.update()
pygame.display.flip()
clock.tick(120)
It is just a matter of Indentation. You have to draw the player and update the display in the application loop, but not after the application loop:
while True:
for event in pygame.event.get():
# [...]
# INDENTATION
#->|
player.update()
pygame.display.flip()
clock.tick(120)

How do i detect if my character collided with an enemy and closes the game if it hits 3 times [duplicate]

This question already has answers here:
How to detect collisions between two rectangular objects or images in pygame
(1 answer)
Why is my collision test always returning 'true' and why is the position of the rectangle of the image always wrong (0, 0)?
(1 answer)
How do I detect collision in pygame?
(5 answers)
Closed 2 years ago.
I want to make it kind of like a life system so that if it collides with the enemy 3 times it will quit
pygame.init()
screen_width = 800
screen_height = 600
window = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Test')
time = pygame.time.Clock()
bg_color1 = (135, 142, 142) # MAIN BG COLOR
bg_color2 = (255, 0, 0) # red
bg_color3 = (255, 255, 0) # yellow
UFO = pygame.image.load('ufo.png')
bg_pic = pygame.image.load('Letsgo.jpg')
clock = pygame.time.Clock()
playerImg = pygame.image.load('enemy.png')
playerX = random.randrange(0, screen_width)
playerY = -50
playerX_change = 0
player_speed = 5
def player(x, y):
window.blit(playerImg, (playerX, playerY))
crashed = False
rect = UFO.get_rect()
obstacle = pygame.Rect(400, 200, 80, 80)
menu = True
playerY = playerY + player_speed
if playerY > screen_height:
playerX = random.randrange(0, screen_width)
playerY = -25
def ufo(x, y):
window.blit(UFO, (x, y))
while menu:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit()
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
menu = False
window.fill((0, 0, 0))
time.tick(30)
window.blit(bg_pic, (0, 0))
pygame.display.update()
x = (screen_width * 0.45)
y = (screen_height * 0.8)
x_change = 0
car_speed = 0
y_change = 0
while not crashed:
x += x_change
if x < 0:
x = 0
elif x > screen_width - UFO.get_width():
x = screen_width - UFO.get_width()
y += y_change
if y < 0:
y = 0
elif y > screen_height - UFO.get_height():
y = screen_height - UFO.get_height()
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
############SIDE TO SIDE################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
###########UP AND DOWN#################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = -5
elif event.key == pygame.K_DOWN:
y_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
if playerY > screen_height:
playerX = random.randrange(0, screen_width)
playerY = 0
playerY += 10
##
window.fill(bg_color1)
ufo(x, y)
player(playerX, playerY)
pygame.display.update()
clock.tick(100)
pygame.quit()
quit()
im thinking of using a collide.rect but cant figure it out any help is appreciated
I want the "playerImg" to be the enemy ...................................................................................
Create a variable that stores the number of lives. Create pygme.Rect objects of the player and the UFO with the method get_rect. Set the location of the rectangles by keyword arguments. Use colliderect to test the collision and decrease the number of lives when a collision is detected and create a new random starting position:
lives = 3
while not crashed:
# [...]
player_rect = playerImg.get_rect(topleft = (playerX, playerY))
ufo_rect = UFO.get_rect(topleft = (x, y))
if player_rect.colliderect(ufo_rect):
lives -= 1
print(lives)
playerX = random.randrange(0, screen_width)
playerY = 0
if lives == 0:
crashed = True
# [...]

Why isnt the #continue part in the program working?

It should call events() function and restart the whole process by displaying the block on the screen again, why isn't it working?
I tried breaking out of gameover(), tried calling pygame.display.update() but nothing seems to work [This is my 1st python game ever, so I may have been a little messy in typing my code]. Can anyone help me solve the problem?
import pygame
import time
pygame.init()
global display_height
global display_width
display_height = 800
display_width = 800
class slither(object):
def __init__(self,top):
self.top=top
self.x = display_height/2
self.y = display_width/2
self.x_change = 0
self.y_change = 0
self.gameOver = False
self.gameLoop = False
self.FPS=30
self.brick_size=10
self.black = (0,0,0)
self.white = (255,255,255)
self.red = (255,0,0)
self.font = pygame.font.SysFont(None, 30)
self.clock = pygame.time.Clock()
self.events()
self.message('',(0,0,0))
self.gameover()
def create_move(self, a, b):
pygame.draw.rect(screen, self.black , [a,b,self.brick_size,self.brick_size])
def message(self, msg, color):
screen_text=self.font.render(msg, True, color)
screen.blit(screen_text, [display_height/2, display_width/2])
pygame.display.update()
def events(self):
while self.gameLoop == False:
screen.fill(self.white)
self.create_move(self.x,self.y)
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.const=True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
self.x_change = -self.brick_size
self.y_change = 0
elif event.key == pygame.K_RIGHT:
self.x_change = self.brick_size
self.y_change = 0
elif event.key == pygame.K_UP:
self.y_change = -self.brick_size
self.x_change = 0
elif event.key == pygame.K_DOWN:
self.y_change = self.brick_size
self.x_change = 0
if self.x_change == -self.brick_size:
self.x -= self.brick_size
y=self.y
self.create_move(self.x, y)
elif self.x_change == self.brick_size:
self.x += self.brick_size
y=self.y
self.create_move(self.x, y)
if self.y_change == -self.brick_size:
self.y -= self.brick_size
x=self.x
self.create_move(x, self.y)
elif self.y_change == self.brick_size:
self.y += self.brick_size
x=self.x
self.create_move(x, self.y)
if self.x == display_height or self.x < 0 or self.y == display_width or self.y < 0 :
self.gameover()
pygame.display.update()
self.clock.tick(30)
def gameover(self):
while self.gameOver == False:
screen.fill((255, 255, 255))
self.message('Game over, Press any to continue or W to quit ', self.black)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
screen.fill(self.white)
self.message('Game Over, You lose', self.black)
time.sleep(2)
pygame.quit()
quit()
else:
self.events() #continue
screen=pygame.display.set_mode((display_height,display_width))
pygame.display.set_caption('Snake')
slither(0).events()
pygame.quit()
quit()
EDIT: I SOLVED IT, THANKS.
This is all I had to change.
Basically, because the block was still out of the screen, hence the gameover() used to get executed again, so when I brought the block back onto the screen, it worked.
else: #continue
self.x=display_height/2
self.y=display_width/2
self.events()

How do you move a sprite up and down?

I've been at it for a while, and I cannot seem to figure out why my sprite is not moving up or down when the program is run.
Player Sprite Class
def __init__(self,name,x,y):
pygame.sprite.Sprite.__init__(self)
self.name = str(name)
self.speed = 5
self.image = pygame.image.load(name+'.png').convert_alpha()
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def move_up(self):
self.rect.y -= self.speed
def move_down(self):
self.rect.y += self.speed
def move_left(self):
self.rect.x -= self.speed
def move_right(self):
self.rect.x += self.speed
def update(self):
self.screen.blit(self.image,(self.rect))
Main File / Loop
class Console:
def __init__(self,width,height):
pygame.init()
self.w = width
self.h = height
self.clock = pygame.time.Clock()
self.screen = pygame.display.set_mode((self.w,self.h))
self.screenName = pygame.display.set_caption("Star's Labyrinth")
class Background(pygame.sprite.Sprite):
def __init__(self,image_file,x,y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
def main():
gameExit = False
game_display = Console(1024,576)
game_display.screen
starboy = Player("starboy",200,200)
background = Background("background.png",0,0)
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
starboy.move_left()
elif event.key == pygame.K_d:
starboy.move_right()
elif event.type == pygame.K_w:
starboy.move_up()
elif event.type == pygame.K_s:
starboy.move_down()
print(pygame.event.get())
game_display.screen.blit(background.image,background.rect)
starboy.update
game_display.screen.blit(starboy.image,(starboy.rect.x,starboy.rect.y))
pygame.display.update()
game_display.clock.tick(30)
I have tried different types of commands trying to figure out whether it's a variable or function problem. Also is there a way I can make it move without having to tap the key.
In the event loop you're checking if the event.type is pygame.K_w or pygame.K_s, but you have to check if the event.key is equal to these constants. Change
elif event.type == pygame.K_w:
starboy.move_up()
elif event.type == pygame.K_s:
starboy.move_down()
to:
elif event.key == pygame.K_w:
starboy.move_up()
elif event.key == pygame.K_s:
starboy.move_down()
You also forgot the parentheses behind starboy.update.

Pygame keyboard animation not working correctly

import pygame
class Sprite:
def __init__(self, x, y, curren_time):
self.rect = pygame.Rect(x, y, 100, 110)
self.images = []
#Tells pygame the image list that you want to stitch together
for x in range(10):
img = pygame.image.load("C:/Users/Trevor/SkyDrive/Documents/TEST6/Cernunnos" + str(x) +".PNG")
#Append the image to each other to create the animation effect
self.images.append( img )
self.current_image = 0
self.time_num = 100
self.time_target = curren_time + self.time_num
def update(self, curren_time):
if curren_time >= self.time_target:
self.time_target = curren_time + self.time_num
self.current_image += 1
if self.current_image == len(self.images):
self.current_image = 0
def render(self, window):
window.blit(self.images[self.current_image], self.rect)
#Colors
black = (0,0,0)
white = (255,255,255)
def main():
pygame.init()
window = pygame.display.set_mode((800,600))
pygame.display.set_caption("Sprites")
move_x, move_y = 0, 0
clock = pygame.time.Clock()
curren_time = pygame.time.get_ticks()
player = Sprite(110,100,curren_time)
font = pygame.font.SysFont(None, 150)
pause_text = font.render("PAUSE",1,white)
pause_rect = pause_text.get_rect( center = window.get_rect().center )
#Adding how many places the image moves when using the key function
state_game = True
state_pause = False
#So while True
while state_game:
curren_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
state_game = False
elif event.type == pygame.KEYDOWN:
if event.key ==pygame.K_ESCAPE:
state_game = False
elif event.key == pygame.K_SPACE:
state_pause = not state_pause
if event.key == pygame.K_LEFT:
move_x = -3
elif event.key == pygame.K_RIGHT:
move_y = 3
elif event.key == pygame.K_UP:
move_x = -3
elif event.key == pygame.K_DOWN:
move_y = 3
elif event.type == pygame.KEYUP:
if event.key in (pygame.K_LEFT, pygame.K_RIGHT):
move_x = 0
elif event.key in (pygame.K_UP, pygame.K_DOWN):
move_y = 0
if not state_pause:
player.rect.x += move_x
player.rect.y += move_y
player.update(curren_time)
#Fills the window with a color
window.fill(black)
player.render(window)
if state_pause:
window.blit(pause_text,pause_rect)
pygame.display.flip()
clock.tick(50)
pygame.quit()
if __name__ == '__main__':
main()
#Code constructed by furas
So the problem is whenever I hit the right key the animation slides off the screen on the left. the animation does not stop when you take your finger off the key. I have searched for the problem myself and am unable to find any problems. Please if you see something that may be causing the problem let me know. Thanks! (Up key = Down, Down key = Down, Right key = Left, Left key = Left)
Your problem is that you have move_x and move_y swapped for K_RIGHT and K_UP.
elif event.key == pygame.K_RIGHT:
move_y = 3
elif event.key == pygame.K_UP:
move_x = -3
Should be:
elif event.key == pygame.K_RIGHT:
move_x = 3
elif event.key == pygame.K_UP:
move_y = -3

Categories

Resources