python 实现"神经衰弱"翻牌游戏


Posted in Python onNovember 09, 2020

"神经衰弱"翻牌游戏考察玩家的记忆力,游戏的开头会短时间给你看一小部分牌的图案,当玩家翻开两张相同图案牌的时候,会消除,和你的小伙伴比一比谁用时更短把。

源代码

import random, pygame, sys
from pygame.locals import *

FPS = 30 # frames per second, the general speed of the program
WINDOWWIDTH = 640 # size of window's width in pixels
WINDOWHEIGHT = 480 # size of windows' height in pixels
REVEALSPEED = 8 # speed boxes' sliding reveals and covers
BOXSIZE = 40 # size of box height & width in pixels
GAPSIZE = 10 # size of gap between boxes in pixels
BOARDWIDTH = 10 # number of columns of icons
BOARDHEIGHT = 7 # number of rows of icons
assert (BOARDWIDTH * BOARDHEIGHT) % 2 == 0, 'Board needs to have an even number of boxes for pairs of matches.'
XMARGIN = int((WINDOWWIDTH - (BOARDWIDTH * (BOXSIZE + GAPSIZE))) / 2)
YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE))) / 2)

#      R  G  B
GRAY   = (100, 100, 100)
NAVYBLUE = ( 60, 60, 100)
WHITE  = (255, 255, 255)
RED   = (255,  0,  0)
GREEN  = ( 0, 255,  0)
BLUE   = ( 0,  0, 255)
YELLOW  = (255, 255,  0)
ORANGE  = (255, 128,  0)
PURPLE  = (255,  0, 255)
CYAN   = ( 0, 255, 255)

BGCOLOR = NAVYBLUE
LIGHTBGCOLOR = GRAY
BOXCOLOR = WHITE
HIGHLIGHTCOLOR = BLUE

DONUT = 'donut'
SQUARE = 'square'
DIAMOND = 'diamond'
LINES = 'lines'
OVAL = 'oval'

ALLCOLORS = (RED, GREEN, BLUE, YELLOW, ORANGE, PURPLE, CYAN)
ALLSHAPES = (DONUT, SQUARE, DIAMOND, LINES, OVAL)
assert len(ALLCOLORS) * len(ALLSHAPES) * 2 >= BOARDWIDTH * BOARDHEIGHT, "Board is too big for the number of shapes/colors defined."

def main():
  global FPSCLOCK, DISPLAYSURF
  pygame.init()
  FPSCLOCK = pygame.time.Clock()
  DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))

  mousex = 0 # used to store x coordinate of mouse event
  mousey = 0 # used to store y coordinate of mouse event
  pygame.display.set_caption('Memory Game')

  mainBoard = getRandomizedBoard()
  revealedBoxes = generateRevealedBoxesData(False)

  firstSelection = None # stores the (x, y) of the first box clicked.

  DISPLAYSURF.fill(BGCOLOR)
  startGameAnimation(mainBoard)

  while True: # main game loop
    mouseClicked = False

    DISPLAYSURF.fill(BGCOLOR) # drawing the window
    drawBoard(mainBoard, revealedBoxes)

    for event in pygame.event.get(): # event handling loop
      if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
        pygame.quit()
        sys.exit()
      elif event.type == MOUSEMOTION:
        mousex, mousey = event.pos
      elif event.type == MOUSEBUTTONUP:
        mousex, mousey = event.pos
        mouseClicked = True

    boxx, boxy = getBoxAtPixel(mousex, mousey)
    if boxx != None and boxy != None:
      # The mouse is currently over a box.
      if not revealedBoxes[boxx][boxy]:
        drawHighlightBox(boxx, boxy)
      if not revealedBoxes[boxx][boxy] and mouseClicked:
        revealBoxesAnimation(mainBoard, [(boxx, boxy)])
        revealedBoxes[boxx][boxy] = True # set the box as "revealed"
        if firstSelection == None: # the current box was the first box clicked
          firstSelection = (boxx, boxy)
        else: # the current box was the second box clicked
          # Check if there is a match between the two icons.
          icon1shape, icon1color = getShapeAndColor(mainBoard, firstSelection[0], firstSelection[1])
          icon2shape, icon2color = getShapeAndColor(mainBoard, boxx, boxy)

          if icon1shape != icon2shape or icon1color != icon2color:
            # Icons don't match. Re-cover up both selections.
            pygame.time.wait(1000) # 1000 milliseconds = 1 sec
            coverBoxesAnimation(mainBoard, [(firstSelection[0], firstSelection[1]), (boxx, boxy)])
            revealedBoxes[firstSelection[0]][firstSelection[1]] = False
            revealedBoxes[boxx][boxy] = False
          elif hasWon(revealedBoxes): # check if all pairs found
            gameWonAnimation(mainBoard)
            pygame.time.wait(2000)

            # Reset the board
            mainBoard = getRandomizedBoard()
            revealedBoxes = generateRevealedBoxesData(False)

            # Show the fully unrevealed board for a second.
            drawBoard(mainBoard, revealedBoxes)
            pygame.display.update()
            pygame.time.wait(1000)

            # Replay the start game animation.
            startGameAnimation(mainBoard)
          firstSelection = None # reset firstSelection variable

    # Redraw the screen and wait a clock tick.
    pygame.display.update()
    FPSCLOCK.tick(FPS)


