Related
def victory_screen():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit_game()
screen.fill(WHITE)
largeText = pygame.font.Font(None,50)
screen.blit(largeText.render("Congratulations!",True,BLUE),(135,40))
largeText = pygame.font.Font(None,35)
screen.blit(largeText.render("You have completed the game!", True, BLUE), (205,90))
button("Try Beat me again", 130, 250, 150, 60, RED, GREEN, menu)
button("Quit", 130, 250, 150, 60, RED, GREEN, quit_game)
pygame.display.update()
pygame.display.flip()
clock.tick(frame_rate)
def instructions_screen():
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit_game()
screen.fill(WHITE)
largeText = pygame.font.Font(None,50)
smallText = pygame.font.Font(None, 35)
screen.blit(largeText.render("Instructions", True, BLUE), (181, 50))
screen.blit(smallText.render("Goal of the game: Reach to 7 points first", True, BLACK), (148, 150))
screen.blit(smallText.render("How to move: Upper arrow - up", True, BLACK), (148, 210))
screen.blit(smallText.render("Lower arrow - down", True, BLACK), (429, 250))
button("Play", 240, 250, 150, 60, GREEN, BLACK, menu)
pygame.display.flip()
clock.tick(60)
def front_page():
next_screen = None
def start_game():
nonlocal next_screen
next_screen = menu
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit_game()
if next_screen is not None:
return next_screen
screen.fill(WHITE)
screen.blit(image1, (0,0))
largeText = pygame.font.Font(None, 65)
screen.blit(largeText.render("Wizard mania", True, BLUE),(240,50))
button("Start", 225, 200, 150, 60, GREEN, BLACK, start_game)
button("Quit", 225,250, 150, 60, GREEN, BLACK, quit_game)
button("Controls", 225, 300, 150, 60, GREEN, BLACK, instructions_screen)
pygame.display.flip()
clock.tick(frame_rate)
def menu():
vel = 4
ply1 = pygame.Rect(40, 45, 30, 30)
keys = pygame.key.get_pressed()
scoreA = 0
scoreB = 0
lefthandwalls = [
LeftHandwall(0, 545, 10, 5)
]
righthandwalls = [
RightHandwall(0, 545, 10, 5)
]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
quit_game
keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and ply1.y > 0:
ply1.y -= vel
if keys[pygame.K_DOWN] and ply1.y < 600 - ply1.height:
ply1.y += vel
for lefthandwalls in LeftHandwall:
if ply1.colliderect(lefthandwalls):
scoreB = scoreB + 1
print(scoreB)
if ply1.colliderect(righthandwalls):
scoreA = scoreA + 1
print(scoreA)
if scoreA == 7:
print("You have won the game")
victory_screen
screen.fill(WHITE)
for lefthandwalls in LeftHandwall:
pygame.draw.rect(screen, BLACK, lefthandwalls)
for righthandwalls in RightHandwall:
pygame.draw.rect(screen, BLACK, righthandwalls)
pygame.display.flip()
clock.tick(60)
def main():
scene = front_page
while scene is not None:
scene = scene()
main()
pygame.quit()
I am coding a ping pong game in pygame for my computer science project. I expected that the game will start from the front page and when "start" pressed it goes to the game, or when "controls" pressed a tutorial will show and lastly "quit" pressed it closes the game. However, I get only a black screen
You have to call the front_page function:
scene = front_page
scene = front_page()
I use a system like this which should theoretically work to close the window:
while running:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
Here is the code:
import pygame
import random
import sys
# Set width and height of window
(width, height) = (400, 600)
# Sets the colours
background_colour = (0, 2, 20)
white = (255, 255, 255)
# creates window
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Space Dodger")
screen.fill(background_colour)
def gameLoop():
# sets sprite starting coordinates
rocketX = 200
rocketY = 450
leftX = 0
leftY = -25
leftWidth = random.randint(0, 300)
# sets obstacle start speed
obstacleSpeed = 1
# sets starting score
score = 0
pygame.init()
font = pygame.font.Font("Pixeled.ttf", 32)
fontSmall = pygame.font.Font("Pixeled.ttf", 25)
scoreX = 10
scoreY = 10
# All images/sprites
# rocket
rocket = pygame.image.load("rocket.png")
rocket = pygame.transform.smoothscale(rocket, (50, 100))
# background image
backgroundSpace = pygame.image.load("spacesky.png")
backgroundSpace = pygame.transform.rotate(backgroundSpace, 90)
backgroundColour = (10, 32, 61)
running = True
while running:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# sets rectangles for obstacles
leftObstacle = pygame.draw.rect(screen, white, pygame.Rect(leftX, leftY, leftWidth, 25))
rightObstacle = pygame.draw.rect(
screen, white, pygame.Rect(leftWidth + 100, leftY, width, 25)
)
rocketRec = pygame.draw.rect(
screen, backgroundColour, pygame.Rect(rocketX + 10, rocketY, 30, 75)
)
# sets score text
displayScore = font.render(str(score), True, (105, 105, 105))
# makes cursor invisible
pygame.mouse.set_visible(False)
# draws new layer over screen
screen.blit(backgroundSpace, (0, 0))
# tracks the mosue location
mouseX, mouseY = pygame.mouse.get_pos()
# draws rectangle behind rocket
pygame.draw.rect(screen, backgroundColour, rocketRec)
# displays the rocket
screen.blit(rocket, (rocketX, rocketY))
# sets rocket horizontal position
if mouseX > width - 50:
rocketX = width - 50
else:
rocketX = mouseX
# displays the score
screen.blit(displayScore, (scoreX, scoreY))
# creates the moving obstacles
pygame.draw.rect(screen, white, leftObstacle)
pygame.draw.rect(screen, white, rightObstacle)
leftY = leftY + obstacleSpeed
# brings obstacle back to top
if leftY > 600:
leftY = -25
leftWidth = random.randint(0, 300)
score = score + 1
if obstacleSpeed >= 6:
obstacleSpeed = 6
else:
obstacleSpeed = obstacleSpeed + 0.2
if rocketRec.colliderect(leftObstacle) or rocketRec.colliderect(rightObstacle):
collisionScreen()
def startScreen():
lightGrey = (200, 200, 200)
darkGrey = (165, 165, 165)
lightGrey2 = (200, 200, 200)
darkGrey2 = (165, 165, 165)
# background image
backgroundSpace = pygame.image.load("spacesky.png")
backgroundSpace = pygame.transform.rotate(backgroundSpace, 90)
backgroundColour = (10, 32, 61)
pygame.init()
fontSmall = pygame.font.Font("Pixeled.ttf", 25)
running = True
while running:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# start screen
# makes cursor visible
pygame.mouse.set_visible(True)
# tracks the mosue location
mouseX, mouseY = pygame.mouse.get_pos()
# draws new layer over screen
screen.blit(backgroundSpace, (0, 0))
# Puts on logo
logo = pygame.image.load("name.png")
logo = pygame.transform.smoothscale(logo, (500, 300))
screen.blit(logo, (-40, 10))
# creates start button
startRecU = pygame.draw.rect(screen, darkGrey, pygame.Rect(120, 270, 160, 60))
startRec = pygame.draw.rect(screen, lightGrey, pygame.Rect(125, 275, 150, 50))
startText = fontSmall.render("START", True, (0, 0, 0))
# displays the start text
screen.blit(startText, (135, 262))
# detects if mouse is hovering over button
if 280 > mouseX > 120 and 330 > mouseY > 270:
darkGrey = (200, 200, 200)
lightGrey = (165, 165, 165)
else:
lightGrey = (200, 200, 200)
darkGrey = (165, 165, 165)
# detects if start button is clicked
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and 280 > mouseX > 120 and 330 > mouseY > 270:
gameLoop()
# creates quit button
quitRecU = pygame.draw.rect(screen, darkGrey2, pygame.Rect(120, 350, 160, 60))
quitRec = pygame.draw.rect(screen, lightGrey2, pygame.Rect(125, 355, 150, 50))
quitText = fontSmall.render("QUIT", True, (0, 0, 0))
# displays the start text
screen.blit(quitText, (156, 340))
# detects if mouse is hovering over button
if 280 > mouseX > 120 and 410 > mouseY > 350:
darkGrey2 = (200, 200, 200)
lightGrey2 = (165, 165, 165)
else:
lightGrey2 = (200, 200, 200)
darkGrey2 = (165, 165, 165)
# detects if quit button is clicked
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and 280 > mouseX > 120 and 410 > mouseY > 350:
running = False
def collisionScreen():
lightGrey = (200, 200, 200)
darkGrey = (165, 165, 165)
lightGrey2 = (200, 200, 200)
darkGrey2 = (165, 165, 165)
# background image
backgroundSpace = pygame.image.load("spacesky.png")
backgroundSpace = pygame.transform.rotate(backgroundSpace, 90)
backgroundColour = (10, 32, 61)
# explosion
explosion = pygame.image.load("explosion.png")
explosion = pygame.transform.smoothscale(explosion, (100, 100))
pygame.init()
fontSmall = pygame.font.Font("Pixeled.ttf", 25)
fontMini = pygame.font.Font("Pixeled.ttf", 15)
running = True
while running:
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# draws new layer over screen
screen.blit(backgroundSpace, (0, 0))
# makes cursor visible
pygame.mouse.set_visible(True)
# tracks the mosue location
mouseX, mouseY = pygame.mouse.get_pos()
# displays the explosion
screen.blit(explosion, (150, 400))
# creates play again button
playAgainRecU = pygame.draw.rect(screen, darkGrey, pygame.Rect(120, 270, 160, 60))
playAgainRec = pygame.draw.rect(screen, lightGrey, pygame.Rect(125, 275, 150, 50))
playAgainText = fontMini.render("PLAY AGAIN", True, (0, 0, 0))
# displays the start text
screen.blit(playAgainText, (135, 278))
# detects if mouse is hovering over button
if 280 > mouseX > 120 and 330 > mouseY > 270:
darkGrey = (200, 200, 200)
lightGrey = (165, 165, 165)
else:
lightGrey = (200, 200, 200)
darkGrey = (165, 165, 165)
# detects if play button is clicked
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and 280 > mouseX > 120 and 330 > mouseY > 270:
gameLoop()
# creates quit button
quit2RecU = pygame.draw.rect(screen, darkGrey2, pygame.Rect(120, 350, 160, 60))
quit2Rec = pygame.draw.rect(screen, lightGrey2, pygame.Rect(125, 355, 150, 50))
quit2Text = fontSmall.render("QUIT", True, (0, 0, 0))
# displays the start text
screen.blit(quit2Text, (156, 340))
# detects if mouse is hovering over button
if 280 > mouseX > 120 and 410 > mouseY > 350:
darkGrey2 = (200, 200, 200)
lightGrey2 = (165, 165, 165)
else:
lightGrey2 = (200, 200, 200)
darkGrey2 = (165, 165, 165)
# detects if quit button is clicked
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN and 280 > mouseX > 120 and 410 > mouseY > 350:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
startScreen()
Your code is pretty messy, try to do all your code to only one main loop (you have three now). This is how I suggest how it should be done.
import pygame
from sys import exit
pygame.init()
screen = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()
#Conststants, variables and images
startMenu = True
mainGame = False
collisionScreen = False
#Main loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.MOUSEBUTTONDOWN:
#All things that are supposed to happen can be pressed by the mouse (if statement)
if startMenu:
#Start Menu code
elif mainGame:
#Main game code
elif collisionScreen:
#Collision screen code
pygame.display.update()
clock.tick(60) #fps
I hope it helps you, Adam
Hello I am making a tic tac toe game in pygame the problem i encountered is that when i draw an x on the board it does not draw.it works when i draw a circle as shown in the code. please tell me how to fix also can you tell me how to take turns in this game because i cannot figure out how to draw an x and let the computer draw an o and so on.i want to wait for the user to draw an x and then let the computer draw an o.
Here Is The Code:
import pygame,random
pygame.init()
width = 600
height = 600
res = (width,height)
screen = pygame.display.set_mode(res)
pygame.display.set_caption("Tic Tac Toe")
background = (255,150,150)
color_light = (170,170,170)
color_dark = (100,100,100)
hover_color = (255, 204, 203)
rect_list = [
pygame.Rect(10, 10, 180, 190),
pygame.Rect(200, 10, 190, 190),
pygame.Rect(400, 10, 190, 190),
pygame.Rect(10, 210, 180, 180),
pygame.Rect(200, 210, 190, 180),
pygame.Rect(400, 210, 190, 180),
pygame.Rect(10, 400, 180, 190),
pygame.Rect(200, 400, 190, 190),
pygame.Rect(400, 400, 190, 190)]
clicked_list = [0 for _ in rect_list]
count = 0
def draw_x(x,y,width,height):
for i in range(5):
pygame.draw.aaline(screen,"blue",(x+i,y),(width+x+i,height+y)) # start_pos(x+thickness,y)---end_pos(width+x+thickness,height+y)
pygame.draw.aaline(screen,"blue",(width+x+i,y),(x+i,height+y)) # start_pos(x+width+thickness,y)---end_pos(x+thickness,y+height)
def draw_line():
line_color = (212, 212, 255)
pygame.draw.rect(screen, line_color, (190,10,10,580))
pygame.draw.rect(screen, line_color, (390, 10, 10, 580))
pygame.draw.rect(screen, line_color, (10, 200, 580, 10))
pygame.draw.rect(screen, line_color, (10, 390, 580, 10))
def highlight():
for rect in rect_list:
if rect.collidepoint(mouse):
pygame.draw.rect(screen,hover_color,rect)
def random_no():
randomno = random.randint(0,len(rect_list)-1)
if clicked_list[randomno] != 1:
pass
else:
random_no()
return randomno
def mouse_click():
x_turn = True
y_turn = False
o_no = random_no()
clicked_list[o_no] = 2
for i,rect in enumerate(rect_list):
if clicked_list[i] == 1:
if x_turn and clicked:
pygame.draw.rect(screen, background, rect)
draw_x(rect.x,rect.y,rect.width,rect.height)
if clicked_list[i] == 2:
if y_turn:
pygame.draw.rect(screen, background, rect)
pygame.draw.ellipse(screen, "blue", rect, 5)
# rect_list.remove(rect_list[i])
# clicked_list.remove(clicked_list[i])
while True:
mouse = pygame.mouse.get_pos()
x = screen.get_at(mouse)[:3]
screen.fill(background)
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
pygame.quit()
if ev.type == pygame.MOUSEBUTTONDOWN:
clicked = True
for i, rect in enumerate(rect_list):
if rect.collidepoint(ev.pos) and x == hover_color:
clicked_list[i] = 1
draw_line()
highlight()
mouse_click()
pygame.display.update()
The mouse click must be handled in the event loop. However, you need a function draw_borad that draws "X" and "O".
Add a variable that indicates if its the turn of "X" or "O":
x_turn = True
If the mouse is pressed and a field is empty (0), change the status of the field and change the x_turn variable:
if rect.collidepoint(ev.pos) and x == hover_color:
if clicked_list[i] == 0:
clicked_list[i] = 1 if x_turn else 2
x_turn = not x_turn
Draw all the "X" and "O" in draw_borad:
def draw_borad():
for i,rect in enumerate(rect_list):
if clicked_list[i] == 1:
pygame.draw.rect(screen, background, rect)
draw_x(rect.x,rect.y,rect.width,rect.height)
if clicked_list[i] == 2:
pygame.draw.rect(screen, background, rect)
pygame.draw.ellipse(screen, "blue", rect, 5)
x_turn = True
while True:
mouse = pygame.mouse.get_pos()
x = screen.get_at(mouse)[:3]
screen.fill(background)
for ev in pygame.event.get():
if ev.type == pygame.QUIT:
pygame.quit()
if ev.type == pygame.MOUSEBUTTONDOWN:
clicked = True
for i, rect in enumerate(rect_list):
if rect.collidepoint(ev.pos) and x == hover_color:
if clicked_list[i] == 0:
clicked_list[i] = 1 if x_turn else 2
x_turn = not x_turn
draw_line()
highlight()
draw_borad()
pygame.display.update()
How do I make entities take damage with colors? I made a game with enemies shooting blue lasers and I want the player to take damage. And the player shoots a red laser. Upon detecting colors, I want a certain statement to be true. That would lower an entity's health by one. If color collision is a thing, it can be very useful for making many different games. Here is my code:
# importing packages
import pygame
import random
import time
import sys
# Initializing Pygame
pygame.init()
# Setting a display caption
pygame.display.set_caption("Space Invaders")
spaceship = pygame.image.load("spaceship2.png")
blue_enemy = pygame.image.load("blue_enemy.png")
green_enemy = pygame.image.load("green_enemy.png")
orange_enemy = pygame.image.load("orange_enemy.png")
pink_enemy = pygame.image.load("pink_enemy.png")
yellow_enemy = pygame.image.load("yellow_enemy.png")
# Creating a font
pygame.font.init()
font = pygame.font.SysFont("consolas", 30)
large_font = pygame.font.SysFont("consolas", 60)
small_font = pygame.font.SysFont("consolas", 20)
# Setting a display width and height and then creating it
display_width = 700
display_height = 500
display_size = [display_width, display_height]
game_display = pygame.display.set_mode(display_size)
intro_display = pygame.display.set_mode(display_size)
# Creating a way to add text to the screen
def message(sentence, color, x, y, font_type, display):
sentence = font_type.render(str.encode(sentence), True, color)
display.blit(sentence, [x, y])
def main():
global white
global black
global clock
# Spaceship coordinates
spaceship_x = 300
spaceship_y = 375
spaceship_x_change = 0
blue_enemy_health = 5
green_enemy_health = 5
orange_enemy_health = 5
pink_enemy_health = 5
yellow_enemy_health = 5
# Clock making
# Initializing pygame
pygame.init()
# Creating colors
red = (0, 0, 0)
blue = (0, 0, 255)
# clock stuff
clock = pygame.time.Clock()
time_elapsed_since_last_action = 0
time_elapsed_since_last_action2 = 0
time_elapsed_since_last_action3 = 0
# Creating a loop to keep program running
while True:
laser_rect = pygame.Rect(spaceship_x + 69, 70, 4, 310)
# --- Event Processing and controls
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
spaceship_x_change = 10
elif event.key == pygame.K_LEFT:
spaceship_x_change = -10
elif event.key == pygame.K_r:
red = (255, 0, 0)
elif time_elapsed_since_last_action2 > 250:
pygame.draw.rect(game_display, red, laser_rect)
time_elapsed_since_last_action2 = 0
elif event.type == pygame.KEYUP:
spaceship_x_change = 0
red = (0, 0, 0)
spaceship_x += spaceship_x_change
# Preventing the ship from going off the screen
if spaceship_x > display_width - 140:
spaceship_x -= 10
if spaceship_x < 1:
spaceship_x += 10
# Setting Display color
game_display.fill(black)
laser_coords = [70, 209, 348, 505, 630]
random_x_coord = random.choice(laser_coords)
dt = clock.tick()
time_elapsed_since_last_action += dt
if time_elapsed_since_last_action > 500:
pygame.draw.rect(game_display, blue, [random_x_coord, 85, 6, 305])
time_elapsed_since_last_action = 0
time_elapsed_since_last_action2 += dt
# Creating a spaceship, lasers, and enemies
game_display.blit(spaceship, (spaceship_x, spaceship_y))
message(str(blue_enemy_health), white, 65, 10, font, game_display)
game_display.blit(blue_enemy, (20, 25))
message(str(green_enemy_health), white, 203, 10, font, game_display)
game_display.blit(green_enemy, (160, 25))
message(str(orange_enemy_health), white, 341, 10, font, game_display)
game_display.blit(orange_enemy, (300, 25))
message(str(pink_enemy_health), white, 496, 10, font, game_display)
game_display.blit(pink_enemy, (440, 25))
message(str(yellow_enemy_health), white, 623, 10, font, game_display)
game_display.blit(yellow_enemy, (580, 25))
health = 10
message("Spaceship durability: " + str(health), white, 20, 480, small_font, game_display)
# Updating Screen so changes take places
pygame.display.update()
# Setting FPS
FPS = pygame.time.Clock()
FPS.tick(60)
black = (0, 0, 0)
white = (255, 255, 255)
gray = (100, 100, 100)
while True:
intro_display.fill(black)
pygame.event.poll()
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
message("Space Bugs", white, 180, 150, large_font, intro_display)
if 150 + 100 > mouse[0] > 150 and 350 + 50 > mouse[1] > 350:
pygame.draw.rect(game_display, gray, [150, 350, 100, 50])
if click[0] == 1:
break
else:
pygame.draw.rect(game_display, white, [150, 350, 100, 50])
if 450 + 100 > mouse[0] > 450 and 350 + 50 > mouse[1] > 350:
pygame.draw.rect(game_display, gray, [450, 350, 100, 50])
if click[0] == 1:
pygame.quit()
quit()
else:
pygame.draw.rect(game_display, white, [450, 350, 100, 50])
message("Start", black, 155, 360, font, intro_display)
message("Quit", black, 465, 360, font, intro_display)
# Go ahead and update the screen with what we've drawn.
pygame.display.update()
# Wrap-up
# Limit to 60 frames per second
clock = pygame.time.Clock()
clock.tick(60)
# Executing the function
if __name__ == "__main__":
main()
No, there is no such a "thing" as a "color collision". What color have the images? Are they uniformly colored? Most likely the pictures are only different in some details. A collision which checks for a uniform color is completely useless. A collision that also looks for a uniform color is almost useless.
If you detect a collision, you know the laser and the enemy. Hence, you know the color with which you represent them. All you have to do is do an additional check after the collision is detected.
Use pygame.sprite.Sprite to implement the objects. Add an attribute that indicates the color of the object:
class ColoredSprite(pygame.sprite.Sprite):
def __init__(self, x, y, image, color):
super().__init__()
self.image = image
self.rect = self.image.get_rect(center = (x, y)
slef.color = color
Manage the spites in pygame.sprite.Groups and use spritecollide to detect the collisions. Check the color attributes when a collision is detected
collide_list = sprite.spritecollide(sprite_group, False):
for other_sprite in collide_list:
if sprite.color == 'red' and other_sprite.color == 'blue':
# [...]
elif sprite.color == 'blue' and other_sprite.color == 'red':
# [...]
It is even possible to implement your own collision detection method and use it in combination with spritecollide by setting the optional collided argument:
def color_collision(sprite1, sprite2):
if sprite1.rect.colliderect(sprite2.rect):
return ((sprite1.color == 'red' and sprite2.color == 'blue') or
(sprite1.color == 'blue' and sprite2.color == 'red'))
return false
collide_list = sprite.spritecollide(sprite_group, False, color_collision):
for other_sprite in collide_list:
# [...]
Minimal example:
import pygame
pygame.init()
window = pygame.display.set_mode((250, 250))
sprite1 = pygame.sprite.Sprite()
sprite1.image = pygame.Surface((75, 75))
sprite1.image.fill('red')
sprite1.rect = pygame.Rect(*window.get_rect().center, 0, 0).inflate(75, 75)
sprite1.color = 'red'
sprite2 = pygame.sprite.Sprite()
sprite2.image = pygame.Surface((75, 75))
sprite2.image.fill('blue')
sprite2.rect = pygame.Rect(*window.get_rect().center, 0, 0).inflate(75, 75)
sprite2.color = 'blue'
all_group = pygame.sprite.Group([sprite2, sprite1])
def color_collision(sprite1, sprite2):
if sprite1.rect.colliderect(sprite2.rect):
return ((sprite1.color == 'red' and sprite2.color == 'blue') or
(sprite1.color == 'blue' and sprite2.color == 'red'))
return False
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
sprite1.rect.center = pygame.mouse.get_pos()
collide = pygame.sprite.spritecollide(sprite1, all_group, False, color_collision)
window.fill(0)
all_group.draw(window)
for s in collide:
pygame.draw.rect(window, (255, 255, 255), s.rect, 5, 1)
pygame.display.flip()
pygame.quit()
exit()
I am making a game, and when I want to go through the loop normally, it doesn't work.
it goes through the loop, but for some reason, it backtracks, rather than starting over. When I add a continue statement, the button just disappears.
Why isn't the continue statement working properly?
Here is my code:
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 300))
pygame.font.init()
done = False
bro = True
x = 100
y = 100
#button1 = pygame.draw.rect(screen, (0, 0, 255), (200, 200, 30, 30))
#if check <= pos - (w/2) and check >=
pygame.display.set_caption("Auto Maze!")
donk = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
mouse = event.pos
try:
assert button1.collidepoint(mouse)
except AssertionError:
pass
except NameError:
pass
else:
donk = True
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
y -= 5
elif pressed[pygame.K_s]:
y += 5
elif pressed[pygame.K_a]:
x -= 5
elif pressed[pygame.K_d]:
x += 5
screen.fill((0, 0, 0))
"""try:
assert player.colliderect(wall1)
except AssertionError:
pass
except NameError:
pass
else:
death_screen = pygame.display.set_mode((400, 300))
button1 = pygame.draw.rect(death_screen, (0, 0, 255), (200, 200, 30, 30))
if donk:
break"""
player = pygame.draw.rect(screen, (0, 255, 0), (x, y, 60, 60))
wall1 = pygame.draw.rect(screen, (255, 0, 0), (300, 0, 100, 300))
if player.colliderect(wall1):
death_screen = pygame.display.set_mode((400, 300))
myfont = pygame.font.SysFont("Comic Sans MS", 10)
button1 = pygame.draw.rect(death_screen, (0, 0, 255), (175, 100, 60, 30))
text = myfont.render("Try Again", False, (255, 0, 0))
screen.blit(text, (175, 100))
if donk:
screen = pygame.display.set_mode((400, 300))
clock.tick(60)
pygame.display.flip()
quit()
Add a gameover to your application:
gameover = False:
Do different things in the application loop, dependent on the state of gameover:
while not done:
# [...]
if not gameover:
# draw game scene
# [...]
else:
# draw gamover scene (button)
# [...]
Set the gameover state if the player collides:
gameover = player.colliderect(wall1)
Reset the position of the player if the continue button is pressed:
if event.type == pygame.MOUSEBUTTONDOWN:
if gameover:
if button1.collidepoint(event.pos):
gameover = False
x, y = 100, 100
See the example:
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption("Auto Maze!")
pygame.font.init()
myfont = pygame.font.SysFont("Comic Sans MS", 10)
x, y = 100, 100
gameover = False
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
if gameover:
if button1.collidepoint(event.pos):
gameover = False
x, y = 100, 100
screen.fill((0, 0, 0))
if not gameover:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
y -= 5
elif pressed[pygame.K_s]:
y += 5
elif pressed[pygame.K_a]:
x -= 5
elif pressed[pygame.K_d]:
x += 5
player = pygame.draw.rect(screen, (0, 255, 0), (x, y, 60, 60))
wall1 = pygame.draw.rect(screen, (255, 0, 0), (300, 0, 100, 300))
gameover = player.colliderect(wall1)
else:
button1 = pygame.draw.rect(screen, (0, 0, 255), (175, 100, 60, 30))
text = myfont.render("Try Again", False, (255, 0, 0))
screen.blit(text, (175, 100))
pygame.display.flip()
clock.tick(60)
quit()
This does the same as your code, but just cleaned up. Hopefully it solves your problem
import pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((400, 300))
pygame.font.init()
done = False
mouse = None
click = False
state = "main"
myfont = pygame.font.SysFont("Comic Sans MS", 10)
player = pygame.Rect(100,100,60,60)
wall1 = pygame.Rect(300, 0, 100, 300)
button1 = pygame.Rect(175, 100, 60, 30)
pygame.display.set_caption("Auto Maze!")
while not done:
click = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.MOUSEBUTTONDOWN:
mouse = event.pos
click = True
screen.fill((0, 0, 0))
if state == "main":
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]:
player.y -= 5
elif pressed[pygame.K_s]:
player.y += 5
elif pressed[pygame.K_a]:
player.x -= 5
elif pressed[pygame.K_d]:
player.x += 5
#draw player and wall
pygame.draw.rect(screen, (0, 255, 0), player)
pygame.draw.rect(screen, (255, 0, 0), wall1)
if player.colliderect(wall1):
state = "death"
else:
pygame.draw.rect(screen, (0, 0, 255), button1)
text = myfont.render("Try Again", False, (255, 0, 0))
screen.blit(text, (175, 100))
if click:
if button1.collidepoint(mouse):
state = "main"
player.x = 100
player.y = 100
clock.tick(60)
pygame.display.flip()
quit()