Mouse clicked on random image in python [duplicate] - python

This question already has an answer here:
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)
Closed 2 years ago.
I am beginner in python. Recently i am doing a pygame poject. I want to make a game where the screen will show an image in a random position, and after 0.3 seconds, the image will move to another random position again. The player will repeatedly click on the position-changed image with the mouse and the score will increase. Even if I do everything, clicking with the mouse does not increase the score.
Here is my code:
pygame.init()
width = 500
height = 500
score = 0
display = pygame.display.set_mode((width, height))
pygame.display.set_caption("Tapping")
image = pygame.image.load('spaceship.png').convert()
sides = ['Top', 'Botom', 'left', 'Right']
weights = [width, width, height, height]
posx = random.randint(50, 450)
posy = random.randint(20, 460)
tsp = 1.2
Mousex = 0
Mousey = 0
def image_view(x, y):
display.blit(image, (x, y))
run = True
while run:
display.fill((153, 255, 187))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
Mousex, Mousey = event.pos
if image.get_rect().collidepoint(posx, posy):
score += 1
side = random.choices(sides, weights)[0]
if side == 'Top':
posx = random.randrange(100, 300)
posy = random.randrange(20, 100)
time.sleep(tsp)
elif side == 'Botom':
posx = random.randrange(350, 430)
posy = random.randrange(250, 450)
time.sleep(tsp)
elif side == 'left':
posx = random.randrange(20, 250)
posy = random.randrange(20, 250)
time.sleep(tsp)
elif side == 'Right':
posx = random.randrange(280, 450)
posy = random.randrange(280, 450)
time.sleep(tsp)
print(score)
image_view(posx, posy)
pygame.display.update()

You have to evaluate if the mouse is on the image. Note, a pygame.Surface has no position. It is blit at a position. Hence the position of the pygame.Rect object, which is returned by get_rect() is (0, 0).
You have to set the position by a keyword argument (e.g. image.get_rect(topleft = (posx, posy))). Finally you can use collidepoint() to evaluate if the mouse cursor (Mousex, Mousey) is on the region of the display, where the image is currently placed:
if event.type == pygame.MOUSEBUTTONDOWN:
Mousex, Mousey = event.pos
image_rect = image.get_rect(topleft = (posx, posy))
if image_rect.collidepoint(Mousex, Mousey):
score += 1
Further more, time.sleep(tsp) prevents the system from responding. Never delay the main application loop.
Use pygame.time.get_ticks() to get get the time in milliseconds. Add a variable next_choice_time. The time indicates when the position of the image has to be changed. Set a new time when the position of the image is changed:
next_choice_time = 0
while run:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
Mousex, Mousey = event.pos
image_rect = image.get_rect(topleft = (posx, posy))
if image_rect.collidepoint(Mousex, Mousey):
score += 1
next_choice_time = current_time
if current_time >= next_choice_time:
next_choice_time = current_time + 300 # 300 milliseconds == 0.3 seconds
side = random.choices(sides, weights)[0]
# [...]
See the example:
import pygame
import random
pygame.init()
width = 500
height = 500
score = 0
display = pygame.display.set_mode((width, height))
pygame.display.set_caption("Tapping")
image = pygame.image.load('spaceship.png').convert()
sides = ['Top', 'Botom', 'left', 'Right']
weights = [width, width, height, height]
posx = random.randint(50, 450)
posy = random.randint(20, 460)
tsp = 1.2
Mousex = 0
Mousey = 0
def image_view(x, y):
display.blit(image, (x, y))
run = True
next_choice_time = 0
while run:
current_time = pygame.time.get_ticks()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
Mousex, Mousey = event.pos
image_rect = image.get_rect(topleft = (posx, posy))
if image_rect.collidepoint(Mousex, Mousey):
score += 1
next_choice_time = current_time
print(score)
if current_time >= next_choice_time:
next_choice_time = current_time + 300 # 300 milliseconds == 0.3 seconds
side = random.choices(sides, weights)[0]
if side == 'Top':
posx = random.randrange(100, 300)
posy = random.randrange(20, 100)
elif side == 'Botom':
posx = random.randrange(350, 430)
posy = random.randrange(250, 450)
elif side == 'left':
posx = random.randrange(20, 250)
posy = random.randrange(20, 250)
elif side == 'Right':
posx = random.randrange(280, 450)
posy = random.randrange(280, 450)
display.fill((153, 255, 187))
image_view(posx, posy)
pygame.display.update()