def generateRevealedBoxesData(val):
  revealedBoxes = []
  for i in range(BOARDWIDTH):
    revealedBoxes.append([val] * BOARDHEIGHT)
  return revealedBoxes


def getRandomizedBoard():
  # Get a list of every possible shape in every possible color.
  icons = []
  for color in ALLCOLORS:
    for shape in ALLSHAPES:
      icons.append( (shape, color) )

  random.shuffle(icons) # randomize the order of the icons list
  numIconsUsed = int(BOARDWIDTH * BOARDHEIGHT / 2) # calculate how many icons are needed
  icons = icons[:numIconsUsed] * 2 # make two of each
  random.shuffle(icons)

  # Create the board data structure, with randomly placed icons.
  board = []
  for x in range(BOARDWIDTH):
    column = []
    for y in range(BOARDHEIGHT):
      column.append(icons[0])
      del icons[0] # remove the icons as we assign them
    board.append(column)
  return board


def splitIntoGroupsOf(groupSize, theList):
  # splits a list into a list of lists, where the inner lists have at
  # most groupSize number of items.
  result = []
  for i in range(0, len(theList), groupSize):
    result.append(theList[i:i + groupSize])
  return result


def leftTopCoordsOfBox(boxx, boxy):
  # Convert board coordinates to pixel coordinates
  left = boxx * (BOXSIZE + GAPSIZE) + XMARGIN
  top = boxy * (BOXSIZE + GAPSIZE) + YMARGIN
  return (left, top)


def getBoxAtPixel(x, y):
  for boxx in range(BOARDWIDTH):
    for boxy in range(BOARDHEIGHT):
      left, top = leftTopCoordsOfBox(boxx, boxy)
      boxRect = pygame.Rect(left, top, BOXSIZE, BOXSIZE)
      if boxRect.collidepoint(x, y):
        return (boxx, boxy)
  return (None, None)


def drawIcon(shape, color, boxx, boxy):
  quarter = int(BOXSIZE * 0.25) # syntactic sugar
  half =  int(BOXSIZE * 0.5) # syntactic sugar

  left, top = leftTopCoordsOfBox(boxx, boxy) # get pixel coords from board coords
  # Draw the shapes
  if shape == DONUT:
    pygame.draw.circle(DISPLAYSURF, color, (left + half, top + half), half - 5)
    pygame.draw.circle(DISPLAYSURF, BGCOLOR, (left + half, top + half), quarter - 5)
  elif shape == SQUARE:
    pygame.draw.rect(DISPLAYSURF, color, (left + quarter, top + quarter, BOXSIZE - half, BOXSIZE - half))
  elif shape == DIAMOND:
    pygame.draw.polygon(DISPLAYSURF, color, ((left + half, top), (left + BOXSIZE - 1, top + half), (left + half, top + BOXSIZE - 1), (left, top + half)))
  elif shape == LINES:
    for i in range(0, BOXSIZE, 4):
      pygame.draw.line(DISPLAYSURF, color, (left, top + i), (left + i, top))
      pygame.draw.line(DISPLAYSURF, color, (left + i, top + BOXSIZE - 1), (left + BOXSIZE - 1, top + i))
  elif shape == OVAL:
    pygame.draw.ellipse(DISPLAYSURF, color, (left, top + quarter, BOXSIZE, half))


