买的一个外国佬的pygame游戏,免费送给大家啦
本帖最后由 某一个“天” 于 2024-1-29 19:40 编辑请大家多多评分,如果大家喜欢 我还有更多{:5_109:}
# Memory Puzzle
# Released under a "Simplified BSD" license
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)-GAPSIZE)) / 2) # 边缘有多少像素
YMARGIN = int((WINDOWHEIGHT - (BOARDHEIGHT * (BOXSIZE + GAPSIZE)-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:
drawHighlightBox(boxx, boxy)
if not revealedBoxes and mouseClicked:
revealBoxesAnimation(mainBoard, [(boxx, boxy)]) # 揭开动画
revealedBoxes = 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, firstSelection)
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, firstSelection), (boxx, boxy)])
revealedBoxes]] = False
revealedBoxes = 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( * 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)
del icons # 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)
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
# color value for x, y spot is stored in board
return board, board
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, box)
pygame.draw.rect(DISPLAYSURF, BGCOLOR, (left, top, BOXSIZE, BOXSIZE))
shape, color = getShapeAndColor(board, box, box)
drawIcon(shape, color, box, box)
if coverage > 0: # only draw the cover if there is an coverage
# 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, - 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:
# 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(17):
color1, color2 = color2, color1 # swap colors
DISPLAYSURF.fill(color1)
drawBoard(board, coveredBoxes)
pygame.display.update()
pygame.time.wait(200)
def hasWon(revealedBoxes):
# Returns True if all the boxes have been revealed, otherwise False
for i in revealedBoxes:
print(i)
if False in i:
return False # return False if any boxes are covered.
return True
if __name__ == '__main__':
main() 这是一个用Pygame编写的记忆游戏。游戏规则是翻转卡片找到相同的图标配对,全部配对成功后游戏胜利。
代码中的`main()`函数是游戏的主函数,其中定义了各种颜色、图形的常量以及一些游戏参数。`generateRevealedBoxesData()`函数用于生成一个与游戏界面大小相同的二维数组,表示卡片是否被翻开。
`getRandomizedBoard()`函数用于生成一个随机的游戏界面,随机放置不同的图标。`splitIntoGroupsOf()`函数用于将一个列表分成多个更小的列表。
`leftTopCoordsOfBox()`函数用于将方格的行列坐标转换为像素坐标。`getBoxAtPixel()`函数用于根据鼠标点击的像素坐标获取方格的行列坐标。
`drawIcon()`函数用于在给定的方格上绘制指定形状和颜色的图标。`getShapeAndColor()`函数用于获取指定方格上的图标形状和颜色。
`drawBoxCovers()`函数用于绘制方格的覆盖效果。`revealBoxesAnimation()`函数用于显示被选中的方格的图标。`coverBoxesAnimation()`函数用于覆盖已经翻开的方格。
`drawBoard()`函数用于绘制游戏界面上所有的方格。`drawHighlightBox()`函数用于绘制方格的高亮效果。
`startGameAnimation()`函数用于开始游戏时的动画效果,随机翻开方格。`gameWonAnimation()`函数用于游戏胜利时的动画效果,闪烁背景颜色。
`hasWon()`函数用于判断游戏是否胜利。如果所有方格都被翻开则返回True,否则返回False。
在代码最后调用`main()`函数启动游戏。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 这样不太好吧,可以先给个官网地址(可能涉及到版权问题)
https://www.ruanyifeng.com/blog/2011/05/how_to_choose_free_software_licenses.html
——————————————————————————————————————————————————————————————-
不过内容不错
作者加油! 歌者文明清理员 发表于 2024-1-29 18:51
这样不太好吧,可以先给个官网地址(可能涉及到版权问题)
https://www.ruanyifeng.com/blog/2011/05/ho ...
论坛不让写url地址。。。 写了地址发不出来 某一个“天” 发表于 2024-1-29 18:53
论坛不让写url地址。。。
emm,对不起,我忘了这个规定{:10_277:}
你可以去掉 “https://” 发,还有你是初级鱼油,应该可以的吧(规则我也忘了,可能改过) 歌者文明清理员 发表于 2024-1-29 18:55
emm,对不起,我忘了这个规定
你可以去掉 “https://” 发,还有你是初级鱼油,应该可以的 ...
发的时候是新鱼油{:5_109:} # By Al Sweigart al@inventwithpython.com
# http://inventwithpython.com/pygame 歌者文明清理员 发表于 2024-1-29 18:51
这样不太好吧,可以先给个官网地址(可能涉及到版权问题)
https://www.ruanyifeng.com/blog/2011/05/ho ...
是这样的 某一个“天” 发表于 2024-1-29 19:02
发的时候是新鱼油
你可以编辑帖子 cjjJasonchen 发表于 2024-1-29 19:36
你可以编辑帖子
懂了 {:5_109:} 某一个“天” 发表于 2024-1-29 19:38
懂了
不用给我每个帖子都评分,只有我写的教程之类的高质量长贴比较缺评分,其他的你给他评分没什么意义 我们至尊vip不缺经验和育碧的 cjjJasonchen 发表于 2024-1-29 23:01
不用给我每个帖子都评分,只有我写的教程之类的高质量长贴比较缺评分,其他的你给他评分没什么意义 我们 ...
其实我是全FishC第二个不用rmb搞到至尊的人
页:
[1]