how can I reflect the screen in pygame - python

I want to make rectangles out from the right edge
How can I make these rectangles move horizontally?
I tried to understand it from this tutorial but I couldn't here
so any ideas about this
my little character ghost
btata.png
import pygame
from pygame.locals import *
import sys
import time
import random
pygame.init()
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((800,600))
pygame.display.set_caption('FullMarx')
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
crashed = False
ghostImg = pygame.image.load('btata.png')
clock = pygame.time.Clock()
def ghost(x,y):
gameDisplay.blit(ghostImg, (x,y))
def things(thingx, thingy, thingw, thingh, color):
pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',20)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
def gameOver():
message_display('Game Over')
def rect():
pygame.draw.rect(screen, color, (x,y,width,height), thickness)
def event():
for event in pygame.event.get():
if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE):
pygame.quit()
sys.exit()
def game():
ghost_width = 50
x = 20
y = 180
isJump = False
jumpCount = 9
#x_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -300
thing_speed = 7
thing_width = 30
thing_height = 30
while True:
event()
gameDisplay.fill(white)
ghost(x,y)
#____Ghost_Motion___________#
keys = pygame.key.get_pressed()
if not(isJump):
if keys[pygame.K_UP] or keys[pygame.K_SPACE] or keys[pygame.K_w]:
isJump = True
walkCount = 0
else:
if jumpCount >= -9:
neg = 1
if jumpCount < 0:
neg = -1
y -= (jumpCount ** 2) * 0.5 * neg
jumpCount -= 1
else:
isJump = False
jumpCount = 9
clock.tick(50)
#____Ghost_Motion___________#
# things(thingx, thingy, thingw, thingh, color)
things(thing_startx, thing_starty, thing_width, thing_height, black)
thing_starty += thing_speed
ghost(x,y)
if thing_starty > display_height:
thing_starty = 0 - thing_height
thing_startx = random.randrange(0,display_width)
if y < thing_starty+thing_height:
print('y crossover')
if x > thing_startx and x < thing_startx + thing_width or x+ghost_width > thing_startx and x + ghost_width < thing_startx+thing_width:
print('x crossover')
gameOver()
pygame.display.update()
#clock.tick(60)
game()
pygame.quit()
quit()

You move a rect (and therefore a player/an image) by modifying its x and y coordinates.
Here's a rudimentary and commented example to help you visualize:
import pygame
from pygame.locals import *
# Initialize a screen
SCREEN = pygame.display.set_mode((700, 500))
# Fill it with black
SCREEN.fill((0, 0, 0))
# Create a rect that'll represent our player
# Arguments: x, y, width, height
player = pygame.rect.Rect(100, 100, 20, 50)
# Keep track of which direction
# the player is moving in
moving_left = False
moving_right = False
moving_up = False
moving_down = False
# Loop
while True:
for event in pygame.event.get():
# Go through every event that pygame
# records, the 'event queue' and
# react accordingly
# User closed the window
if event.type == QUIT:
pygame.quit()
# If the user presses any key, a
# KEYDOWN event is placed into the
# event queue, and we detect it here
if event.type == KEYDOWN:
# The pressed key is 'd'
if event.key == K_d:
moving_right = True
# The pressed key is 'a'
if event.key == K_a:
moving_left = True
# The pressed key is 'w'
if event.key == K_w:
moving_up = True
# The pressed key is 's'
if event.key == K_s:
moving_down = True
# However, if the user lifts stops
# pressing the keyboard,
# a KEYUP event will be placed into
# the event queue
if event.type == KEYUP:
# The unpressed key is 'd'
if event.key == K_d:
moving_right = False
# The unpressed key is 'a'
if event.key == K_a:
moving_left = False
# The unpressed key is 'w'
if event.key == K_w:
moving_up = False
# The unpressed key is 's'
if event.key == K_s:
moving_down = False
# Increment/decrement the players
# coordinates, its 'position'
# this is akin to movement
if moving_left:
player.x -= 2
if moving_right:
player.x += 2
if moving_up:
player.y -= 2
if moving_down:
player.y += 2
# Repaint our screen black,
SCREEN.fill((0, 0, 0))
# draw our player (the rect)
# onto the SCREEN, at its coordinates
# in white.
# You'd simply use SCREEN.blit
# here in order to place an image
pygame.draw.rect(
SCREEN, (255, 255, 255),
player
)
# refresh the screen to show our changes
pygame.display.update()
You've got to conceptualize movement on a 2D surface like so:

