I'm working on making a game for my programming class using python. I don't know how to give the option to the player again when they lose, or quit the game. I am using python 2.7. This is the code for my game:
import pygame, sys, time, random
from pygame.locals import *
# set up pygame
pygame.init()
mainClock = pygame.time.Clock()
# set up the window
WINDOWWIDTH = 1000
WINDOWHEIGHT = 500
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('Dankest Memes')
# set up the colors
PINK = (223, 61, 163)
TEXTCOLOR = (223, 61, 163)
def waitForPlayerToPressKey():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def terminate():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE: # pressing escape quits
terminate()
return
def drawText(text, font, surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
font = pygame.font.SysFont(None, 48)
TEXTCOLOR = (255,250,250)
Score=4
# set up fonts
font = pygame.font.SysFont(None, 48)
myscore=4
# set up the block data structure
file = 'score.txt'
player = pygame.Rect(300, 100, 40, 40)
playerImage = pygame.image.load('player.png')
playerStretchedImage = pygame.transform.scale(playerImage, (40, 40))
foodImage = pygame.image.load('meme.png')
foods = []
for i in range(20):
foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))
foodCounter = 0
NEWFOOD = 40
baddie = pygame.Rect(300, 100, 40, 40)
baddieImage = pygame.image.load('baddie.png')
baddieStretchedImage = pygame.transform.scale(baddieImage, (40, 40))
baddies = []
for i in range(20):
baddies.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))
baddieCounter = 0
NEWBADDIE = 120
# set up keyboard variables
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
MOVESPEED = 6
# set up music
pickUpSound = pygame.mixer.Sound('pickup.wav')
pygame.mixer.music.load('background.mp3')
pygame.mixer.music.play(-1, 0.0)
musicPlaying = True
# show the "Start" screen
drawText('Dankest Memes', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press any key to start.', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 50)
drawText('Move with WASD or the arrow keys.', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 100)
drawText('Collect green Pepes to get points.', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 150)
drawText('Avoid the chickens.', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 200)
pygame.display.update()
waitForPlayerToPressKey()
# run the game loop
while True:
# check for the QUIT event
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
# change the keyboard variables
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if event.key == ord('x'):
player.top = random.randint(0, WINDOWHEIGHT - player.height)
player.left = random.randint(0, WINDOWWIDTH - player.width)
if event.key == ord('m'):
if musicPlaying:
pygame.mixer.music.stop()
else:
pygame.mixer.music.play(-1, 0.0)
musicPlaying = not musicPlaying
if event.type == MOUSEBUTTONUP:
foods.append(pygame.Rect(event.pos[0] - 10, event.pos[1] - 10, 20, 20))
foodCounter += 1
if foodCounter >= NEWFOOD:
# add new food
foodCounter = 0
foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))
baddieCounter += 1
if baddieCounter >= NEWBADDIE:
baddieCounter = 0
baddies.append(pygame.Rect(random.randint(0, WINDOWWIDTH - 20), random.randint(0, WINDOWHEIGHT - 20), 20, 20))
# draw the pink background onto the surface
windowSurface.fill(PINK)
# move the player
if moveDown and player.bottom < WINDOWHEIGHT:
player.top += MOVESPEED
if moveUp and player.top > 0:
player.top -= MOVESPEED
if moveLeft and player.left > 0:
player.left -= MOVESPEED
if moveRight and player.right < WINDOWWIDTH:
player.right += MOVESPEED
drawText('Score: %s' % (Score), font, windowSurface, 10,0)
# draw the block onto the surface
windowSurface.blit(playerStretchedImage, player)
# check if the block has intersected with any food squares.
for food in foods[:]:
if player.colliderect(food):
foods.remove(food)
Score+=2
if musicPlaying:
pickUpSound.play()
for baddie in baddies[:]:
if player.colliderect(baddie):
baddies.remove(baddie)
Score-=4
if musicPlaying:
pickUpSound.play()
if Score < 0:
drawText('You have lost', font, windowSurface, (WINDOWWIDTH / 3), (WINDOWHEIGHT / 3))
drawText('Press escape to quit the game', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 50)
drawText('Press any other key to play again', font, windowSurface, (WINDOWWIDTH / 3) - 50, (WINDOWHEIGHT / 3) + 100)
pygame.display.update()
waitForPlayerToPressKey()
# draw the food
for food in foods:
windowSurface.blit(foodImage, food)
# draw the baddie
for baddie in baddies:
windowSurface.blit(baddieImage, baddie)
# draw the window onto the screen
pygame.display.update()
mainClock.tick(40)
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
The game is simple. The player moves around, collects food to get points and avoids baddies so they don't lose points. When the score drops below 0, the player loses. I managed to get and end game screen, but I can't make it play again or quit the game after this point.
First of, one suggestion. People will be more likely to help you if you show them what you've tried.
anyhow.
What I would do is wrap your entire game loop in a function. Like so:
def game_loop():
while True:
# check for the QUIT event
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
....
next when ever your game ends(I'm assuming it does have a condition that makes it end), call a game over screen function. In your game over screen function, you could first fill the window with a color, then blit any text to the screen you wan to show the user, such as "Press any key to play again". Then you would check if any key was pressed and if so call the game loop function. You also need to check if the user is trying to close the window.
Then call the game over screen function like so:
#pseudo code
if game_has_ended == True:
game_over_screen()
Related
I really have a basic question with a long awnser needed. Can someone show me how to make a Rect jump? I just need a sample with a rectangle.
I see your question and i think i have made some example code for you, but first i want to tell you how it works. In addition to an Y variable to store your location on the Y axis you want a variable called velocityY. For every frame in the game the Y variable is changed with velocityY like this:
while True:
y += velocityY # <----- Here
manage_window()
for event in pygame.event.get():
handle_event(event)
pygame.display.flip()
When you jump you set velocityY to lets say -10 and that will make your rect fly off into the sky, so we need to add gravity. Here is the long example (The important part is):
import pygame
pygame.init()
window = pygame.display.set_mode((800, 600))
x, y = 300, 400
xVelocity, yVelocity = 0, 0
rect = pygame.Rect(x, y, 200, 200)
groundRect = pygame.Rect(0, 500, 800, 100)
clock = pygame.time.Clock()
white = 255, 255, 255
red = 255, 0, 0
black = 0, 0, 0
blue = 0, 0, 255
while True:
clock.tick(60) # Make sure the game is running at 60 FPS
rect = pygame.Rect(x, y, 200, 200) # Updating our rect to match coordinates
groundRect = pygame.Rect(0, 500, 800, 100) # Creating ground rect
# HERE IS WHAT YOU CARE ABOUT #
yVelocity += 0.2 # Gravity is pulling the rect down
x += xVelocity # Here we update our velocity on the X axis
y += yVelocity # Here we update our velocity on the Y axis
# HERE IS WHAT YOU CARE ABOUT #
if groundRect.colliderect(rect): # Check if the rect is colliding with the ground
y = groundRect.top-rect.height
yVelocity = 0
window.fill(white)
pygame.draw.rect(window, red, rect) # Here we draw the rect
pygame.draw.rect(window, black, rect, 5) # Here we draw the black box around the rect
pygame.draw.rect(window, blue, groundRect) # Here we draw the ground
pygame.draw.rect(window, black, groundRect, 5) # Here we draw the black box around the rect
for event in pygame.event.get(): # Getting events
if event.type == pygame.QUIT: # If someone presses X on the window, then we want to quit
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE: # Pressing space will make the cube jump
if y >= 300: # Checking if cube is on the ground and not in the air
yVelocity = -10 # Setting velocity to upwards
pygame.display.flip() # Updating the screen
Just getting started with pygame (python 2.7, win7, i3) and looking at the tutorial here: http://www.pygame.org/docs/tut/intro/intro.html
When I run the code example:
import sys, pygame
pygame.init()
size = width, height = 320, 240
speed = [2, 2]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load('ball.bmp')
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
...from IDLE or powershell, the game window only updates when the mouse is actively moving over the game window. I was expecting that the ball would simply bounce around on its own. Is this mouse--position related performance due to the way pygame/SDL deal with graphics modes? Is it related to the hardware? Is there a way to improve the performance through the code? I'd like to get the proverbial ball rolling with pygame and this seems... odd. Thank you.
edit:
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
You have the update code INSIDE the function! Move it out like this and it will work.
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
I'm stumped after tying to attach a snake tail img, can someone explain a possible way to attach it so after each block is added it stays at the end.
The snake tail is variable tail under ##Snake Images
import pygame
import random
import time
pygame.init()
White = (255,255,255)
Black = (0,0,0)
Green = (0,155,0)
Lgreen = (219,255,219)
Red = (255,0,0)
Dwidth = 800
Dheight = 600
GameDisplay = pygame.display.set_mode((Dwidth,Dheight))
pygame.display.set_caption("Snake")
##Other Images
icon = pygame.image.load('apple.png')
pygame.display.set_icon(icon)
Logo = pygame.image.load('Snakelogo.png')
##Apple Images
appleimg = pygame.image.load('apple.png')
##Snake Images
img = pygame.image.load('snake.png')
tail = pygame.image.load('snakebot.png')
Clock = pygame.time.Clock()
blockS = 20
AppleThickness = 30
FPS = 17.5
direction = "right"
smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 80)
def pause():
paused = True
message("Paused",
Black,
-100,
size="large")
message("Press SPACE again to continue or Q to quit.",
Black,
25)
pygame.display.update()
while paused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
paused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()
Clock.tick(5)
def score(score):
text = smallfont.render("Score: "+str(score), True, Black)
GameDisplay.blit(text,[0,0])
def randAppleGen():
randAppleX = round(random.randrange(0,Dwidth-AppleThickness))#/10.0)*10.0
randAppleY = round(random.randrange(0,Dheight-AppleThickness))#/10.0)*10.0
return randAppleX,randAppleY
randAppleX,randAppleY = randAppleGen()
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(Lgreen)
GameDisplay.blit(Logo,[0,100,800,170])
message("The objective of the game is to eat red apples,",
Black,
-30)
message("the more apples you eat the longer you get and",
Black,
10)
message("if you run into yourself or the edges you die.",
Black,
50)
message("Press C to play, SPACE to pause, or Q to quit.",
Black,
180)
pygame.display.update()
Clock.tick(15)
def snake(blockS,snakeList):
if direction == "right":
head = pygame.transform.rotate(img, 270)
if direction == "left":
head = pygame.transform.rotate(img, 90)
if direction == "up":
head = img
if direction == "down":
head = pygame.transform.rotate(img, 180)
GameDisplay.blit(head,(snakeList[-1][0],snakeList[-1][1]))
for XnY in snakeList[:-1]:
pygame.draw.rect(GameDisplay,Green,[XnY[0],XnY[1],blockS, blockS])
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()
def message(msg,color,y_displace=0, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = (Dwidth/2),(Dheight/2) +y_displace
GameDisplay.blit(textSurf,textRect)
def gameloop():
global direction
direction = "right"
GameEX = False
GameOver = False
Hor_X = Dwidth/2
Ver_Y = Dheight/2
MoveS = 10
MoveDU = 0
snakeList = []
snakeLength = 1
randAppleX,randAppleY = randAppleGen()
while not GameEX:
if GameOver == True:
message("Game Over",
Red,
y_displace=-50,
size="large")
message("Press C to play again or Q to Quit", Black,50, size = "medium")
pygame.display.update()
while GameOver == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
GameEX = True
GameOver = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
GameEX = True
GameOver = False
if event.key == pygame.K_c:
gameloop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
GameEX = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
MoveS = -blockS
MoveDU = 0
direction = "left"
elif event.key == pygame.K_RIGHT:
MoveS = blockS
MoveDU = 0
direction = "right"
elif event.key == pygame.K_UP:
MoveDU = -blockS
MoveS = 0
direction = "up"
elif event.key == pygame.K_DOWN:
MoveDU = blockS
MoveS = 0
direction = "down"
elif event.key == pygame.K_SPACE:
pause()
if Hor_X >= Dwidth or Hor_X < 0 or Ver_Y >= Dheight or Ver_Y < 0:
GameOver = True
Hor_X += MoveS
Ver_Y += MoveDU
GameDisplay.fill(Lgreen)
GameDisplay.blit(appleimg,(randAppleX, randAppleY))
snakeHead = []
snakeHead.append(Hor_X)
snakeHead.append(Ver_Y)
snakeList.append(snakeHead)
if len(snakeList) > snakeLength:
del snakeList[0]
for eachSegment in snakeList[:-1]:
if eachSegment == snakeHead:
GameOver = True
snake(blockS,snakeList)
score(snakeLength-1)
pygame.display.update()
if Hor_X > randAppleX and Hor_X < randAppleX + AppleThickness or Hor_X + blockS > randAppleX and Hor_X + blockS < randAppleX + AppleThickness:
if Ver_Y > randAppleY and Ver_Y < randAppleY + AppleThickness:
randAppleX,randAppleY = randAppleGen()
snakeLength += 1
elif Ver_Y + blockS > randAppleY and Ver_Y + blockS < randAppleY + AppleThickness:
randAppleX,randAppleY = randAppleGen()
snakeLength += 1
Clock.tick(FPS)
pygame.quit()
quit()
game_intro()
gameloop()
inserting this into the snake function is as close as Ive gotten to attaching it to the end~
for XnY in snakeList[0]:
GameDisplay.blit(tail,(snakeList[0][0],snakeList[0][1]))
I just increased my snakeLength to 2 and it solved my problem after adding
for XnY in snakeList[0]:
GameDisplay.blit(tail,(snakeList[0][0],snakeList[0][1]))
into the snake function.
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.MOUSEBUTTONDOWN:
is_inside = my_rect.collidepoint(pygame.mouse.get_pos())
print is_inside
if is_inside == 1:
myfont = pygame.font.SysFont("monospace", 15)
label = myfont.render("The Penrose Triangle by Roman Formicola", 5, (black))
gameDisplay.blit(label, (300,150))
I had it my goal is that once you click on my_rect the message will stay there indefinately
Just create a variable holding your Rect (actually using the Rect class):
my_rect = pygame.Rect(400, 300, 100, 100)
Then you can use the collidepoint() method of Rect to check if the mouse position is inside my_rect:
...
elif event.type == pygame.MOUSEBUTTONDOWN:
is_inside = my_rect.collidepoint(pygame.mouse.get_pos())
pygame.draw.rect(gameDisplay, cyan, my_rect, 0)
...
I have this code
import pygame, random, sys
from pygame.locals import *
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
BLUE = (0 , 0, 255)
WIDTH = 20
HEIGHT = 20
WIDTH1 = 30
HEIGHT1 = 30
MARGIN = 5
MARGIN1 = 10
array_width = 4
array_height = 8
grid = []
guess1 = 'white'
guess2 = 'yellow'
guess3 = 'blue'
guess4 = 'green'
guess5 = 'red'
guess6 = 'pink'
guess7 = 'purple'
guess8 = 'orange'
loop = ()
computerguess = []
# CREATING RANDOM COLOUR SEQUENCE TO GUESS
for i in range(4):
loop = random.randint(1,8)
if loop == 1:
computerguess.append(guess1)
if loop == 2:
computerguess.append(guess2)
if loop == 3:
computerguess.append(guess3)
if loop == 4:
computerguess.append(guess4)
if loop == 5:
computerguess.append(guess5)
if loop == 6:
computerguess.append(guess6)
if loop == 7:
computerguess.append(guess7)
if loop == 8:
computerguess.append(guess8)
print(computerguess)
for row in range(10):
grid.append([])
for column in range(10):
grid[row].append(0)
colors = [(0, 0, 0) for i in range(array_width * array_height)]
blocks = [False for i in range(array_width * array_height)]
indicator_grid = [[None for column in range(4)] for row in range(8)]
pygame.init()
# Set the HEIGHT and WIDTH of the screen
WINDOW_SIZE = [300, 300]
WINDOW_SIZE2 = [300, 300]
screen = pygame.display.set_mode(WINDOW_SIZE)
screen2 = pygame.display.set_mode(WINDOW_SIZE2)
# Set title of screen
pygame.display.set_caption("MASTERMIND GAME")
done = False
clock = pygame.time.Clock()
# -------- Main Program Loop -----------
#TEXT BOX VARIABLES AND DATA
base_font = pygame.font.Font(None, 20)
user_text = ""
input_rect = pygame.Rect (10,250,100,50)
color_active = pygame.Color('lightskyblue3')
color_passive = pygame.Color('gray15')
color=color_passive
active = False
current_color = "white"
grid = [[current_color for column in range(4)] for row in range(8)]
#----MAIN PROGRAM LOOP----#
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.MOUSEBUTTONDOWN:
pos = pygame.mouse.get_pos()
column = pos[0] // (WIDTH + MARGIN)
row = pos[1] // (HEIGHT + MARGIN)
# check if column and row are valid grid indices
if 0 <= row < array_height and 0 <= column < array_width:
try:
grid[row][column] = current_color
except:
print("invalid color")
# TEXT BOX CREATION AND USAGE
if event.type == pygame.MOUSEBUTTONDOWN:
if input_rect.collidepoint(event.pos):
active = True
else:
active = False
if event.type == pygame.KEYDOWN:
if active == True:
if event.key == pygame.K_BACKSPACE:
user_text = user_text[0:-1]
else:
user_text += event.unicode
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN:
user_text = user_text
if user_text != "":
current_color = user_text
user_text = ""
if active:
color = color_active
else:
color=color_passive
#TEXT FOR THE GUI TO MAKE IT EASIER FOR THE USER
screen.fill(0)
pygame.draw.rect(screen,color,input_rect,2)
text_surface= base_font.render(user_text,True,(255,255,255))
screen.blit(text_surface, (input_rect.x +5, input_rect.y + 5))
text1 = base_font.render("WORK BOTTOM TO TOP ", True, (0, 50, 255))
text2 = base_font.render('POSSIBLE CHOICES:', True, (250, 0, 0))
text3 = base_font.render('WHITE BLUE RED', True, (0, 128, 0))
text4 = base_font.render('GREEN ORANGE PINK', True, (0,128,0))
text5= base_font.render('PURPLE YELLOW', True, (0, 128, 0))
screen.blit(text1,(140, 200))
screen.blit(text2,(140, 220))
screen.blit(text3,(140, 240))
screen.blit(text4,(140, 260))
screen.blit(text5,(140, 280))
screen.blit(text5,(140, 280))
for row, gridrow in enumerate(grid):
for column, color in enumerate(gridrow):
pygame.draw.rect(screen,
color,
[(MARGIN + WIDTH) * column + MARGIN,
(MARGIN + HEIGHT) * row + MARGIN,
WIDTH,
HEIGHT])
if gridrow == computerguess:
text = base_font.render("Correct, you win!!!!!", True, (255, 128, 0))
screen.blit(text,
(10, 220 ))
x = 100 + (MARGIN + WIDTH) * column + MARGIN
y = (MARGIN + HEIGHT) * row + MARGIN
color = "grey"
pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)
for row, gridrow in enumerate(grid):
if computerguess[0] == gridrow[0]:
color = "red"
pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)
if computerguess[1] == gridrow[1]:
color = "purple"
pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)
if computerguess[2] == gridrow[2]:
color = "red"
pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)
if computerguess[3] == gridrow[3]:
color = "red"
pygame.draw.circle(screen, color, (x + WIDTH // 2, y + WIDTH // 2), WIDTH // 2)
clock.tick(60)
pygame.display.flip()
pygame.quit()
i would like to add a title screen, that says start in the form of a button and then would transfer them to the code to begin playing, but i'm not very sure how to do it, i have added a new window (WINDOW_SIZE2), but i am not sure where to go from there
Any help is much appreciated
Thanks
The implementation of a button is answered several times. For example Pygame mouse clicking detection, How do I detect if the mouse is hovering over a button? PyGame button class is not displaying the text or changing colour on hover or How can I add an image or icon to a button rectangle in Pygame? and myn more.
Create 2 scenes with 2 application loops. The first loop shows the title screen and waits for button 2 to be pressed. The 2nd loop is the game loop:
button_rect = pygame.Rect(x, y, width, height) # start button rectangle
abort = False
start = False
while not abort and not start:
for event in pygame.event.get():
if event.type == pygame.QUIT:
abort = True
if event.type == MOUSEBUTTONDOWN:
if button_rect.collidepoint(event.pos):
start = True
# draw title screen
# [...]
done = abort
while not done:
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
# game
# [...]
Alternatively, you can combine both scenes in one loop.Add a variable game_state, implement event handling and draw the scenes depending on the value of game_state. Change the game_state when the start button is pressed:
game_state = 'title'
done = False
while not done:
# event handling
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if game_state == 'title':
if event.type == MOUSEBUTTONDOWN:
if button_rect.collidepoint(event.pos):
game_state = 'game'
elif game_state == 'game':
# handle game events:
# [...]
# drawing
if game_state == 'title':
# draw title screen
# [...]
elif game_state == 'game':
# game
# [...]