Pygame code to show how to make a grid and display the grid position as the mouse pointer moves over it.
The start of a battleship game perhaps?
'
'''pg_mouse_grid_position1.py
draw a grid with PyGame and show grid_position of
the grid the mouse is pointing to
exploring the Python module pygame
pygame free from: http://www.pygame.org/
or: http://www.lfd.uci.edu/~gohlke/pythonlibs/
pygame is available for Python27 or Python32
'''
import pygame as pg
import os
# this will center the pygame window on the display screen
os.environ['SDL_VIDEO_CENTERED'] = '1'
pg.init()
class Grid:
def __init__(self,size):
self.size = size
self.font = pg.font.Font(None, 24)
self.pos = [0,0]
self.rend = self.font.render("{0}, {1}".format(*self.pos),
1,(0,100,0))
def draw(self, surface):
w, h = self.size
for ww in range(w, 800, w):
pg.draw.line(surface,(120,120,120), (ww,0), (ww,600))
for hh in range(h, 600, h):
pg.draw.line(surface,(120,120,120), (0,hh), (800,hh))
mouse = pg.mouse.get_pos()
# find mouse position
mouse = map(int,(mouse[0]/self.size[0],
mouse[1]/self.size[1]))
if mouse != self.pos:
self.pos = mouse
self.rend = self.font.render("{0}, {1}".format(*self.pos),
1,(0,200,0))
surface.blit(self.rend, (10,10))
def main():
screen = pg.display.set_mode((800,600))
title = 'move mouse pointer over grid to show the grid position'
pg.display.set_caption(title)
# needed for frame rate
clock = pg.time.Clock()
grid = Grid((50,50))
Run = True
while Run:
for event in pg.event.get():
if event.type == pg.QUIT:
Run = False
elif event.type == pg.KEYDOWN:
if event.key == pg.K_ESCAPE:
Run = False
screen.fill((0,0,0))
grid.draw(screen)
pg.display.flip()
# set frame rate
clock.tick(30)
pg.quit()
if __name__ == "__main__":
main()