pygame实现8*8的点阵,可点击小正方形变换颜色

(小舅子读研需要完成导师给的一个作业,网上没有百度到答案,就动手撸了一个)

题目要求:

在一个大正方形画布中(画布的背景是灰色),有一个正方形的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还怎么运行!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值