I'm creating the base of a game that will have scrolling text and text wrapping when a line of text goes to far on the screen.
Everything works (so far) but at a certain point when using my default_display_text function pygame stops responding. It always stops around the "broke, slap some fancy words" part when I use my default_display_text function with greeting as the variable.
I've been able to solve all my other problems with google but this one has got me really stuck! I'll be glad to give any other information and I hope you understand what my code does with help from the comments.
import pygame, math, pygame.display, time, pygame.mouse
from pygame.locals import *
pygame.init()
pygame.font.init()
infoObject = pygame.display.Info()
window_height = infoObject.current_w
window_width = infoObject.current_h
gameDisplay = pygame.display.set_mode((window_height, window_width), pygame.RESIZABLE)
pygame.display.set_caption('Aperture_Game')
pygame.mouse.set_visible(False)
c_font = 'C:\Windows\Fonts\Courier Regular.fon'
background = (10,10,10)
black = (0,0,0)
white = (255,255,255)
text_color = (39, 167, 216)
clock = pygame.time.Clock()
loop = True
default_font_size = 26
greeting = "Greetings! My name is Cave Johnson, CEO of Aperture Science. Our motto here is \"If it ain't broke, slap some fancy words on it and sell it for profit!\""
'''
def message_display(text,x,y,font,color,size):
fontObj = pygame.font.SysFont(font, size)
label = fontObj.render(text, 1, color)
gameDisplay.blit(label, (x,y))
'''
def default_display_text(string,x,y):
text = ''
#a tracks i's value.
a = 0
#newline helps determine when to wrap the text.
newline = 0
#ref is a reference for when to wrap the text (I only want to wrap text after a space so the wrapping doesn't split words in half).
ref = ' '
fontObj = pygame.font.SysFont(c_font, default_font_size)
text_surface = fontObj.render(text, True, text_color)
text_rect = text_surface.get_rect()
#this for loop is what displays the text one character at a time and wraps it.
for i in range(len(string)):
gameDisplay.fill(background)
if newline == 0:
gameDisplay.blit(text_surface, (x,y))
#if the text goes to far to the right and a word is complete, I want to start a new line.
if pygame.Surface.get_width(text_surface) > 1000:
#makes sure that its not in the middle of a word.
if string[a] == ref:
#making sure its not a double space
if string[a+1] != ref:
newline = 1
text = text[a:]
else:
newline = 0
#adds another character of the string to the text variable
if newline == 0:
text += string[i]
# if newline is not 0 then the start of the text is shifted down and all the previous text is deleted.
else:
y += 25
newline = 0
text += string[a:a+1]
text = text[a:]
a = 0
a += 1
pygame.display.update()
pygame.time.wait(50)
#Just your average main loop
def main():
loop = True
while loop:
for event in pygame.event.get():
if event.type == pygame.QUIT:
loop = False
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
loop = False
#add controls here later
gameDisplay.fill(background)
default_display_text(greeting, 50, 50)
pygame.display.update()
clock.tick(60)
main()
pygame.quit()
quit()
The Python Debugger is your friend.
Start your program using the syntax
python -m pdb <scriptfile>
Enter "c" for continue into the cli
As soon as your program seems to freeze, press CTRL+C
You should then be able to analyze the current state of the program using the debugger. For instance entering "where" into the cli, you should see the current callstack and line number.
Related
I am creating a game with pygame in which the color of a letter changes when you type that letter. Like nitrotype.com. However the problem is that I don't know how to change the colour of individual letters.
I can't clear the screen and then do it because then that would change the color of the entire line.
So either I need a way to change the colour of individual letters or a way to just put single letters on the screen one at a time. However I don't know how to uniformly put the letters(such that the end sentence is centered). Please could someone help me out here. Either by telling me how to change the color of individual letters or how to put individual letters in a perfect manner and then change their color.
import pygame as pg
import pygame
pg.init()
screenHeight, screenWidth = 600, 800
gameDisplay = pg.display.set_mode((screenWidth, screenHeight))
pg.display.set_caption("Nitrotype")
black = (255, 255, 255)
white = (0, 0, 0)
gameDisplay.fill(white)
pg.display.update()
gameOn = True
with open("text.txt", "r") as f:
contents = f.read()
def msgToScreen(msg, color, size):
cur = []
strings = []
words = msg.split(" ")
for i in words:
cur.append(i)
if len(" ".join(cur)) >= 35:
strings.append(" ".join(cur))
cur = []
if cur != []:strings.append(" ".join(cur))
curY = 20
for string in strings:
font = pg.font.SysFont(None, size)
text = font.render(string, True, color)
text_rect = text.get_rect(center=(screenWidth/2, curY))
gameDisplay.blit(text, text_rect)
curY += 40
return text
textOnScreen = msgToScreen(contents, black, 50)
pg.display.update()
curIdx = 0
keyCombination = {"a":pg.K_a, "b":pg.K_b, "c":pg.K_c, "d":pg.K_d, "e":pg.K_e, "f":pg.K_f,
"g":pg.K_g, "h":pg.K_h, "i":pg.K_i, "j":pg.K_j, "k":pg.K_k, "l":pg.K_l,
"m":pg.K_m, "n":pg.K_n, "o":pg.K_o, "p":pg.K_p, "q":pg.K_q, "r":pg.K_r,
"s":pg.K_s, "t":pg.K_t, "u":pg.K_u, "v":pg.K_v, "w":pg.K_w, "x":pg.K_x,
"y":pg.K_y, "z":pg.K_z}
while gameOn:
for event in pygame.event.get():
if event.type == pg.QUIT:
gameOn = False
if event.type == pg.KEYDOWN:
if event.key == keyCombination[contents[curIdx].lower()]:
#Here is where the color of the current letter should change
curIdx += 1
pg.quit()
You can't change the color of a single letter during font rendering; you'll have to render your text letter by letter.
You can either use render() to render each letter to its own surface and blit them to your screen, but you have to calculate where each letter should go manually.
It's a little bit easier if you use the new freetype module, which has a lot of handy functions in the Font class like origin, get_rect and get_metrics which can calculate how big each letter is.
Here's a simple example I hacked together. It's not perfect but you'll get the idea.
import pygame
import pygame.freetype
from itertools import cycle
def main():
pygame.init()
screen = pygame.display.set_mode((800, 600))
# just some demo data for you to type
data = cycle(['This is an example.', 'This is another, longer sentence.'])
current = next(data)
current_idx = 0 # points to the current letter, as you have already guessed
font = pygame.freetype.Font(None, 50)
# the font in the new freetype module have an origin property.
# if you set this to True, the render functions take the dest position
# to be that of the text origin, as opposed to the top-left corner
# of the bounding box
font.origin = True
font_height = font.get_sized_height()
# we want to know how much space each letter takes during rendering.
# the item at index 4 is the 'horizontal_advance_x'
M_ADV_X = 4
# let's calculate how big the entire line of text is
text_surf_rect = font.get_rect(current)
# in this rect, the y property is the baseline
# we use since we use the origin mode
baseline = text_surf_rect.y
# now let's create a surface to render the text on
# and center it on the screen
text_surf = pygame.Surface(text_surf_rect.size)
text_surf_rect.center = screen.get_rect().center
# calculate the width (and other stuff) for each letter of the text
metrics = font.get_metrics(current)
while True:
events = pygame.event.get()
for e in events:
if e.type == pygame.QUIT:
return
if e.type == pygame.KEYDOWN:
if e.unicode == current[current_idx].lower():
# if we press the correct letter, move the index
current_idx += 1
if current_idx >= len(current):
# if the sentence is complete, let's prepare the
# next surface
current_idx = 0
current = next(data)
text_surf_rect = font.get_rect(current)
baseline = text_surf_rect.y
text_surf = pygame.Surface(text_surf_rect.size)
text_surf_rect.center = screen.get_rect().center
metrics = font.get_metrics(current)
# clear everything
screen.fill('white')
text_surf.fill('white')
x = 0
# render each letter of the current sentence one by one
for (idx, (letter, metric)) in enumerate(zip(current, metrics)):
# select the right color
if idx == current_idx:
color = 'lightblue'
elif idx < current_idx:
color = 'lightgrey'
else:
color = 'black'
# render the single letter
font.render_to(text_surf, (x, baseline), letter, color)
# and move the start position
x += metric[M_ADV_X]
screen.blit(text_surf, text_surf_rect)
pygame.display.flip()
if __name__ == '__main__':
main()
Centering the text is easy using a second Surface and using the Rect class' center property.
Okay, I'am trying to create a Tom and Jerry game with the pygame library.
The game focuses on catching mice by clicking on them as they appear in their holes. The problem
is that sometimes a cat appears instead of a mouse and should the player erroneously click on the
cat (s)he looses all earned points, but the game continues.
The mouse is an image of a mouse and the cat is an image of an cat.
If you click on the mouse, you get mouse, otherwise the cat gets the points.
The code is a mess, that's because I don't know what I'am doing and just set an another event loop because then it works, because it runs after I create the mouse. It works to click on the mouse but then you click somewhere else and after that it's like you did not clicked on the mouse.
The mouse is created in a loop and is supposed to wait for 5 seconds and if you click on the mouse within these seconds then an appropriate message prints out in the console ,,Jerry clicked!" else "1 click". If you don't click on the mouse within 5 seconds a image covers the mouse so she disappears.
Now, what I'am trying to do right now is to print the message 1 click when the player does not click on anything but print 1 click jerry clicked when the player clicks on the mouse. I have a image of the mousehole and then I put the mouse on the mousehole, that is, on an another image.
This code works with one image at least:
pygame.init()
width=350;
height=400
screen = pygame.display.set_mode( (width, height ) )
pygame.display.set_caption('clicked on image')
redSquare = pygame.image.load("images/red-square.png").convert()
x = 20; # x coordnate of image
y = 30; # y coordinate of image
screen.blit(redSquare , ( x,y)) # paint to screen
pygame.display.flip() # paint screen one time
running = True
while (running):
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
# Set the x, y postions of the mouse click
x, y = event.pos
if redSquare.get_rect().collidepoint(x, y):
print('clicked on image')
#loop over, quite pygame
pygame.quit()
My problem is that, when I click on the mouse and then I don't click on the mouse I can't click on the mouse again at another position.
So what's wrong? What I'am doing wrong here?
Here is my code:
import pygame
from pygame import *
from random import *
init()
run = True
screen = (800,800)
screen = display.set_mode(screen)
xpos = 0
ypos = 0
mouseorcatxpos = 5
mouseorcatypos = 0
mousehole = image.load("mousehole.png").convert()
cat = image.load("tom.png")
jerry = image.load("jerry.png")
def makeholes():
global ypos
global xpos
for holey in range(1,9):
for holex in range(1,9):
screen.blit(mousehole,(xpos,ypos))
display.flip()
xpos += 100
ypos += 100
xpos = 0
def mouseorcat():
global xpos
mouseorcatxpos = 5
ypos = 0
for mousecaty in range(1,9):
pygame.event.pump()
for mousecatx in range(1,9):
randommouse = randint(1, 3)
randomcat = randint(1, 10)
if(randommouse == 2):
screen.blit(jerry, (mouseorcatxpos, ypos))
display.flip()
for event in pygame.event.get():
if (event.type == MOUSEBUTTONDOWN):
if jerry.get_rect().collidepoint(xpos, ypos) == False:
print("l clicked!")
x, y = event.pos
if jerry.get_rect().collidepoint(xpos, y):
print("JERRY CLICKED!!")
x, y = event.pos
print(x, y)
time.wait(5000)
#screen.blit(mousehole, (mouseorcatxpos - 5, ypos))
display.flip()
elif(randomcat == 2):
screen.blit(cat, (mouseorcatxpos, ypos))
display.flip()
time.wait(1500)
screen.blit(mousehole, (mouseorcatxpos-5, ypos))
display.flip()
mouseorcatxpos += 100
mouseorcatxpos = 0
ypos += 100
makeholes()
while run == True:
for event in pygame.event.get():
mouseorcat()
if event.type == QUIT:
run = False
I rewrote your game to show you how I would do it.
To keep track of the time and to limit the framerate I used a pygame.time.Clock and a timer variable. The clock returns the time in milliseconds since clock.tick was called the last time, which is used to increase the timer variable. The cat just replaces the mouse after two seconds and the mouse is set to a new position. I use pygame.Rects to store the positions, but you could also use lists or tuples.
import sys
import random
import pygame
pygame.init()
size = (800, 800)
screen = pygame.display.set_mode(size)
# Images replaced by pygame.Surface. Do that too
# in the future before you post your code.
mousehole = pygame.Surface((40, 40)).convert()
mousehole.fill(pygame.Color(30, 30, 30))
cat = pygame.Surface((40, 40)).convert()
cat.fill(pygame.Color(110, 110, 130))
jerry = pygame.Surface((40, 40)).convert()
jerry.fill(pygame.Color(190, 130, 0))
# Create the background image and blit the holes.
background = pygame.Surface(size).convert()
for holey in range(8):
for holex in range(8):
background.blit(mousehole, (holex*100, holey*100))
def new_position():
"""Return a random position between 0-700 in steps of 100."""
return (random.randrange(0, 701, 100), random.randrange(0, 701, 100))
def main():
fps = 30
clock = pygame.time.Clock()
jerry_rect = jerry.get_rect() # Stores jerry's position and size.
jerry_rect.topleft = new_position() # New random position.
# The cat is outside of the screen first.
cat_rect = cat.get_rect(topleft=(-100, -100))
points = 0
timer = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
if jerry_rect.collidepoint(event.pos):
points += 1
print('Jerry caught! Points:', points)
timer = 0
jerry_rect.topleft = new_position()
else:
print('Missed. Points:', points)
# Run logic.
timer += clock.tick(fps) / 1000 # timer + seconds since last tick.
if timer > 2: # Cat catches mouse after 2 seconds.
cat_rect.topleft = jerry_rect.topleft
jerry_rect.topleft = new_position()
timer = 0
points = 0
print('Tom caught Jerry.')
# Draw.
# Clear the screen by blitting the bg.
screen.blit(background, (0, 0))
screen.blit(jerry, jerry_rect)
screen.blit(cat, cat_rect)
pygame.display.flip()
if __name__ == '__main__':
main()
pygame.quit()
sys.exit()
Side notes:
Don't use star imports (from module import *), because that can make code harder to read. If you want you can use from pygame.locals import *, if it's the only star import.
Don't use global variables, because they can make code harder to read, understand and maintain. Pass variables to functions as arguments and then return the result.
Update: Some notes about your program:
The first big problem is that your game has two event loops and the important one is deeply nested inside of two other for loops and a if. The event loop should be directly under the main while loop (one indentation level (when you have more experience you can put it into a function or class method)).
The two for loops seem to have the purpose to let the code run until randommouse or randomcat are 2. To run code until a condition is met is the purpose of a while loop. But in this case you should better just pick a random number and write the if/elif conditions so that they always apply. For example, you want a 2/3 chance for mouse and 1/3 for a cat,
random_number = random.randint(1, 3)
if random_number < 3:
print("2/3 probability. It's a mouse")
else:
print("1/3 probability. It's a cat")
Or use random.choice with a list:
>>> random.choice(['mouse', 'mouse', 'cat'])
'mouse'
time.wait(5000) shouldn't be used because the game just hangs in this time. You can't even close the window. Limit the framerate and get the time since the last tick with a pygame.time.Clock.
pygame.event.pump() is not needed.
If you call get_rect() without an argument, the rect is positioned at (0, 0).
if jerry.get_rect().collidepoint(xpos, y):
That's the reason why clicking on jerry only works in the top row, and because you use the global xpos here. Since xpos is 0, the whole top row counts as Jerry.
You can pass coordinates to get_rect like so (you can also use center or other args instead of topleft):
jerry_rect = jerry.get_rect(topleft=(50, 100))
I'm sorry but I don't think I can simply fix your code. I've tried it several times, but I always end up re-writing it completely.
I begin by extracting the event loop out of the two nested for loops, then remove these loops, create rects for the mouse and cat, fix the collision detection, add a timer and so on. Take a close look at my example and try to rewrite your game in a similar way, and keep asking questions if you don't understand something.
I am trying to make the dialog appear one character at a time (Like in Pokemon games and other similar).
I have searched over the internet but have not managed to find anything helpful.
I am aware of another question asked like this, but it didn't solve what I am trying to do. I know this can be done because I have seen games made with python where this has been done.
import pygame, sys
from pygame.locals import *
WINDOW_WIDTH = 500
WINDOW_HEIGHT = 500
pygame.init()
DISPLAYSURF = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
def display_text_animation(string):
text = ''
for i in range(len(string)):
DISPLAYSURF.fill(WHITE)
text += string[i]
text_surface = font.render(text, True, BLACK)
text_rect = text_surface.get_rect()
text_rect.center = (WINDOW_WIDTH/2, WINDOW_HEIGHT/2)
DISPLAYSURF.blit(text_surface, text_rect)
pygame.display.update()
pygame.time.wait(100)
def main():
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
display_text_animation('Hello World!')
main()
NOTE: I haven't used pygame before so this may not work.
The below works very well. And stops any overloading of the event queue (so multiple lines or lots of text don't stall the animation). This is necessary if embedded in a simple application that doesn't handle the event queue in some other way.
line_space = 16
basicfont = pygame.font.SysFont('MorePerfectDOSVGA', 16)
def text_ani(str, tuple):
x, y = tuple
y = y*line_space ##shift text down by one line
char = '' ##new string that will take text one char at a time. Not the best variable name I know.
letter = 0
count = 0
for i in range(len(str)):
pygame.event.clear() ## this is very important if your event queue is not handled properly elsewhere. Alternativly pygame.event.pump() would work.
time.sleep(0.05) ##change this for faster or slower text animation
char = char + str[letter]
text = basicfont.render(char, False, (2, 241, 16), (0, 0, 0)) #First tuple is text color, second tuple is background color
textrect = text.get_rect(topleft=(x, y)) ## x, y's provided in function call. y coordinate amended by line height where needed
screen.blit(text, textrect)
pygame.display.update(textrect) ## update only the text just added without removing previous lines.
count += 1
letter += 1
print char ## for debugging in console, comment out or delete.
text_ani('this is line number 1 ', (0, 1)) # text string and x, y coordinate tuple.
text_ani('this is line number 2', (0, 2))
text_ani('this is line number 3', (0, 3))
text_ani('', (0, 3)) # this is a blank line
This is a bit more simplistic, it creates a function which you can use whenever you want. In this example I called my function 'slow' and made it so that you need to input a string when calling it. Whatever is inputted will display character by character. The speed depends on the value near 'sleep'. Hope this helped.
from time import * #imports all the time functions
def slow(text): #function which displays characters one at a time
for letters in text: #the variable goes through each character at a time
print(letters, end = "") #current character is printed
sleep(0.02) #insert the time between each character shown
#the for loop will move onto the next character
slow("insert text here") #instead of print, use the name of the function
If you run this as it is, it should output "insert text here" one character at a time.
I wrote an application in pygame to display some text. The text consist of a counter which is updated every second or so. I am using raspberry pi for this application. So when I use xserver then everything is displayed correctly but if I use sdl_videodriver fbcon for display then static text is displayed correctly but the counter(text) whose value changes is not displayed correctly. The new value of counter is displayed over the older value and thus after few seconds it becomes unreadable. Following is my code
class pyscope :
def __init__(self):
disp_no = os.getenv("DISPLAY")
if disp_no:
print "I'm running under X display = {0}".format(disp_no)
drivers = ['fbcon', 'directfb', 'svgalib']
found = False
for driver in drivers:
if not os.getenv('SDL_VIDEODRIVER'):
os.putenv('SDL_VIDEODRIVER', driver)
try:
pygame.display.init()
except pygame.error:
print 'Driver: {0} failed.'.format(driver)
continue
found = True
break
if not found:
raise Exception('No suitable video driver found!')
size = [1920,1080]
self.screen = pygame.display.set_mode(size,pygame.FULLSCREEN)
self.screen.fill((0,0,0))
pygame.font.init()
pygame.display.update()
def __del__(self):
"Destructor to make sure pygame shuts down, etc."
def test(self):
pygame.display.set_caption("Test")
done=False
clock=pygame.time.Clock()
font = pygame.font.SysFont("consolas", 34, True)
frame_rate = 20
count = 0
while done==False:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done=True
high_score = 2270
plan = 2100
count = count + 1
font = pygame.font.SysFont("consolas", 200, True)
if count >100:
count = 12
output_string = "ACTUAL %s" %count
text = font.render(output_string,True,red)
pygame.display.flip()
self.screen.blit(text, [250,420])
output1 = "random %.2f" %(float(count)/100*100)
text = font.render(output1,True,red)
self.screen.blit(text, [250,540])
pygame.display.flip()
clock.tick(20)
pygame.display.flip()
scope = pyscope()
scope.test()
time.sleep(10)
Thus my question how can I avoid new text being rendered over older text while using sdl_videodriver?
It is not enough to update() the screen, you should also "clear" it with a color. Before any blitting/drawing, do:
self.screen.fill((0,0,0))
You currently only do this once, when initializing the application. This should be done on each frame, if you want to keep a fresh, new screen on each frame.
It sounds like pygame is not clearing the area of the text counter.
Since I don't have access to an raspberry pi I would suggest you to
make sure you clear/update the area where the counter is rendered.
Before blitting out the text, you could clear the screen area with pygame.draw.rect
pygame.draw.rect(self.screen,(0,0,0),text.get_rect())
Should work OK, as long as your background is a solid color.
I'm a new programmer working on a memory game for my computer science summative.The game goes like this: the computer displays random boxes at random positions and then the user has to guess where the boxes are and click on it.
I'm basically done, except right now I'm trying to create 5 different levels that range in level of difficulty. eg level 1 will display 2 boxes and level 2 will display 5, etc. And then if the user gets through all levels they can play again. I know its a lot but I really want to get an A on this.
But right now I'm stuck because it doesn't really work until I try to close the window, and even then it only goes halfway. Any help would be appreciated.
import pygame , sys
import random
import time
size=[500,500]
pygame.init()
screen=pygame.display.set_mode(size)
# Colours
LIME = (0,255,0)
RED = (255, 0, 0)
BLACK = (0,0,0)
PINK = (255,102,178)
SALMON = (255,192,203)
WHITE = (255,255,255)
LIGHT_PINK = (255, 181, 197)
SKY_BLUE = (176, 226, 255)
screen.fill(BLACK)
# Width and Height of game box
width=50
height=50
# Margin between each cell
margin = 5
rows = 20
columns = 20
# Set title of screen
pygame.display.set_caption("Spatial Recall")
# Used to manage how fast the screen updates
clock=pygame.time.Clock()
coord=[]
# Create a 2 dimensional array. A two dimesional
# array is simply a list of lists.
def resetGrid():
grid = []
for row in range(rows):
# Add an empty array that will hold each cell
# in this row
grid.append([])
for column in range(columns):
grid[row].append(0) # Append a cell
return grid
def displayAllPink(pygame):
for row in range(rows):
for column in range(columns):
color = LIGHT_PINK
pygame.draw.rect(screen,color,[(margin+width)*column + margin,(margin+height)*row+margin,width,height])
pygame.display.flip()
def displayOtherColor(pygame,grid):
coord = []
for i in range(random.randint(2,5)):
x = random.randint(2, rows-1)
y = random.randint(2, columns-1)
color = LIME
pygame.draw.rect(screen,color,[(margin+width)*y + margin,(margin+height)*x+margin,width,height])
coord.append((x,y))
grid[x][y] = 1
pygame.display.flip()
time.sleep(1)
return coord
def runGame(gameCount,coord,pygame,grid):
pygame.event.clear()
pygame.display.set_caption("Spatial Recall: Level "+ str(gameCount))
pygame.time.set_timer(pygame.USEREVENT,1000)
time = 0
#clock.tick(
# -------- Main Program Loop -----------
#Loop until the user clicks the close button.
done = False
while done==False:
event = pygame.event.wait() # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loop
pygame.event.clear()
print "Game ",gameCount, "ends"
elif event.type == pygame.USEREVENT:
time = time + 1
pygame.display.set_caption("Spatial Recall: Level "+ str(gameCount) + " Time: "+ str(time))
if time == 100:
done = True
pygame.display.set_caption("Time out, moving to next level")
pygame.event.clear()
return False
elif event.type == pygame.MOUSEBUTTONDOWN:
# User clicks the mouse. Get the position
pos = pygame.mouse.get_pos()
# Change the x/y screen coordinates to grid coordinates
column=pos[0] // (width+margin)
row=pos[1] // (height+margin)
if (row,column) in coord:
print coord
coord.remove((row,column))
print coord
color = LIME
pygame.draw.rect(screen,color,[(margin+width)*column + margin,(margin+height)*row+margin,width,height])
if coord == []:
done=True
pygame.display.set_caption("Time out, moving to next level")
pygame.event.clear()
return True
else:
color = RED
pygame.draw.rect(screen,color,[(margin+width)*column + margin,(margin+height)*row+margin,width,height])
pygame.display.flip()
def startTheGame(gameCount):
grid = resetGrid()
displayAllPink(pygame)
coord = displayOtherColor(pygame,grid)
displayAllPink(pygame)
runGame(gameCount,coord,pygame,grid)
for i in range(2):
startTheGame(i+1)
pygame.quit ()
You may want to use the pygame.font module. http://pygame.org/docs/ref/font.html
First, load a font, either from a file or from one of the system font functions.
Call YourFontObject.render(your_text_string). That'll return a Surface that contains the string rendered in the given font. Note, you can't use newline (\n) characters! You'll have to do the spacing yourself.
Blit this Surface onto the screen after everything else so nothing will obscure it.
Also, you don't need the pygame parameter in your functions.
Hope this helps.