go button does not work due to issues in main loop - python

def game_controls(): # First page of controls #################################
gcont = True
global intro
gameDisplay.fill(white)
while gcont:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
game_controls1()
message_to_screen("Cystal Caves", green,-100, size="large")
message_to_screen("Created by 'Alan Benoy'", black, 10)
message_to_screen("-- -- -- -- -- Press -C- to continue along screens -- -- -- -- --", yellow, 250)
def game_controls1(): # Page 1 of controls ###################################
gcont1 = True
global intro
gameDisplay.fill(white)
while gcont1:
message_to_screen("Welcome to Crystal Caves!",green,-100,size="large")
message_to_screen("Journey through different caverns and explore the caves mysteries!",black,10)
message_to_screen("Find the caves hidden treasures and become rich!",black,50)
message_to_screen("But BEWARE... Danger lurks around every corner with monster hiding in dark!",black,90)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
game_controls2()
def game_controls2(): # Page 2 of controls ###################################
gcont2 = True
global intro
gameDisplay.fill(white)
while gcont2:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
game_controls3()
message_to_screen("Controls:",green,-100,size="large")
message_to_screen("Press the right arrow key to movie right",black,10)
message_to_screen("Press the left arrow key to move left",black,50)
message_to_screen("Press the up arrow key to jump up",black,90)
message_to_screen("Press -E- to exit the game whenever",black,130)
message_to_screen("Press -P- to pause the game",black,170)
message_to_screen("Press -C- to unpause and continue the game",black,210)
message_to_screen("Press -R- to restart the game (to Main Menu)",black,250)
def game_controls3(): # Final page of controls ###############################
gcont3 = True
global intro
gameDisplay.fill(white)
while gcont3:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_e:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
game_intro() # Leads user back to game intro screen
message_to_screen("Now it's Time to Play:",green,-100,size="large")
message_to_screen("Enter the cave to begin your adventure... IF YOU DARE!!!",black,10)
######################## Message to Screen Variables ##########################
def text_objects(text, color,size = "small"):
if size == "small":
textSurface = smallfont.render(text, True, color)
if size == "medium":
textSurface = medfont.render(text, True, color)
if size == "large":
textSurface = largefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def message_to_screen(msg,color, y_displace = 0, size = "small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = (int(display_width / 2), int(display_height / 2)+y_displace)
gameDisplay.blit(textSurf, textRect)
pygame.display.update()
########################## Game Intro Buttons #################################
def button(msg,x,y,w,h,ic,ac, action = None ):
global intro
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#print(click)
#print(mouse)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, ac, (x, y, w, h))
if click[0] == 1 and action != None:
if action == "play":
intro = False
redrawGameWindow()
if click[0] == 1 and action != None:
if action == "controls":
game_controls()
if click[0] == 1 and action != None:
if action == "quit":
pygame.quit()
quit()
else:
pygame.draw.rect(gameDisplay, ic,(x, y, w, h))
font = pygame.font.SysFont('calbri', 30)
text = font.render(msg, 1, (255, 255, 255))
position = ( ((x+8)+((w-100)/2)), ((y+40)+((h-100)/2)) )
win.blit(text, position)
########################## Game Intro Function ################################
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
elif event.key == pygame.K_e:
pygame.quit()
quit()
win.fill((0, 255, 255))
font = pygame.font.SysFont('Bahnschrift Light', 60)
text = font.render('Cystal Caves', 1, (0, 0, 255))
win.blit(text, (424, 60))
button(' Go!',(150+160),450,100,50,(0, 255, 0),(0, 200, 0), "play")
button("Controls",(350+160),450,100,50,(249, 166, 2), (255, 255, 0), "controls")
button(' Quit?',(550+160),450,100,50,(255, 0, 0),(200, 0, 0), "quit")
pygame.display.update()
clock.tick(15)
This is the issue as it does not activate the go button, I have tried using the redraw game window and variables but nothing seems to work. I really need this fixed as it is part of a very big assignment that is due soon and I am having mental breakdowns. I have gotten the c button to work and it enters the game and I tried for the go button but its not working and I just don't know why. PLEASE HELP!!!!

I believe this is an issue with your global intro variable. The global keyword should be used when you want to assign a new value to a global variable inside a function and a global variable should be initialized outside of a function.
So if you initialize the intro variable outside of any function e.g.
intro = true
def game_controls(): # First page of controls #################################
gcont = True
global intro
gameDisplay.fill(white)
...
and then change your game_intro() function to
def game_intro():
global intro
while intro:
...
then your issue should be solved (or at least an issue should be solved).

Related

Pygame error: pygame.error: display Surface quit

So I created a Python game Tetris based on Youtube tutorial:
https://www.youtube.com/watch?v=zfvxp7PgQ6c&t=2075s
But the pygame.error: display Surface quit occurs.
I have tried to add "break", "sys.exit()", "QUIT" after the pygame.quit but does not work.
Does anyone know how to solve it? Here is the code: (You can skip to the def main_menu)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run == False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
current_piece.x -= 1
if not (valid_space(current_piece, grid)):
current_piece.x += 1
if event.key == pygame.K_RIGHT:
current_piece.x += 1
if not (valid_space(current_piece, grid)):
current_piece.x -= 1
if event.key == pygame.K_DOWN:
current_piece.y += 1
if not (valid_space(current_piece, grid)):
current_piece.y -= 1
if event.key == pygame.K_UP:
current_piece.rotation += current_piece.rotation + 1 % len(current_piece.shape)
if not (valid_space(current_piece, grid)):
current_piece.rotation -= 1
shape_pos = convert_shape_format(current_piece)
for i in range(len(shape_pos)):
x, y = shape_pos[i]
if y > -1:
grid[y][x] = current_piece.color
if change_piece:
for pos in shape_pos:
p = (pos[0], pos[1])
locked_positions[p] = current_piece.color
current_piece = next_piece
next_piece = get_shape()
change_piece = False
score += clear_rows(grid, locked_positions) * 10
draw_window(win, grid, score, last_score)
draw_next_shape(next_piece, win)
pygame.display.update()
if check_lost(locked_positions):
draw_text_middle(win, "You Lost!", 80, (255,255,255))
pygame.display.update()
pygame.time.delay(1500)
run = False
update_score(score)
def main_menu(win):
run = True
while run:
win.fill((0,0,0))
draw_text_middle(win, 'Press any key to play', 60, (255,255,255))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
main(win)
pygame.display.QUIT()
win = pygame.display.set_mode((s_width, s_height))
pygame.display.set_caption('Tetris')
main_menu(win)
Updated code:
def main_menu(win):
run = True
while run:
win.fill((0,0,0))
draw_text_middle(win, 'Press any key to play', 60, (255,255,255))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
main(win)
pygame.quit()
win = pygame.display.set_mode((s_width, s_height))
pygame.display.set_caption('Tetris')
main_menu(win)
In your main_menu loop you are telling it to loop while local boolean run == True. This is okay, but you should as people mentioned in the comments do a pygame.quit() and optionally quit() (closes the window) instead of the pygame.display.quit() and sys.exit() that you have right now.
The second problem occurs if you start the game by going into the main loop. I assume that the main loop runs your events function shown at the top?
Depending on how you have written the code, the boolean run in the event function is
local. This means that it will not change the value of the run you are using in your
main loop (nor change it in the main_menu loop). I would suggest to transfer into OOP and create a self.run boolean instead,
or else you need to make the boolean run global.
And you should in the event function write this instead of what you have now at the
top:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
quit()
Hope this helps!

Why is the "Game Over" text not displayed?

I have this code, and when I click ESC, I don't see "Game Over". The program waits for two seconds and closes without displaying text.
Pygame 1.9.6
What am I doing wrong?
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -block_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = block_size
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_x_change = 0
lead_y_change = -block_size
elif event.key == pygame.K_DOWN:
lead_x_change = 0
lead_y_change = block_size
elif event.key == pygame.K_ESCAPE:
run = False
game_display.fill(white)
lead_x += lead_x_change
lead_y += lead_y_change
pygame.draw.rect(game_display, black, [lead_x, lead_y, width, height])
pygame.display.update()
clock.tick()
draw_text_middle("Game Over", 40, (0, 0, 0, 255), game_display)
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
You've to remove the pygame.quit() call from the event loop. pygame.quit() uninitialize all pygame modules. After calling this function, nothing can be drawn any further calls to any pygame instructions will cause an exception.
I recommend to process the pygame events by pygame.event.pump() before .delay the application. This allows pygame to handle internal actions:
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# pygame.quit() <---------- delete
# [...]
draw_text_middle("Game Over", 40, (0, 0, 0, 255), game_display)
pygame.display.update()
pygame.event.pump()
pygame.time.delay(2000)
pygame.quit()

Im making a menu that uses the arrow keys to navigate it, but it doesnt work

I'm making a game with a menu that uses left and right arrow keys to navigate it. The issue is when you press one of the arrows, it rapidly switches between the two. I'm assuming I need to use pygame.KEYUP, but i'm not sure how to use it. Right now it just flickers between Play and Quit. Here's my code. I want it so if you press left or right it selects play or quit and doesn't flicker between both.
'''
Mega Maro Bois
Zan3yGameZ 2018
'''
import pygame, time
pygame.init()
def createWindow():
global WIDTH, HEIGHT, TITLE, W
WIDTH, HEIGHT = 800, 450
TITLE = "Mega Maro Bois"
pygame.display.set_caption(TITLE)
W = pygame.display.set_mode( (WIDTH, HEIGHT), pygame.HWSURFACE|pygame.DOUBLEBUF )
createWindow()
menu = pygame.image.load("Graphics\\Menu.png")
############################################################# PLAY PICTURES
play = pygame.image.load("Graphics\\Play.png")
play_sel = pygame.image.load("Graphics\\Play_Selected.png")
############################################################# QUIT PICTURES
quit = pygame.image.load("Graphics\\Quit.png")
quit_sel = pygame.image.load("Graphics\\Quit_Selected.png")
Event = "Menu"
loop = True
Button_Sel = "Play"
Button_Sel2 = 1
if Event == "Menu":
W.blit(menu, (0, 0))
W.blit(play, (25, 250))
W.blit(quit, (435, 250))
while loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
if Event == "Menu":
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
Button_Sel = "Play"
if event.key == pygame.K_2:
Button_Sel = "Quit"
if event.key == pygame.K_RIGHT:
Button_Sel2 += 1
if event.key == pygame.K_LEFT:
Button_Sel2 -= 1
#################################################################ENTER SELECT
if Button_Sel == "Play" and event.key == pygame.K_RETURN:
Event = "Play"
if Button_Sel == "Quit" and event.key == pygame.K_RETURN:
pygame.quit()
exit()
#################################################################SPACE SELECT
if Button_Sel == "Play" and event.key == pygame.K_SPACE:
Event = "Play"
if Button_Sel == "Quit" and event.key == pygame.K_SPACE:
pygame.quit()
exit()
###################################################IF USER SELECTS PLAY
if Button_Sel == "Play":
W.blit(play_sel, (25, 250))
W.blit(quit, (435, 250))
###################################################IF USER SELECTS QUIT
if Button_Sel == "Quit":
W.blit(play, (25, 250))
W.blit(quit_sel, (435, 250))
if Button_Sel2 == 1:
Button_Sel = "Play"
if Button_Sel2 == 2:
Button_Sel = "Quit"
pygame.display.update()
pygame.quit()
exit()
I mostly just need to know how to use pygame.KEYUP in this situation.
Your if event.type == pygame.KEYDOWN: is outside the event dealing loop for event in pygame.event.get():
That means you keep processing the same event over and over
Put the event check inside the loop.

Collision detection between an image and an object in Pygame

Hope you all are having a great day.
I am trying to detect a collision between my object (the black rectangle) and the food image.
What i want to basically do is whenever my rectangle collides with the food image, the food image is then placed randomly on the screen and the score gets increased by +1.
import pygame
import time
import random
pygame.init()
#Colours
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,155,0)
#Game Display
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('KALM Creation')
#Directions
DOWN='down'
UP='up'
LEFT='left'
RIGHT='right'
#Score
score=0
# My food image
foodimg=pygame.image.load("food.png")#.convert_alpha()
foodrect = foodimg.get_rect()
foodrect.centerx = 100
foodrect.centery = 200
#Our Icon For The Game
icon=pygame.image.load('icon1.jpg')
pygame.display.set_icon(icon)
#Clock
clock = pygame.time.Clock()
FPS = 30
cellSize=10
#Font Size
smallfont = pygame.font.SysFont("comicsansms", 25)
medfont = pygame.font.SysFont("comicsansms", 50)
largefont = pygame.font.SysFont("comicsansms", 80)
#The score function - displays the score on top right
def scoredisplay(scoredef=0):
text=smallfont.render("Score :%s" %(scoredef) ,True ,black)
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(white)
#Game Initial display message
message_to_screen("Welcome To Eat it Game",
green,
-200,
size="medium")
message_to_screen("Press 'C' to play the game or 'Q' to quit.",
black,
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)
#Drawing Cells
def drawCell(coords,ccolor):
for coord in coords:
x=coord['x']*cellSize
y=coord['y']*cellSize
makeCell=pygame.Rect(x,y,cellSize,cellSize)
pygame.draw.rect(gameDisplay,ccolor,makeCell)
#The Game run up
def runGame():
score=0
gameExit = False
gameOver = False
#Starting Position of the object
startx=3
starty=3
coords=[{'x':startx,'y':starty}]
direction = RIGHT
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",
black,
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:
direction = LEFT
elif event.key == pygame.K_RIGHT:
direction = RIGHT
elif event.key == pygame.K_UP:
direction = UP
elif event.key == pygame.K_DOWN:
direction = DOWN
if direction == UP:
newCell={'x':coords[0]['x'],'y':coords[0]['y']-1}
elif direction == DOWN:
newCell={'x':coords[0]['x'],'y':coords[0]['y']+1}
elif direction == LEFT:
newCell={'x':coords[0]['x']-1,'y':coords[0]['y']}
elif direction == RIGHT:
newCell={'x':coords[0]['x']+1,'y':coords[0]['y']}
del coords[-1]
coords.insert(0, newCell)
gameDisplay.fill(white)
drawCell(coords,black)
clock.tick(FPS)
#If object moves outside the screen , game gets over.
if(newCell['x']<0 or newCell['y']<0 or newCell['x']>display_width/cellSize or newCell['y']>display_height):
gameOver= True
#Displays Score
scoredisplay(score)
gameDisplay.blit(foodimg,foodrect)
#pygame.display.flip()
pygame.display.update()
#The game run up
def gameLoop():
clock.tick(FPS)
runGame()
pygame.quit()
quit()
game_intro()
gameLoop()
In the drawcell() call:
if makecell.colliderect(foodrect):
foodrect.x = random.randint(0, sceeenwidth)
foodrect.y = random.randint(0, screenheight)
Should do it.