Related

Python Snake doesn't grow [duplicate]

This question already has an answer here:
How do I get the snake to grow and chain the movement of the snake's body?
(1 answer)
Closed 1 year ago.
I'm new to python and only now the basics, I'm trying to make a snake game but I can't seem to figure out how to make my snake grow 1 extra square each time it eats an apple. My reasoning is that I keep a list of all the old positions but only show the last one on the screen, and each time the snakes eats another apple it shows 1 extra old positions making the snake 1 square longer.
This is my code:
import pygame
from random import randint
WIDTH = 400
HEIGHT = 300
dis = pygame.display.set_mode((WIDTH,HEIGHT))
white = (255,255,255)
BACKGROUND = white
blue = [0,0,255]
red = [255,0,0]
class Snake:
def __init__(self):
self.image = pygame.image.load("snake.bmp")
self.rect = self.image.get_rect()
self.position = (10,10)
self.direction = [0,0]
self.positionslist = [self.position]
self.length = 1
pygame.display.set_caption('Snake ')
def draw_snake(self,screen):
screen.blit(self.image, self.position)
def update(self):
self.position = (self.position[0] + self.direction[0],self.position[1] + self.direction[1])
self.rect = (self.position[0],self.position[1],5, 5 )
self.positionslist.append(self.position)
if self.position[0]< 0 :
self.position = (WIDTH,self.position[1])
elif self.position[0] > WIDTH:
self.position = (0,self.position[1])
elif self.position[1] > HEIGHT:
self.position = (self.position[0],0)
elif self.position[1] < 0 :
self.position = (self.position[0],HEIGHT)
class Food:
def __init__(self):
self.image = pygame.image.load("appel.png")
self.rect = self.image.get_rect()
apple_width = -self.image.get_width()
apple_height = -self.image.get_height()
self.position = (randint(0,WIDTH+apple_width-50),randint(0,HEIGHT+apple_height-50))
self.rect.x = self.position[0]
self.rect.y = self.position[1]
def draw_appel(self,screen):
screen.blit(self.image, self.position)
def eat_appel (self, snake):
if self.rect.colliderect(snake.rect) == True:
self.position = (randint(0,WIDTH),randint(0,HEIGHT))
self.rect.x = self.position[0]
self.rect.y = self.position[1]
snake.length += 1
def main():
game_over = False
while not game_over:
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
snake = Snake()
food = Food()
while True:
screen.fill(BACKGROUND)
font = pygame.font.Font('freesansbold.ttf', 12)
text = font.render(str(snake.length), True, red, white)
textRect = text.get_rect()
textRect.center = (387, 292)
screen.blit(text,textRect)
snake.update()
#snake.update_list()
snake.draw_snake(screen)
food.draw_appel(screen)
food.eat_appel(snake)
pygame.display.flip()
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
snake.direction = [0,1]
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
snake.direction = [1,0]
if event.key == pygame.K_LEFT:
snake.direction = [-1,0]
if event.key == pygame.K_UP:
snake.direction = [0,-1]
if event.key == pygame.K_DOWN:
snake.direction = [0,1]
if __name__ == "__main__":
main()
This can have multiple reasons. Firstly, I saw you tried to increase the length of the snake by typing snake.length += 1, which may work (probably won't because the module pygame allows the snake to hover around, but not like the loop or conditional statements). One of my tips would be, to increase the length of the snake by using the idea of adding the score with your present snake.length every time (because once your score is 1 by eating an apple, your snake.length would be 2. And it increases with the score). This is my code (a few modifications might be needed):
import pygame
import time
import random
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
orange = (255, 165, 0)
width, height = 600, 400
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Mania")
clock = pygame.time.Clock()
snake_size = 10
snake_speed = 15
message_font = pygame.font.SysFont('ubuntu', 30)
score_font = pygame.font.SysFont('ubuntu', 25)
def print_score(score):
text = score_font.render("Score: " + str(score), True, orange)
game_display.blit(text, [0,0])
def draw_snake(snake_size, snake_pixels):
for pixel in snake_pixels:
pygame.draw.rect(game_display, white, [pixel[0], pixel[1], snake_size, snake_size])
def run_game():
game_over = False
game_close = False
x = width / 2
y = height / 2
x_speed = 0
y_speed = 0
snake_pixels = []
snake_length = 1
target_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
target_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
while not game_over:
while game_close:
game_display.fill(black)
game_over_message = message_font.render("Game Over!", True, red)
game_display.blit(game_over_message, [width / 3, height / 3])
print_score(snake_length - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
game_over = True
game_close = False
if event.key == pygame.K_2:
run_game()
if event.type == pygame.QUIT:
game_over = True
game_close = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_speed = -snake_size
y_speed = 0
if event.key == pygame.K_RIGHT:
x_speed = snake_size
y_speed = 0
if event.key == pygame.K_UP:
x_speed = 0
y_speed = -snake_size
if event.key == pygame.K_DOWN:
x_speed = 0
y_speed = snake_size
if x >= width or x < 0 or y >= height or y < 0:
game_close = True
x += x_speed
y += y_speed
game_display.fill(black)
pygame.draw.rect(game_display, orange, [target_x, target_y, snake_size, snake_size])
snake_pixels.append([x, y])
if len(snake_pixels) > snake_length:
del snake_pixels[0]
for pixel in snake_pixels[:-1]:
if pixel == [x, y]:
game_close = True
draw_snake(snake_size, snake_pixels)
print_score(snake_length - 1)
pygame.display.update()
if x == target_x and y == target_y:
target_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
target_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
snake_length += 1
clock.tick(snake_speed)
pygame.quit()
quit()
run_game()

If I have two rectangles of different sizes(10 by 10 and 20 by 20) in Pygame, how can I figure out when the two rectangles collide?

I am unable to detect when two rectangles of different sizes collide.
I've tried, "if x == obj_x and y == obj_y:" where x is one rectangle's x-value, obj_x is the other rectangle's x value, and the same for the y-values.
import pygame
import time
import random
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
display_width = 500
display_height = 500
screen = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Avoid')
x_change = 0
y_change = 0
FPS = 30
block_size = 10
font = pygame.font.SysFont(None, 25)
smallfont = pygame.font.SysFont("comicsansms",25)
def showLives(lives):
text = smallfont.render("Lives: "+str(lives), True, white)
screen.blit(text, [0,0])
def message_to_screen(msg,color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [100,250])
clock = pygame.time.Clock()
def gameLoop():
gameExit = False
gameOver = False
x = 250
y = 425
x_change = 0
y_change = 0
obj_speed = 5
obj_y = 0
obj_x = 0
obj2_y = 0
obj2_x = 0
obj2_speed = 3
lives = 3
while not gameExit:
while gameOver == True:
screen.fill(white)
message_to_screen("Game Over, Press C to play again or Q to quit", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -block_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = block_size
y_change = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
x_change = 0
y_change = 0
if x > 500-block_size:
x-=block_size
if x < 0+block_size:
x+=block_size
# if x >= display_width-block_size-block_size or x < 0:
# gameOver = True
obj_y = obj_y + obj_speed
if obj_y > display_height:
obj_x = random.randrange(0, display_width-block_size)
obj_y = -25
obj2_y = obj2_y + obj2_speed
if obj2_y > display_height:
obj2_x = random.randrange(1, display_width-block_size)
obj2_y = -27
x += x_change
y += y_change
screen.fill(black)
pygame.draw.rect(screen,white, [obj_x,obj_y,20,20])
pygame.draw.rect(screen,white, [obj2_x,obj2_y,20,20])
pygame.draw.rect(screen, red, [x,y,block_size,block_size])
showLives(lives)
pygame.display.update()
if x == obj_x and y == obj_y:
lives -= 1
if lives == 0:
gameOver = True
clock.tick(FPS)
pygame.quit()
quit()
gameLoop()
I want the program to detect when any part of the rectangles collide instead of just detecting when one point on each of the rectangles collide.
PyGame has class pygame.Rect() to keep rectangle's position and size. It uses it to draw images/sprites and check collision between sprites.
x = 250
y = 425
obj_y = 0
obj_x = 0
rect_1 = pygame.Rect(x, y, 10, 10)
rect_2 = pygame.Rect(obj_x, obj_y, 20, 20)
and then you can check collision
rect_1.colliderect(rect_2)
You can also use it to draw rectangle on screen
pygame.draw.rect(screen, white, rect_2)
pygame.draw.rect(screen, red, rect_1)
You can also use it to check collision between rectangle and point - ie. to check if button was clicked by mouse
button_rect.collidepoint(event.pos)
To change values in rectangle you have rect_1.x, rect_1.y, rect_1.width, rect_1.height but also
x,y
top, left, bottom, right
topleft, bottomleft, topright, bottomright
midtop, midleft, midbottom, midright
center, centerx, centery
size, width, height
w,h
Some of them takes tuple with (x, y)
for example: center rectangle on screen
rect_1.center = (display_width//2, display_height//2)
or event using screen
rect_1.center = screen.get_rect().center
OR center text on screen
screen_text_rect = screen_text.get_rect()
screen_text_rect.center = screen.get_rect().center
screen.blit(screen_text, screen_text_rect)

I can not get my collision to work in pygame

import pygame, time, random
pygame.init()
display_width = 800
display_height = 600
white = (255,255,255)
green = (0,255,0)
black = (0,0,0)
gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
boy = pygame.image.load("pig.png")
fence = pygame.image.load("fence.png")
def message_display(text):
largeText = pygame.font.Font("freesansbold.ttf",115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = (display_width/2),(display_height/2)
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def crash():
message_display("Game Over")
def fence1(fencex, fencey, fencew, fenceh, color):
gameDisplay.blit(fence, (fencex, fencey, fencew, fenceh))
def collision():
pig_image = pygame.image.load("pig.png")
pig_rect = pig_image.get_rect()
fence_image = pygame.image.load("fence.png")
fence_rect = fence_image.get_rect()
if pig_rect.colliderect(fence_rect):
crash()
def game_loop():
fence_startx = 900
fence_starty = gameDisplay.get_height() * 0.8
fence_speed = 15
fence_width = 50
fence_height = 50
x = gameDisplay.get_width() * 0.1
y = gameDisplay.get_height() * 0.8
y_change = 0
on_ground = True
gravity = .9
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
if on_ground:
y_change = -20
on_ground = False
y_change += gravity
y += y_change
if y >= 500:
y = 500
y_change = 0
on_ground = True
gameDisplay.fill(green)
gameDisplay.blit(boy, (x, y))
fence1(fence_startx, fence_starty, fence_width, fence_height, white)
fence_startx -= fence_speed
randomx = random.randint(1,3)
if fence_startx <= -50:
if randomx == 1:
fence_startx = 1000
if randomx == 2:
fence_startx = 800
if randomx == 3:
fence_startx = 1500
collision()
pygame.display.flip()
clock.tick(60)
game_loop()
pygame.quit()
quit()
For some reason when I run this code, it spams me "Game Over". Could someone please help me on this issue. I use a collision function in this code. Is using the pygame.rect code the best way to do collision in pygame? Everything works except for my collision in the game. I would greatly appreciate some help. Thanks.
In the collision function you create two rects but leave their coordinates at the default position (0, 0) so the rects overlap. You should add rects for the player and the fence in the main game_loop function, set their x and y (or the topleft) attributes to the desired coordinates and then update them every iteration of the while loop. To check if the rects collide, pass them to the collision function and do this:
def collision(boy_rect, fence_rect):
if boy_rect.colliderect(fence_rect):
# I'm just printing it to shorten the code example.
print('crash')
Here's a minimal, complete example:
import random
import pygame
pygame.init()
green = (0,255,0)
gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
boy = pygame.Surface((40, 60))
boy.fill((0, 40, 100))
fence = pygame.Surface((50, 50))
fence.fill((100, 60, 30))
def collision(boy_rect, fence_rect):
if boy_rect.colliderect(fence_rect):
# I'm just printing it to shorten the code example.
print('crash')
def game_loop():
fence_speed = 15
# Create a fence and a boy rect and set their x,y or topleft coordinates.
fence_rect = fence.get_rect()
fence_rect.x = 900
fence_rect.y = gameDisplay.get_height() * 0.8
x = gameDisplay.get_width() * 0.1
y = gameDisplay.get_height() * 0.8
boy_rect = boy.get_rect(topleft=(x, y))
y_change = 0
on_ground = True
gravity = .9
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
if on_ground:
y_change = -20
on_ground = False
y_change += gravity
y += y_change
if y >= 500:
y = 500
y_change = 0
on_ground = True
boy_rect.y = y # Update the rect position.
gameDisplay.fill(green)
gameDisplay.blit(boy, boy_rect)
gameDisplay.blit(fence, fence_rect)
# Update the position of the fence rect.
fence_rect.x -= fence_speed
if fence_rect.x <= -50:
# You can use random.choice to pick one of these values.
fence_rect.x = random.choice((800, 1000, 1500))
# Pass the two rects and check if they collide.
collision(boy_rect, fence_rect)
pygame.display.flip()
clock.tick(60)
game_loop()
pygame.quit()

How to tell if a sprite is touching another sprite in pygame

I know people already asked this but my code is very different and their solution does not apply to my problem.
I am trying to make a game where the objective is to "catch" the fruit. However, whenever my basket touches the fruit, the fruit goes right past the basket. Here is my code:
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
car_width = 64
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Avoid The Falling Objects')
clock = pygame.time.Clock()
carImg = pygame.image.load('basket.png')
appleImg = pygame.image.load('apple.png')
score = 0
def things(thingx, thingy):
#pygame.draw.rect(gameDisplay, color, [thingx, thingy, thingw, thingh])\
gameDisplay.blit(appleImg, (thingx,thingy))
def car(x,y):
gameDisplay.blit(carImg, (x,y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',40)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display(('You dropped a fruit! Your score was: {}').format(score))
def game_loop():
score = 0
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
thing_startx = random.randrange(0, display_width)
thing_starty = -600
thing_speed = 7
thing_width = 100
thing_height = 100
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
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
x += x_change
gameDisplay.fill(white)
things(thing_startx, thing_starty)
thing_starty += thing_speed
car(x,y)
if x > display_width - car_width or x < 0 - car_width:
crash()
if thing_starty > display_height:
crash()
if y < thing_starty+thing_height:
print('y crossover')
if x > thing_startx and x < thing_startx + thing_width or x + car_width > thing_startx and x + car_width < thing_startx:
score += 1
thing_starty = -100
thing_startx = random.randrange(0, display_width)
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
You could use pygame.Rect() and colliderect() to check collision.
import pygame
import random
# --- constants --- (UPPER_CASE names)
DISPLAY_WIDTH = 800
DISPLAY_HEIGHT = 600
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
CAR_WITDH = 64
# --- functions --- (lower_case names)
def text_objects(text, font):
text_image = font.render(text, True, BLACK)
return text_image, text_image.get_rect()
def message_display(text):
large_font = pygame.font.Font('freesansbold.ttf',40)
text_image, text_rect = text_objects(text, large_font)
text_rect.center = screen_rect.center
screen.blit(text_image, text_rect)
pygame.display.update()
pygame.time.delay(2000)
def crash(score):
message_display(('You dropped a fruit! Your score was: {}').format(score))
def reset_positions():
car_rect.x = DISPLAY_WIDTH * 0.45
car_rect.y = DISPLAY_HEIGHT * 0.8
apple_rect.x = random.randrange(0, DISPLAY_WIDTH)
apple_rect.y = -600
def game_loop():
score = 0
x_change = 0
apple_speed = 7
reset_positions()
clock = pygame.time.Clock()
while True:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
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 in (pygame.K_LEFT, pygame.K_RIGHT):
x_change = 0
# --- updates (without draws) ---
car_rect.x += x_change
apple_rect.y += apple_speed
if car_rect.right > DISPLAY_WIDTH or car_rect.left < 0:
crash(score)
reset_positions()
score = 0
if apple_rect.bottom > DISPLAY_HEIGHT:
crash(score)
reset_positions()
score = 0
if car_rect.colliderect(apple_rect):
score += 1
car_rect.y -= 10
apple_rect.x = random.randrange(0, DISPLAY_WIDTH-apple_rect.width)
apple_rect.y = -600
# --- draws (without updates) ---
screen.fill(WHITE)
screen.blit(apple_image, apple_rect)
screen.blit(car_image, car_rect)
pygame.display.update()
# --- FPS ---
clock.tick(60)
# --- main --- (lower_case names)
# - init -
pygame.init()
screen = pygame.display.set_mode((DISPLAY_WIDTH, DISPLAY_HEIGHT))
screen_rect = screen.get_rect()
pygame.display.set_caption('Avoid The Falling Objects')
# - objects -
car_image = pygame.image.load('basket.png')
car_rect = car_image.get_rect()
apple_image = pygame.image.load('apple.png')
apple_rect = apple_image.get_rect()
# - mainloop -
game_loop()

Why does the score increase abruptly in pygame?

I am trying to make a game in pygame, but i am getting two bugs.
Bug 1
My score increases abruptly in the game , where my condition is to increase only 1 point at a time.
My code to increase score is:
if thing_starty >display_height:
thing_stary = 0-thing_height
thing_startx= random.randrange(0,display_width)
dodged += 1
thing_speed += 1
thing_width += (dodged * 1.2)
Here dodged is my score , it should increase by one every time the block goes off the screen.
Bug 2
In my game there is a black rectangle following from top, but the thing is once it goes off the screen, it does not come back.Also after the block passes outside the screen , the game ends even if there is no collision.
The code for the block to come back is:
if thing_starty >display_height: #Check if block is there in the screen or not
thing_stary = 0 - thing_height
thing_startx= random.randrange(0,display_width)
dodged += 1
thing_speed += 1
thing_width += (dodged * 1.2)
Full code:
import pygame
import time
import random
pygame.init()
#Colours
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
#Game Display
display_width = 1080
display_height = 720
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Eat It! ~ Snapnel Productions')
#Clock
clock = pygame.time.Clock()
FPS = 60
#Font Size
exsmallfont = pygame.font.SysFont("comicsansms", 17)
smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 80)
#Car
def car(x,y):
gameDisplay.blit(carimg,(x,y))
global x, y, x_change
carimg=pygame.image.load('food.png')
#With of the car( i.e food image)
car_width=10
#Things
def things(thingx,thingy,thingw,thingh,color):
pygame.draw.rect(gameDisplay,color,[thingx,thingy,thingw,thingh])
#Things doged
def things_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, red)
gameDisplay.blit(text,(0,0))
#Starting Of the game
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key ==pygame.K_c:
intro = False
if event.key ==pygame.K_q:
pygame.quit()
quit()
gameDisplay.fill(black)
#Game Initial display message
message_to_screen("Dodge It!",
red,
-200,
size="large")
message_to_screen("Press 'C' to play the game or 'Q' to quit.",
white,
150,
size="small")
pygame.display.update()
clock.tick(15)
#Text Size
def text_objects(text,color, size):
if size=="small":
textSurface=smallfont.render(text, True ,color)
elif size=="medium":
textSurface=medfont.render(text, True ,color)
elif size=="large":
textSurface=largefont.render(text, True ,color)
return textSurface,textSurface.get_rect()
#Message to screen
def message_to_screen(msg,color,y_displace=0,size="small"):
textSurf,textRect=text_objects(msg,color,size)
textRect.center = (display_width / 2),(display_height / 2)+y_displace
gameDisplay.blit(textSurf,textRect)
#The Game run up
def runGame():
#global x,y, x_change
gameExit = False
gameOver = False
x=(display_width*0.45)
y=(display_height*0.48)
x_change =0
#To count score
thingCount=1
dodged=0
#Block Initial Size
thing_startx = random.randrange(0,display_width)
thing_starty = -600
thing_speed = 7
thing_width = 100
thing_height = 100
while not gameExit:
while gameOver == True:
#Game Over message
gameDisplay.fill(white)
message_to_screen("Game over",
red,
y_displace=-50,
size="large")
message_to_screen("Press C to play again or Q to quit.",
red,
y_displace=50,
size="medium")
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
#Game Controls
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
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
x += x_change
gameDisplay.fill(white)
things(thing_startx,thing_starty,thing_width,thing_height,black)
thing_starty+=thing_speed
car(x,y)
things_dodged(dodged)
if x>display_width-car_width or x<0:
gameOver = True
#Check if block is in the screen
if thing_starty >display_height:
thing_stary = 0 - thing_height
thing_startx= random.randrange(0,display_width)
dodged += 1
thing_speed += 1
thing_width += (dodged * 1.2)
#Check Collision with block
if y < thing_starty+thing_height:
print('y crossover')
if x > thing_startx and x < thing_startx + thing_width or x+car_width > thing_startx and x + car_width < thing_startx+thing_width:
print('x crossover')
gameOver = True
pygame.display.update()
#The game run up
def gameLoop():
clock.tick(FPS)
runGame()
pygame.quit()
quit()
game_intro()
gameLoop()
is the food image.
Thanks in advance fellows , really , thanks to pay attention to this bug.
You have a typo in your variable name, it should likely be:
thing_starty
instead of:
thing_stary

Categories

Resources