鱼C论坛

 找回密码
 立即注册
查看: 362|回复: 13

[作品展示] 买的一个外国佬的pygame游戏,免费送给大家啦

[复制链接]
发表于 2024-1-29 16:22:40 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 某一个“天” 于 2024-1-29 19:40 编辑

请大家多多评分,如果大家喜欢 我还有更多
  1. # Memory Puzzle
  2. # Released under a "Simplified BSD" license

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

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

  16. #            R    G    B
  17. GRAY     = (100, 100, 100)
  18. NAVYBLUE = ( 60,  60, 100)
  19. WHITE    = (255, 255, 255)
  20. RED      = (255,   0,   0)
  21. GREEN    = (  0, 255,   0)
  22. BLUE     = (  0,   0, 255)
  23. YELLOW   = (255, 255,   0)
  24. ORANGE   = (255, 128,   0)
  25. PURPLE   = (255,   0, 255)
  26. CYAN     = (  0, 255, 255)

  27. BGCOLOR = NAVYBLUE
  28. LIGHTBGCOLOR = GRAY
  29. BOXCOLOR = WHITE
  30. HIGHLIGHTCOLOR = BLUE

  31. DONUT = 'donut'
  32. SQUARE = 'square'
  33. DIAMOND = 'diamond'
  34. LINES = 'lines'
  35. OVAL = 'oval'

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

  39. def main():
  40.     global FPSCLOCK, DISPLAYSURF
  41.     pygame.init()
  42.     FPSCLOCK = pygame.time.Clock()
  43.     DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))

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

  47.     mainBoard = getRandomizedBoard()
  48.     revealedBoxes = generateRevealedBoxesData(False)

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

  50.     DISPLAYSURF.fill(BGCOLOR)
  51.     startGameAnimation(mainBoard)

  52.     while True: # main game loop
  53.         mouseClicked = False

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

  56.         for event in pygame.event.get(): # event handling loop
  57.             if event.type == QUIT or (event.type == KEYUP and event.key == K_ESCAPE):
  58.                 pygame.quit()
  59.                 sys.exit()
  60.             elif event.type == MOUSEMOTION:
  61.                 mousex, mousey = event.pos
  62.             elif event.type == MOUSEBUTTONUP:
  63.                 mousex, mousey = event.pos
  64.                 mouseClicked = True

  65.         boxx, boxy = getBoxAtPixel(mousex, mousey)
  66.         if boxx != None and boxy != None:
  67.             # The mouse is currently over a box.
  68.             if not revealedBoxes[boxx][boxy]:
  69.                 drawHighlightBox(boxx, boxy)
  70.             if not revealedBoxes[boxx][boxy] and mouseClicked:
  71.                 revealBoxesAnimation(mainBoard, [(boxx, boxy)])   # 揭开动画
  72.                 revealedBoxes[boxx][boxy] = True # set the box as "revealed"
  73.                 if firstSelection == None: # the current box was the first box clicked
  74.                     firstSelection = (boxx, boxy)
  75.                 else: # the current box was the second box clicked
  76.                     # Check if there is a match between the two icons.
  77.                     icon1shape, icon1color = getShapeAndColor(mainBoard, firstSelection[0], firstSelection[1])
  78.                     icon2shape, icon2color = getShapeAndColor(mainBoard, boxx, boxy)

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

  88.                         # Reset the board
  89.                         mainBoard = getRandomizedBoard()
  90.                         revealedBoxes = generateRevealedBoxesData(False)

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

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

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


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


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

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

  116.     # Create the board data structure, with randomly placed icons.
  117.     board = []
  118.     for x in range(BOARDWIDTH):
  119.         column = []
  120.         for y in range(BOARDHEIGHT):
  121.             column.append(icons[0])
  122.             del icons[0] # remove the icons as we assign them
  123.         board.append(column)

  124.     return board


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

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


  137. def getBoxAtPixel(x, y):
  138.     for boxx in range(BOARDWIDTH):
  139.         for boxy in range(BOARDHEIGHT):
  140.             left, top = leftTopCoordsOfBox(boxx, boxy)
  141.             boxRect = pygame.Rect(left, top, BOXSIZE, BOXSIZE)
  142.             if boxRect.collidepoint(x, y):
  143.                 return (boxx, boxy)
  144.     return (None, None)


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

  148.     left, top = leftTopCoordsOfBox(boxx, boxy) # get pixel coords from board coords
  149.     # Draw the shapes
  150.     if shape == DONUT:
  151.         pygame.draw.circle(DISPLAYSURF, color, (left + half, top + half), half - 5)   # 大圆
  152.         pygame.draw.circle(DISPLAYSURF, BGCOLOR, (left + half, top + half), quarter - 5)   # 小圆
  153.     elif shape == SQUARE:
  154.         pygame.draw.rect(DISPLAYSURF, color, (left + quarter, top + quarter, BOXSIZE - half, BOXSIZE - half))
  155.     elif shape == DIAMOND:
  156.         pygame.draw.polygon(DISPLAYSURF, color, ((left + half, top), (left + BOXSIZE - 1, top + half), (left + half, top + BOXSIZE - 1), (left, top + half)))
  157.     elif shape == LINES:
  158.         for i in range(0, BOXSIZE, 4):
  159.             pygame.draw.line(DISPLAYSURF, color, (left, top + i), (left + i, top))   # 左上部分
  160.             pygame.draw.line(DISPLAYSURF, color, (left + i, top + BOXSIZE - 1), (left + BOXSIZE - 1, top + i))   # 右下部分
  161.     elif shape == OVAL:
  162.         pygame.draw.ellipse(DISPLAYSURF, color, (left, top + quarter, BOXSIZE, half))


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


  167. def drawBoxCovers(board, boxes, coverage):
  168.     # Draws boxes being covered/revealed. "boxes" is a list
  169.     # of two-item lists, which have the x & y spot of the box.
  170.     for box in boxes:
  171.         left, top = leftTopCoordsOfBox(box[0], box[1])
  172.         pygame.draw.rect(DISPLAYSURF, BGCOLOR, (left, top, BOXSIZE, BOXSIZE))
  173.         shape, color = getShapeAndColor(board, box[0], box[1])
  174.         drawIcon(shape, color, box[0], box[1])
  175.         if coverage > 0: # only draw the cover if there is an coverage
  176.             # coverage是图标覆盖的范围
  177.             pygame.draw.rect(DISPLAYSURF, BOXCOLOR, (left, top, coverage, BOXSIZE))
  178.     pygame.display.update()
  179.     FPSCLOCK.tick(FPS)


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


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


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


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


  203. def startGameAnimation(board):
  204.     # Randomly reveal the boxes 8 at a time.
  205.     coveredBoxes = generateRevealedBoxesData(False)
  206.     boxes = []
  207.     for x in range(BOARDWIDTH):
  208.         for y in range(BOARDHEIGHT):
  209.             boxes.append( (x, y) )
  210.     random.shuffle(boxes)
  211.     boxGroups = splitIntoGroupsOf(8, boxes)

  212.     drawBoard(board, coveredBoxes)
  213.     for boxGroup in boxGroups:
  214.         revealBoxesAnimation(board, boxGroup)
  215.         coverBoxesAnimation(board, boxGroup)


  216. def gameWonAnimation(board):
  217.     # flash the background color when the player has won
  218.     coveredBoxes = generateRevealedBoxesData(True)
  219.     color1 = LIGHTBGCOLOR
  220.     color2 = BGCOLOR

  221.     for i in range(17):
  222.         color1, color2 = color2, color1 # swap colors
  223.         DISPLAYSURF.fill(color1)
  224.         drawBoard(board, coveredBoxes)
  225.         pygame.display.update()
  226.         pygame.time.wait(200)


  227. def hasWon(revealedBoxes):
  228.     # Returns True if all the boxes have been revealed, otherwise False
  229.     for i in revealedBoxes:
  230.         print(i)
  231.         if False in i:
  232.             return False # return False if any boxes are covered.
  233.     return True


  234. if __name__ == '__main__':
  235.     main()