Pygame Index Out of Range

I am building an asteroids-like game with python, but I'm running into trouble with keeping within the range of my possibleTurrets array. All I'm doing is iterating through the array, and when the edge cases outside of the array occur, I deal with them through:
if currentTurPos > 8:
currentTurPos = 8
elif currentTurPos < 0:
currenTurPos = 0
This is in reference to this array:
possibleTurrets = [ (x-27,y-2),
(x-26,y-5),
(x-25,y-8),
(x-23,y-12),
(x-20,y-14),
(x-18,y-15),
(x-15,y-17),
(x-13,y-19),
(x-11,y-21)
]
For some reason this code works fine on pygame.K_UP but not on pygame.K_DOWN and I have no idea why.
This seems like it should be really obvious, but I've spent an hour trying to fix it, and am drawing a blank. The issue is with my ufo function, and the currentTurPos variable.
# Libraries
import pygame
import time
import random
import os
# Initialize Pygame
pygame.init()
# Colors
white = (255,255,255)
black = (0,0,0)
red = (200,0,0)
blue = (0,0,255)
green = (34,177,76)
light_green = (0,255,0)
yellow = (200,200,0)
light_yellow = (255,255,0)
light_red = (255,0,0)
# Display
display_width = 800
display_height = 600
gameDisplay = pygame.display.set_mode((display_width,display_height))
#pygame.display.set_caption('Slither')
#icon = pygame.image.load('apple.bmp')
#pygame.display.set_icon(icon)
clock = pygame.time.Clock()
# Sprites
ufoWidth = 40
ufoHeight = 20
turretWidth = 5
turretHeight = 10
fps = 15 # Speed
# Fonts
smallFont = pygame.font.SysFont("comicsansms", 25)
medFont = pygame.font.SysFont("comicsansms", 50)
largeFont = pygame.font.SysFont("comicsansms", 80)
def ufo(x,y,turPos):
x = int(x)
y = int(y)
possibleTurrets = [ (x-27,y-2),
(x-26,y-5),
(x-25,y-8),
(x-23,y-12),
(x-20,y-14),
(x-18,y-15),
(x-15,y-17),
(x-13,y-19),
(x-11,y-21)
]
pygame.draw.circle(gameDisplay, blue, (x,y),int(ufoHeight/2))
pygame.draw.ellipse(gameDisplay, black, (x-ufoHeight, y, ufoWidth, ufoHeight))
pygame.draw.line(gameDisplay,blue,(x,y),possibleTurrets[turPos],turretWidth)
# Font sizes
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()
# Displays a message: Requires message, color, y-displacement, and size arguments
def message_to_screen(msg, color, y_displace=0, size="small"):
textSurf, textRect = text_objects(msg, color, size)
textRect.center = (int(display_width/2), (int(display_height/2) + y_displace))
gameDisplay.blit(textSurf, textRect)
# Show button text
def text_to_button(msg,color, buttonx,buttony,buttonwidth,buttonheight,size="small"):
textSurf, textRect = text_objects(msg,color,size)
textRect.center = ((buttonx+(buttonwidth/2)), buttony+(buttonheight/2))
gameDisplay.blit(textSurf, textRect)
# On button hover
def button(text,x,y,width,height,inactive_color,active_color,action):
cursor = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + width > cursor[0] > x and y + height > cursor[1] > y:
pygame.draw.rect(gameDisplay,active_color,(x,y,width,height))
if click[0] == 1 and action != None:
if action == "play":
gameLoop()
if action == "controls":
game_controls()
if action == "quit":
pygame.quit()
quit()
else:
pygame.draw.rect(gameDisplay,inactive_color,(x,y,width,height))
text_to_button(text,black,x,y,width,height)
def game_controls():
gcont = True
while gcont:
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(white)
message_to_screen("Controls", green, -100, size="large")
message_to_screen("Fire: Spacebar", black, -30, size="small")
message_to_screen("Move turret: Up and Down arrows", black, 10, size="small")
message_to_screen("Move UFO: Left and Right arrows", black, 50, size="small")
message_to_screen("Pause: P", black, 90, size="small")
button("Play",150,450,100,50, green, light_green, action="play")
button("Quit",550,450,100,50, red, light_red, action="quit")
pygame.display.update()
clock.tick(fps)
# Pauses game and gives continue and quit options
def pause():
paused = True
message_to_screen("Paused", black, -100, size="large")
message_to_screen("Press P to play, or Q to quit.", black, 25, size="small")
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_p:
paused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()
pygame.display.update()
clock.tick(fps)
# Keeps track of, and displays the score
def score(score):
text = smallFont.render(" Score: " + str(score), True, black)
gameDisplay.blit(text, [0,0])
# Barrier
def barrier():
xlocation = (display_width/2) + random.randint(-0.2*displayWidth,0.2*displayWidth)
# Intro screen - Title and directions
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(white)
message_to_screen("Welcome to UFO!", green, -100, size="large")
message_to_screen("The objective of the game is to search and destroy.", black, -30, size="small")
message_to_screen("Destroy your opponent before they destroy you.", black, 10, size="small")
message_to_screen("The more enemies you destroy, the harder they get.", black, 50, size="small")
button("Play",150,450,100,50, green, light_green, action="play")
button("Controls",350,450,100,50, yellow, light_yellow, action="controls")
button("Quit",550,450,100,50, red, light_red, action="quit")
pygame.display.update()
clock.tick(fps)
# Main game loop
def gameLoop():
gameExit = False
gameOver = False
mainUfoX = display_width * 0.9
mainUfoY = display_height * 0.9
ufoMove = 0
currentTurPos = 0
changeTur = 0
# Game over screen and changes for key inputs
while not gameExit:
if gameOver == True:
message_to_screen("Game over!", red, -50, size="large")
message_to_screen("Press C to play again, Q to quit.", black, 50, size="medium")
pygame.display.update()
while gameOver == True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
gameOver = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
gameLoop()
# Make changes for specific key inputs
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
ufoMove = -5
elif event.key == pygame.K_RIGHT:
ufoMove = 5
elif event.key == pygame.K_UP:
changeTur = 1
elif event.key == pygame.K_DOWN:
changeTur = -1
elif event.key == pygame.K_p:
pause()
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
ufoMove = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
changeTur = 0
gameDisplay.fill(white)
mainUfoX += ufoMove
currentTurPos += changeTur
if currentTurPos > 8:
currentTurPos = 8
elif currentTurPos < 0:
currenTurPos = 0
ufo(mainUfoX,mainUfoY,currentTurPos)
pygame.display.update()
clock.tick(fps)
# Quits
pygame.quit()
quit()
# Loads game intro screen
game_intro()
# gameLoop calls itself to begin game
gameLoop()
It was a typo (I'm an idiot).
currentTurPos was currenTurPos.
Lesson learned: complex variable names with repeating letters are dangerous.

Categories

Resources