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

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

源代码

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 "神经衰弱"翻牌游戏的资料请关注我们其它相关文章!

(0)

相关推荐

  • Python tkinter制作单机五子棋游戏

    本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 以下文章来源于Python家庭,作者Python家庭 实战项目:使用Python编写一个能够完成基本对战的五子棋游戏.面向新手. 程序主要包括两个部分,图形创建与逻辑编写两部分. 程序的运行结果: 样式创建 老规矩,先把用到的包导入进来. from tkinter import * import math 然后建立一个样式的类,类名称chessBoard.这里加了很多注释,避免

  • python实现简单贪吃蛇游戏

    本文实例为大家分享了python实现贪吃蛇游戏的具体代码,供大家参考,具体内容如下 代码: from turtle import * from random import randrange from time import sleep ### 定义变量 snake = [[0,0],[10,0],[20,0],[30,0],[40,0],[50,0]] apple_x = randrange(-20,20)*10 apple_y = randrange(-20,20)*10 aim_x = 1

  • 详解python百行有效代码实现汉诺塔小游戏(简约版)

    直接上代码: #左中右塔用一个列表存储 left = list() center = list() right = list() """ 初始化函数 """ def init(): size = input("(请友善输入整数,未写判断!)请输入层数:") #初始化塔列表,如5层 左边塔放 1-3-5-7-9,中间和右边放5个-1 for i in range(1,int(size) + 1): left.append(i*2

  • Python使用tkinter实现摇骰子小游戏功能的代码

    TKinter Python 的 GUI 库非常多,之所以选择 Tkinter,一是最为简单,二是自带库,不需下载安装,随时使用,跨平台兼容性非常好,三则是从需求出发的,Python 在实际应用中极少用于开发复杂的桌面应用,毕竟,Python 的各种 GUI 工具包都"一般得很",不具备优势. 贴吧看到的一个求助题,大致需求是:3个人摇骰子,每人摇3次,点数之和最大的获胜,支持玩家名称输入.我觉得这个题目挺有意思的,做了个界面程序,欢迎大家交流指正~ #!usr/bin/env pyt

  • python实现数字炸弹游戏

    Python–数字炸弹游戏,供大家参考,具体内容如下 数字炸弹游戏规则: 在一个数字范围内,有一个数字作为炸弹,谁猜中这个炸弹就被惩罚.比如范围是1~99, 炸弹是60,然后猜了一个数字是30,30不是炸弹,那么现在猜数字的范围就缩小到30~100, 又猜了一个数字80,80也不是炸弹,那么现在又缩小范围到30~80,每次猜不能猜边界上的值, 直到你或电脑猜中这个炸弹,然后就会受到惩罚,游戏结束 要求:你先输入一个数如果不是炸弹,然后让电脑缩小范围输入一个数字,如果还不是炸弹你再次缩小范围输入,

  • python实现移动木板小游戏

    本文实例为大家分享了python实现移动木板小游戏的具体代码,供大家参考,具体内容如下 一.游戏简介 本游戏是通过python编写的小游戏,给初学者熟悉python编程语言抛砖引玉,希望有所帮助. 成型的效果图如下: 二.编写步骤 1.引入库 代码如下: ###### AUTHOR:破茧狂龙 ###### ###### DATE:20201002 ###### ###### DESCRIPTION:移动的木板 ###### import pygame from pygame.locals imp

  • python实现简单的五子棋游戏

    本文实例为大家分享了python实现五子棋游戏的具体代码,供大家参考,具体内容如下 # -*- coding:utf-8 -*- # @Time: 2017/8/29 0029 10:14 # @Author: assasin # @Email: assasin0308@sina.com from tkinter import * import math class chessBoard(): def __init__(self): # 创建一个tk对象,窗口 self.window = Tk(

  • python实现数字炸弹游戏程序

    相信许多小伙伴都玩过数字炸弹游戏,就是指在一定数字范围(一般是整数,不包含边界)里,一个玩家选中一个数字当作炸弹,其余玩家在这个范围猜数字,每次只要没猜中炸弹数字,则根据玩家猜的数字缩小范围,直至其中一个玩家猜中炸弹数字,游戏结束. 在这里,我们可以尝试用Python编程的思想来拆解游戏过程(纯属无聊),核心主要为以下两个问题: (1)数字炸弹的产生 (2)如何缩小范围 第一个问题很简单,可以使用random模块随机生成,需要注意的是数字炸弹不包含边界,randint函数可以生成指定范围的整数,

  • Python中猜拳游戏与猜筛子游戏的实现方法

    猜拳游戏 import random player_input=input("请输入(0剪刀,1石头,2布):") player=int(player_input) computer=random.randint(0,2) if(player==0 and computer==2) or (player==1 and computer==0) or (player==2 and computer==1): print("电脑出的是%s,恭喜,你赢了!"%comput

  • python求解汉诺塔游戏

    本文实例为大家分享了python求解汉诺塔游戏的具体代码,供大家参考,具体内容如下 一.问题定义 百度百科定义:汉诺塔(又称河内塔)问题是源于印度一个古老传说的益智玩具.据说大梵天创造世界的时候做了三根金刚石柱子,在一根柱子上从下往上按照从小到大顺序摞着64片黄金圆盘.大梵天命令婆罗门借助其中一根柱子,把64片黄金圆盘重新摆放到第三个根柱子上.并且规定,在小黄金圆盘上不能放大的黄金圆盘,在三根柱子之间一次只能移动一个圆盘. 例如,如果黄金圆盘只有3片,则为了满足游戏规则,那么必须按照如下图所示的

  • python实现猜数游戏(保存游戏记录)

    本文实例为大家分享了python实现猜数游戏的具体代码,供大家参考,具体内容如下 内容如下: ①游戏可以重复进行,每当一个用户结束后,程序会提示是否还要继续,输入y继续,输入其他的字符退出: ②增加玩家姓名,并对该玩家的成绩进行记录,并存储在new.txt文件中: ③增加文件读取功能,即每次程序启动,都首先读取new.txt文件,并给出之前玩家的最高成绩和姓名.(当最高成绩重叠时,取最新记录) import random import os if os.path.exists("D:\\new.

随机推荐