复制代码
01.png
02.png

评分

参与人数 2荣誉 +5 鱼币 +5 贡献 +6 收起 理由
python爱好者. + 3 鱼C有你更精彩^_^
cjjJasonchen + 5 + 5 + 3 先评再看,是好习惯~

查看全部评分

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-1-29 16:26:31 | 显示全部楼层
这是一个用Pygame编写的记忆游戏。游戏规则是翻转卡片找到相同的图标配对,全部配对成功后游戏胜利。

代码中的`main()`函数是游戏的主函数,其中定义了各种颜色、图形的常量以及一些游戏参数。`generateRevealedBoxesData()`函数用于生成一个与游戏界面大小相同的二维数组,表示卡片是否被翻开。

`getRandomizedBoard()`函数用于生成一个随机的游戏界面,随机放置不同的图标。`splitIntoGroupsOf()`函数用于将一个列表分成多个更小的列表。

`leftTopCoordsOfBox()`函数用于将方格的行列坐标转换为像素坐标。`getBoxAtPixel()`函数用于根据鼠标点击的像素坐标获取方格的行列坐标。

`drawIcon()`函数用于在给定的方格上绘制指定形状和颜色的图标。`getShapeAndColor()`函数用于获取指定方格上的图标形状和颜色。

`drawBoxCovers()`函数用于绘制方格的覆盖效果。`revealBoxesAnimation()`函数用于显示被选中的方格的图标。`coverBoxesAnimation()`函数用于覆盖已经翻开的方格。