Related

How do you move the circle to the mouse position [duplicate]

This question already has answers here:
pygame 2 dimensional movement of an enemy towards the player, how to calculate x and y velocity?
(1 answer)
Pygame make sprite walk in given rotation
(1 answer)
How to make smooth movement in pygame
(2 answers)
Closed 1 year ago.
I created a circle in pygame. The circle moves to wherever you click, but instead of "walking" over there, it just appears. I tried some ways, but it doesn't work. If you could find out a way to do it, that would be great. The moving function is in the move function in the Player class.
# import
import pygame
# initialize pygame
pygame.init()
# frame rate variables
FPS = 120
clock = pygame.time.Clock()
# game variables
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800
mouse_pos = ''
# colors
BLUE = (0, 0, 255)
# activate screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Bonker')
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
# init the sprite class
pygame.sprite.Sprite.__init__(self)
self.x = x
self.y = y
self.mouse_x = 0
self.mouse_y = 0
def move(self):
# delta x and delta y
dx = 0
dy = 0
# extract info from tuple
(x, y) = mouse_pos
self.mouse_x = x
self.mouse_y = y
# create tuple destination and current position tuple
destination = (self.mouse_x, self.mouse_y)
current_pos = [self.x, self.y]
# draw the rectangle
if current_pos[0] >= SCREEN_WIDTH // 2:
dx = 10
self.x += dx
if current_pos[0] < SCREEN_WIDTH // 2:
dx = -10
self.x += dx
if current_pos[1] >= SCREEN_HEIGHT // 2:
dy = 10
self.y += dy
if current_pos[1] < SCREEN_HEIGHT // 2:
dy = -10
self.y += dy
pygame.draw.circle(screen, BLUE, (self.x, self.y), 20)
def draw(self):
# draw the circle
pygame.draw.circle(screen, BLUE, (SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2), 20)
# create instances
# player instance
player = Player(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
player.draw()
# main loop
run = True
while run:
# run frame rate
clock.tick(FPS)
# events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
screen.fill((0, 0, 0))
mouse_pos = pygame.mouse.get_pos()
player.move()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
pygame.display.update()
pygame.quit()
I think some code is not needed
Help would be appreciated
This will move the circle to the mouse position. It doesn't move in one diagonal, but that can be changed.
# import
import pygame
# initialize pygame
pygame.init()
# frame rate variables
FPS = 120
clock = pygame.time.Clock()
# game variables
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 800
# colors
BLUE = (0, 0, 255)
# activate screen
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Bonker')
class Player(pygame.sprite.Sprite):
def __init__(self, x, y):
# init the sprite class
pygame.sprite.Sprite.__init__(self)
self.rect = pygame.Rect(0, 0, 40, 40)
self.rect.x = x
self.rect.y = y
self.radius = 20
self.destination = None
self.moving = False
self.dx = 0
self.dy = 0
def set_destination(self, pos):
self.destination = pos
# delta x and delta y
self.dx = self.destination[0] - self.rect.centerx
self.dy = self.destination[1] - self.rect.centery
self.moving = True
def move(self):
if self.rect.centerx != self.destination[0]:
if self.dx > 0:
self.rect.centerx += 1
elif self.dx < 0:
self.rect.centerx -= 1
if self.rect.centery != self.destination[1]:
if self.dy > 0:
self.rect.centery += 1
elif self.dy < 0:
self.rect.centery -= 1
elif self.rect.center == self.destination:
self.moving = False
def draw(self):
# draw the circle
pygame.draw.circle(screen, BLUE, self.rect.center, self.radius)
# create instances
# player instance
player = Player(SCREEN_WIDTH // 2, SCREEN_HEIGHT // 2)
player.draw()
# main loop
run = True
movetime = 100
move = False
while run:
# run frame rate
dt = clock.tick(FPS)
movetime -= dt
if movetime <= 0:
move = True
movetime = 400
# events
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = pygame.mouse.get_pos()
player.set_destination(mouse_pos)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
run = False
if player.moving:
player.move()
screen.fill((0, 0, 0))
player.draw()
pygame.display.update()
pygame.quit()

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()

Is there any other way I can pause a certain function for a certain period? [duplicate]

I am working on a pong game. When either of the scores hit 10, it is supposed to put up some text on the screen and say the right player has won or left player has won. However, in my program, it isn't working. When it has to show the text that the right or left player has won, it doesn't show it. But it works for everything else. Here is the code:
# Importing libraries
import pygame
import random
import time
# Initializing PyGame
pygame.init()
# Setting a window name
pygame.display.set_caption("Ping Pong")
# Creating a font
pygame.font.init()
font = pygame.font.SysFont(None, 30)
pong_font = pygame.font.SysFont("comicsansms", 75)
# Set the height and width of the screen
window_width = 700
window_height = 500
size = [window_width, window_height]
game_win = pygame.display.set_mode(size)
game_win2 = pygame.display.set_mode(size)
# Creating a messaging system
def message(sentence, color, x, y, font_type, display):
sentence = font_type.render(sentence, True, color)
display.blit(sentence, [x, y])
# Creating colors
white = (225, 225, 225)
black = (0, 0, 0)
gray = (100, 100, 100)
# Setting up ball
ball_size = 25
class Ball:
"""
Class to keep track of a ball's location and vector.
"""
def __init__(self):
self.x = 0
self.y = 0
self.change_x = 0
self.change_y = 0
def make_ball():
ball = Ball()
# Starting position of the ball.
ball.x = 350
ball.y = 250
# Speed and direction of rectangle
ball.change_x = 5
ball.change_y = 5
return ball
def main():
# Scores
left_score = 0
right_score = 0
pygame.init()
# Loop until the user clicks the close button.
done = False
ball_list = []
ball = make_ball()
ball_list.append(ball)
# Right paddle coordinates
y = 200
y_change = 0
x = 50
# Left paddle coordinates
y1 = 200
y1_change = 0
x1 = 650
while not done:
# --- Event Processing
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
y_change = -7
elif event.key == pygame.K_s:
y_change = 7
elif event.key == pygame.K_UP:
y1_change = -7
elif event.key == pygame.K_DOWN:
y1_change = 7
elif event.type == pygame.KEYUP:
y_change = 0
y1_change = 0
y += y_change
y1 += y1_change
# Preventing from letting the paddle go off screen
if y > window_height - 100:
y -= 10
if y < 50:
y += 10
if y1 > window_height - 100:
y1 -= 10
if y1 < 50:
y1 += 10
# Logic
for ball in ball_list:
# Move the ball's center
ball.x += ball.change_x
ball.y += ball.change_y
# Bounce the ball if needed
if ball.y > 500 - ball_size or ball.y < ball_size:
ball.change_y *= -1
if ball.x > window_width - ball_size:
ball.change_x *= -1
left_score += 1
if ball.x < ball_size:
ball.change_x *= -1
right_score += 1
ball_rect = pygame.Rect(ball.x - ball_size, ball.y - ball_size, ball_size * 2, ball_size * 2)
left_paddle_rect = pygame.Rect(x, y, 25, 75)
if ball.change_x < 0 and ball_rect.colliderect(left_paddle_rect):
ball.change_x = abs(ball.change_x)
right_paddle_rect = pygame.Rect(x1, y1, 25, 75)
if ball.change_x > 0 and ball_rect.colliderect(right_paddle_rect):
ball.change_x = -abs(ball.change_x)
# Here is the where the messaging system doesn't work, I don't know why! It works fine for everything else
if right_score == 10:
message("RIGHT PLAYER HAS WON!!", white, 300, 200, font, game_win)
time.sleep(5)
pygame.quit()
quit()
elif left_score == 10:
message("LEFT PLAYER HAS WON!!", white, 300, 200, font, game_win)
time.sleep(5)
pygame.quit()
quit()
# Drawing
# Set the screen background
game_win.fill(black)
# Draw the balls
for ball in ball_list:
pygame.draw.circle(game_win, white, [ball.x, ball.y], ball_size)
# Creating Scoreboard
message("Left player score: " + str(left_score), white, 10, 10, font, game_win)
message("Right player score: " + str(right_score), white, 490, 10, font, game_win)
# Drawing a left paddle
pygame.draw.rect(game_win, white, [x, y, 25, 100])
# Drawing a right paddle
pygame.draw.rect(game_win, white, [x1, y1, 25, 100])
# Setting FPS
FPS = pygame.time.Clock()
FPS.tick(60)
# Updating so actions take place
pygame.display.flip()
while True:
game_win2.fill(black)
pygame.event.get()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
message("Pong", white, 280, 100, pong_font, game_win2)
if 150 + 100 > mouse[0] > 150 and 350 + 50 > mouse[1] > 350:
pygame.draw.rect(game_win, gray, [150, 350, 100, 50])
if click[0] == 1:
break
else:
pygame.draw.rect(game_win, white, [150, 350, 100, 50])
if 450 + 100 > mouse[0] > 450 and 350 + 50 > mouse[1] > 350:
pygame.draw.rect(game_win, gray, [450, 350, 100, 50])
if click[0] == 1:
pygame.quit()
quit()
else:
pygame.draw.rect(game_win, white, [450, 350, 100, 50])
message("Start", black, 175, 367, font, game_win2)
message("Quit", black, 475, 367, font, game_win2)
# Go ahead and update the screen with what we've drawn.
pygame.display.flip()
# Wrap-up
# Limit to 60 frames per second
clock = pygame.time.Clock()
clock.tick(60)
if __name__ == "__main__":
main()
I have added a little comment, it is: "# Here is the where the messaging system doesn't work, I don't know why! It works fine for everything else". Now when someone scores 10 points, Nothing happens. Its= wait for a couple of seconds. That is so you can read the "Left player has won" or "Right player has won" before the program closes. But it simply doesn't show up! I don't know why! Can someone help with this?
The display is updated only if either pygame.display.update() or pygame.display.flip()
is called. See pygame.display.flip():
This will update the contents of the entire display.
Further you've to handles the events with pygame.event.pump(), before the update of the display becomes visible in the window.
See pygame.event.pump():
For each frame of your game, you will need to make some sort of call to the event queue. This ensures your program can internally interact with the rest of the operating system.
If you want to display a text and delay the game, then you've to update the display and handle the events.
Write a function which delays the game and updates the display. I recommend to use the pygame.time module to implement the delay (e.g. pygame.time.delay())
def update_and_wait(delay):
pygame.display.flip()
pygame.event.pump()
pygame.time.delay(delay * 1000) # 1 second == 1000 milliseconds
Or even implement a function which its own event loop to keep the application responding. Measure the time by pygame.time.get_ticks():
def update_and_wait(delay):
start_time = pygame.time.get_ticks()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
print("auit")
pygame.quit()
return False
if pygame.time.get_ticks() >= start_time + delay * 1000:
break
return True
Use the function in the application:
def main():
# [...]
while not done:
# [...]
for ball in ball_list:
# [...]
if right_score == 0:
message_wait("RIGHT PLAYER HAS WON!!", white, 300, 200, font, game_win)
update_and_wait(5)
quit()
elif left_score == 0:
message_wait("LEFT PLAYER HAS WON!!", white, 300, 200, font, game_win)
update_and_wait(5)
quit()

How would I detect NO KEY PRESS / No Input in Python?

I am making a simple box moving "game" to learn the pygame import, but I would like to set the box back to gray after there are no keys pressed.
import pygame
from pygame.locals import *
pygame.init()
width = 400
height = 400
screen = pygame.display.set_mode((width,height))
done = False
clock = pygame.time.Clock()
color = (150, 150, 150)
x = 0
y = 0
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
is_blue = not is_blue
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP] or pressed[pygame.K_w] and y > 0:
y -= 3
color = (0,0,255)
if pressed[pygame.K_DOWN] or pressed[pygame.K_s] and y+60 < height: #Adding 60 because height of block = 60
y += 3
color = (255,255,0)
if pressed[pygame.K_LEFT] or pressed[pygame.K_a] and x > 0:
x -= 3
color = (0,255,0)
if pressed[pygame.K_RIGHT] or pressed[pygame.K_d] and x+60 < width: #Adding 60 because width of block = 60
x += 3
color = (255,0,0)
screen.fill((0, 0, 0))
pygame.draw.rect(screen, color, pygame.Rect(x, y, 60, 60))
pygame.display.flip()
clock.tick(60)
Just add the set of the color=(150,150,150) inside the while loop(:
Put it as the first line inside the loop.

All of spritesheet being displayed onto screen

I have a problem with my game which isn't a bug but a problem. I am using spritesheets to make my game and using a for loop to call my Platform class automaticaly. However when I try to call the the platform class it just displays the whole spritesheet. There may be an error in the class platform or level_1 but I am not sure what it is. Please can you help me if you have pygame.
An image of what is happening
import pygame
# Colours + Global constants
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
BLACK = (0, 0, 0)
RANDOM = (12, 211, 123)
WIDTH = 800
HEIGHT = 600
SIZE = (WIDTH, HEIGHT)
# CLASSES
# Block is the common platform
Platform class:
class Platform(pygame.sprite.Sprite):
def __init__(self, display, x_screen, y_screen, x_sheet, y_sheet, height, length):
super().__init__()
self.image = pygame.image.load("tiles_spritesheet.png")
self.rect = self.image.get_rect()
display.blit(self.image, (x_screen, y_screen), (x_sheet, y_sheet, height, length))
Level_1 class:
class Level01(Level):
def __init__(self, player1, monster, display):
# Initialise level1
super().__init__()
# Level01 things
block = Block(WIDTH*3, 3, BLACK)
Level.all_things = self.all_things
self.sprites.add(player1, monster)
self.platforms.add(block)
self.all_things.add(player1, block, monster)
theLevel = [[1, HEIGHT, 0, 0],
[1, HEIGHT, WIDTH*3, 0]]
level = [[600, 400, 710, 0, 70, 70]]
for platform in theLevel:
block = Block(platform[0], platform[1], RED)
block.rect.x = platform[2]
block.rect.y = platform[3]
self.platforms.add(block)
self.all_things.add(block)
for goodPlatform in level:
platform = Platform(display, goodPlatform[0], goodPlatform[1], goodPlatform[2], goodPlatform[3], goodPlatform[4], goodPlatform[5])
self.platforms.add(platform)
self.all_things.add(platform)
main:
def main():
# Init pygame
pygame.init()
# Set screen
background = pygame.image.load("background.jpg")
backgroundRect = background.get_rect()
display = pygame.display.set_mode(background.get_size())
# Creating FPS thingy
clock = pygame.time.Clock()
# Making levels + Player
monster = Monster(30, 30, RANDOM)
player = Player()
level_1 = Level01(player, monster, display)
# Choosing level
levelList = []
levelList.append(level_1)
currentLevelNumber = 0
currentLevel = levelList[currentLevelNumber]
y_speed = -5
# Game loop
loop = True
while loop == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
player.move_right()
if event.key == pygame.K_LEFT:
player.move_left()
if event.key == pygame.K_UP:
player.move_up(currentLevel.platforms)
if event.key == pygame.KMOD_LSHIFT and event.key == pygame.K_RIGHT:
player.sprint()
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT and player.sprite_x_change < 0:
player.stop()
if event.key == pygame.K_RIGHT and player.sprite_x_change > 0:
player.stop()
if event.key == pygame.KMOD_LSHIFT:
player.sprite_x_change -= 10
# Update things
#monster.jump()
if player.rect.x > 400:
player.rect.x = 400
currentLevel.scroll_x(-10)
if player.rect.x >= WIDTH:
player.rect.x = WIDTH
currentLevel.scroll(0)
if player.rect.y >= HEIGHT:
main()
if player.sprite_x_change < 0 and player.rect.x >= 120:
currentLevel.scroll_x(0)
if currentLevel.shift_x >= WIDTH *3 - 400:
currentLevel.scroll_x(0)
sprite_x_change = 0
if player.rect.left <= 120 and player.sprite_x_change < 0:
player.rect.x = 120
player.rect.left = 120
currentLevel.scroll_x(10)
'''
if player.rect.y <= 300:
if player.standing == False and player.sprite_y_change < 0:
currentLevel.scroll_y(10)
if currentLevel.shift_y > 0:
y_speed = -4
if player.standing == True and player.rect.y < 300:
y_speed = 4
print(currentLevel.shift_y)
currentLevel.scroll_y(y_speed)
'''
display.blit(background, backgroundRect)
currentLevel.drawer(display)
# Refresh screen
player.updater(currentLevel.platforms)
clock.tick(30)
pygame.display.update()
pygame.quit()
loop = False
if __name__ == "__main__":
main()
Group use self.image and self.rect to blit element so
create subsurface using pygame.Surface.subsurface and (x_sheet, y_sheet, height, length) - and assign to self.image
assign (x_screen, y_screen, height, length) to self.rect
.
class Platform(pygame.sprite.Sprite):
def __init__(self, display, x_screen, y_screen, x_sheet, y_sheet, height, length):
super().__init__()
self.tiles = pygame.image.load("tiles_spritesheet.png")
self.image = self.tiles.subsurface(pygame.Rect(x_sheet, y_sheet, height, length))
self.rect = self.image.get_rect(x=x_screen, y=y_screen)
#display.blit(self.image, self.rect)

Categories

Resources