(小舅子读研需要完成导师给的一个作业,网上没有百度到答案,就动手撸了一个)
题目要求:
在一个大正方形画布中(画布的背景是灰色),有一个正方形的88的点阵,点阵的每一个点又是一个小正方形,当用鼠标左键点击某一小正方形时,它的颜色会切换成绿色,再点击下又恢复成黑色。你可在88点阵.上点击出你喜欢的文字和图案。采用pygame编写这个任务程序。
# Import a library of functions called 'pygame'
import pygame
from math import pi
# Initialize the game engine
pygame.init()
# Define the colors we will use in RGB format
BLACK = ( 0, 0, 0)
WHITE = (255, 255, 255)
GREEN = ( 0, 255, 0)
GREY = (190, 190, 190)
# Set the height and width of the screen
size = [400, 400]
screen = pygame.display.set_mode(size)
pygame.display.set_caption("绘图")
#blockColorDic
blockColorDic = {}
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
initScreenflag = True
#mouse click event
def mouseClik(pos):
x,y = pos
x = x - x % 50
y = y - y % 50
xyPosition = (x,y)
if blockColorDic[xyPosition]:
pygame.draw.rect(screen, GREEN, [x, y, 50, 50])
blockColorDic[xyPosition] = False
else:
pygame.draw.rect(screen, BLACK, [x, y, 50, 50])
blockColorDic[xyPosition] = True
pygame.display.update()
#init screen grey
def initScreen():
screen.fill(GREY)
x = 0
while x <= 400:
pygame.draw.line(screen, BLACK, [x, 0], [x,400], 1)
pygame.draw.line(screen, BLACK, [0, x], [400,x], 1)
y = 0
xyPosition = ()
while y <= 400:
xyPosition = (x,y)
blockColorDic[xyPosition] = True
y += 50
x += 50
# Go ahead and update the screen with what we've drawn.
# This MUST happen after all the other drawing commands.
pygame.display.flip()
while not done:
# This limits the while loop to a max of 10 times per second.
# Leave this out and we will use all CPU we can.
clock.tick(10)
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done=True # Flag that we are done so we exit this loopb
elif event.type == pygame.MOUSEBUTTONUP:# mouse click event
mouseClik(pygame.mouse.get_pos())
# set the screen background color
if initScreenflag:
initScreen()
initScreenflag = False
# Be IDLE friendly
pygame.quit()
第一次编辑的代码竟然没有缩进,那python还怎么运行!