`drawBoard()`函数用于绘制游戏界面上所有的方格。`drawHighlightBox()`函数用于绘制方格的高亮效果。

`startGameAnimation()`函数用于开始游戏时的动画效果,随机翻开方格。`gameWonAnimation()`函数用于游戏胜利时的动画效果,闪烁背景颜色。

`hasWon()`函数用于判断游戏是否胜利。如果所有方格都被翻开则返回True,否则返回False。

在代码最后调用`main()`函数启动游戏。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-1-29 18:51:37 | 显示全部楼层
这样不太好吧,可以先给个官网地址(可能涉及到版权问题)

https://www.ruanyifeng.com/blog/ ... tware_licenses.html

Snipaste_2024-01-29_18-49-28.png

——————————————————————————————————————————————————————————————-

不过内容不错

作者加油!
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2024-1-29 18:53:53 | 显示全部楼层
歌者文明清理员 发表于 2024-1-29 18:51
这样不太好吧,可以先给个官网地址(可能涉及到版权问题)

https://www.ruanyifeng.com/blog/2011/05/ho ...

论坛不让写url地址。。。

评分

参与人数 1贡献 +3 收起 理由
cjjJasonchen + 3 我评分要用完了,下次再给你评分了~

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-1-29 18:55:04 | 显示全部楼层
写了地址发不出来
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-1-29 18:55:16 | 显示全部楼层
某一个“天” 发表于 2024-1-29 18:53
论坛不让写url地址。。。

emm,对不起,我忘了这个规定

你可以去掉 “https://” 发,还有你是初级鱼油,应该可以的吧(规则我也忘了,可能改过)
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-1-29 19:02:05 | 显示全部楼层
歌者文明清理员 发表于 2024-1-29 18:55
emm,对不起,我忘了这个规定

你可以去掉 “https://” 发,还有你是初级鱼油,应该可以的 ...

发的时候是新鱼油
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-1-29 19:02:43 | 显示全部楼层
# By Al Sweigart al@inventwithpython.com
# http://inventwithpython.com/pygame
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-1-29 19:36:11 | 显示全部楼层
歌者文明清理员 发表于 2024-1-29 18:51
这样不太好吧,可以先给个官网地址(可能涉及到版权问题)

https://www.ruanyifeng.com/blog/2011/05/ho ...

是这样的
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-1-29 19:36:35 | 显示全部楼层

你可以编辑帖子
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2024-1-29 19:38:50 | 显示全部楼层

懂了

评分

参与人数 1荣誉 +3 鱼币 +5 收起 理由
cjjJasonchen + 3 + 5 还给你,评分留给需要的新人或者高质量帖子.

查看全部评分

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-1-29 20:50:19 | 显示全部楼层
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-1-29 23:01:16 | 显示全部楼层

不用给我每个帖子都评分,只有我写的教程之类的高质量长贴比较缺评分,其他的你给他评分没什么意义 我们至尊vip不缺经验和育碧的
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2024-1-29 23:14:20 | 显示全部楼层
cjjJasonchen 发表于 2024-1-29 23:01
不用给我每个帖子都评分,只有我写的教程之类的高质量长贴比较缺评分,其他的你给他评分没什么意义 我们 ...

其实我是全FishC第二个不用rmb搞到至尊的人
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-28 21:56

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表