def getShapeAndColor(board, boxx, boxy):
  # shape value for x, y spot is stored in board[x][y][0]
  # color value for x, y spot is stored in board[x][y][1]
  return board[boxx][boxy][0], board[boxx][boxy][1]


def drawBoxCovers(board, boxes, coverage):
  # Draws boxes being covered/revealed. "boxes" is a list
  # of two-item lists, which have the x & y spot of the box.
  for box in boxes:
    left, top = leftTopCoordsOfBox(box[0], box[1])
    pygame.draw.rect(DISPLAYSURF, BGCOLOR, (left, top, BOXSIZE, BOXSIZE))
    shape, color = getShapeAndColor(board, box[0], box[1])
    drawIcon(shape, color, box[0], box[1])
    if coverage > 0: # only draw the cover if there is an coverage
      pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, coverage, BOXSIZE))
  pygame.display.update()
  FPSCLOCK.tick(FPS)


def revealBoxesAnimation(board, boxesToReveal):
  # Do the "box reveal" animation.
  for coverage in range(BOXSIZE, (-REVEALSPEED) - 1, -REVEALSPEED):
    drawBoxCovers(board, boxesToReveal, coverage)


def coverBoxesAnimation(board, boxesToCover):
  # Do the "box cover" animation.
  for coverage in range(0, BOXSIZE + REVEALSPEED, REVEALSPEED):
    drawBoxCovers(board, boxesToCover, coverage)


def drawBoard(board, revealed):
  # Draws all of the boxes in their covered or revealed state.
  for boxx in range(BOARDWIDTH):
    for boxy in range(BOARDHEIGHT):
      left, top = leftTopCoordsOfBox(boxx, boxy)
      if not revealed[boxx][boxy]:
        # Draw a covered box.
        pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, BOXSIZE, BOXSIZE))
      else:
        # Draw the (revealed) icon.
        shape, color = getShapeAndColor(board, boxx, boxy)
        drawIcon(shape, color, boxx, boxy)


def drawHighlightBox(boxx, boxy):
  left, top = leftTopCoordsOfBox(boxx, boxy)
  pygame.draw.rect(DISPLAYSURF, HIGHLIGHTCOLOR, (left - 5, top - 5, BOXSIZE + 10, BOXSIZE + 10), 4)


def startGameAnimation(board):
  # Randomly reveal the boxes 8 at a time.
  coveredBoxes = generateRevealedBoxesData(False)
  boxes = []
  for x in range(BOARDWIDTH):
    for y in range(BOARDHEIGHT):
      boxes.append( (x, y) )
  random.shuffle(boxes)
  boxGroups = splitIntoGroupsOf(8, boxes)

  drawBoard(board, coveredBoxes)
  for boxGroup in boxGroups:
    revealBoxesAnimation(board, boxGroup)
    coverBoxesAnimation(board, boxGroup)


def gameWonAnimation(board):
  # flash the background color when the player has won
  coveredBoxes = generateRevealedBoxesData(True)
  color1 = LIGHTBGCOLOR
  color2 = BGCOLOR

  for i in range(13):
    color1, color2 = color2, color1 # swap colors
    DISPLAYSURF.fill(color1)
    drawBoard(board, coveredBoxes)
    pygame.display.update()
    pygame.time.wait(300)


def hasWon(revealedBoxes):
  # Returns True if all the boxes have been revealed, otherwise False
  for i in revealedBoxes:
    if False in i:
      return False # return False if any boxes are covered.
  return True


if __name__ == '__main__':
  main()

运行效果:

python 实现"神经衰弱"翻牌游戏

以上就是python 实现"神经衰弱"翻牌游戏的详细内容,更多关于python "神经衰弱"翻牌游戏的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
pyqt4教程之实现windows窗口小示例分享
Mar 07 Python
Python实现一个简单的MySQL类
Jan 07 Python
在Python程序和Flask框架中使用SQLAlchemy的教程
Jun 06 Python
解决python3 网络请求路径包含中文的问题
May 10 Python
python虚拟环境迁移方法
Jan 03 Python
在Python 不同级目录之间模块的调用方法
Jan 19 Python
python 利用pandas将arff文件转csv文件的方法
Feb 12 Python
Python列表的切片实例讲解
Aug 20 Python
python实现的读取网页并分词功能示例
Oct 29 Python
python爬取本站电子书信息并入库的实现代码
Jan 20 Python
python实现飞船游戏的纵向移动
Apr 24 Python
Python容器类型公共方法总结
Aug 19 Python
Python字典dict常用方法函数实例
Nov 09 #Python
Python实现哲学家就餐问题实例代码
Nov 09 #Python
使用Python实现NBA球员数据查询小程序功能
Nov 09 #Python
Python暴力破解Mysql数据的示例
Nov 09 #Python
python 实现一个图形界面的汇率计算器
Nov 09 #Python
python 读取串口数据的示例
Nov 09 #Python
Cpython解释器中的GIL全局解释器锁
Nov 09 #Python
You might like
图解上海144收音机
2021/03/02 无线电
PHP数组及条件,循环语句学习
2012/11/11 PHP
PHP实现更新中间关联表数据的两种方法
2014/09/01 PHP
PHP函数积累总结
2019/03/19 PHP
layui数据表格自定义每页条数limit设置
2019/10/26 PHP
JavaScript 动态生成方法的例子
2009/07/22 Javascript
Extjs学习笔记之三 extjs form更多的表单项
2010/01/07 Javascript
自己使用jquery写的一个无缝滚动的插件
2014/04/30 Javascript
用html+css+js实现的一个简单的图片切换特效
2014/05/28 Javascript
Javascript中的高阶函数介绍
2015/03/15 Javascript
浅谈Jquery核心函数
2015/06/18 Javascript
Javascript实现获取及设置光标位置的方法
2015/07/21 Javascript
JavaScript引用类型和基本类型详解
2016/01/06 Javascript
webpack中引用jquery的简单实现
2016/06/08 Javascript
如何检测JavaScript的各种类型
2016/07/30 Javascript
微信小程序 自定义Toast实例代码
2017/06/12 Javascript
vue-cli 打包使用history模式的后端配置实例
2018/09/20 Javascript
解决node-sass偶尔安装失败的方法小结
2018/12/05 Javascript
小程序实现人脸识别功能(百度ai)
2018/12/23 Javascript
详解jQuery设置内容和属性
2019/04/11 jQuery
vue 使用element-ui中的Notification自定义按钮并实现关闭功能及如何处理多个通知
2019/08/17 Javascript
js实现图片区域可点击大小随意改变(适用移动端)代码实例
2019/09/11 Javascript
JS实现普通轮播图特效
2020/01/01 Javascript
小程序实现背景音乐播放和暂停
2020/06/19 Javascript
Python处理XML格式数据的方法详解
2017/03/21 Python
Python实现多并发访问网站功能示例
2017/06/19 Python
详解python里使用正则表达式的全匹配功能
2017/10/19 Python
Python键盘输入转换为列表的实例
2018/06/23 Python
python发送多人邮件没有展示收件人问题的解决方法
2019/06/21 Python
css3圆角样式分享自定义按钮样式
2013/12/27 HTML / CSS
大学生自我鉴定范文模板
2014/01/21 职场文书
二手房购房意向书范本
2014/04/01 职场文书
2014年学雷锋活动总结
2014/06/26 职场文书
公司人事管理制度
2015/08/05 职场文书
怎样写工作总结啊!
2019/06/18 职场文书
tree shaking对打包体积优化及作用
2022/07/07 Java/Android