﻿{"id":518,"date":"2020-09-02T04:12:23","date_gmt":"2020-09-01T20:12:23","guid":{"rendered":"https:\/\/byy3.com\/?p=518"},"modified":"2021-01-09T10:10:09","modified_gmt":"2021-01-09T02:10:09","slug":"python%e5%b0%8f%e6%b8%b8%e6%88%8f%e6%ba%90%e7%a0%81pygame%e4%b9%8b%e8%b4%aa%e5%90%83%e8%9b%87%e5%ae%9e%e4%be%8b","status":"publish","type":"post","link":"https:\/\/byy3.com\/?p=518","title":{"rendered":"python\u5c0f\u6e38\u620f\u6e90\u7801pygame\u4e4b\u8d2a\u5403\u86c7\u5b9e\u4f8b"},"content":{"rendered":"<pre># Wormy (a Nibbles clone)\r\n# By Al Sweigart al@inventwithpython.com\r\n# http:\/\/byy3.com\/pygame\r\n# Released under a \"Simplified BSD\" license\r\n\r\nimport random, pygame, sys\r\nfrom pygame.locals import *\r\n\r\nFPS = 12 #\u6e38\u620f\u901f\u5ea6\r\nWINDOWWIDTH = 640\r\nWINDOWHEIGHT = 480\r\nCELLSIZE = 20\r\nassert WINDOWWIDTH % CELLSIZE == 0, \"Window width must be a multiple of cell size.\"\r\nassert WINDOWHEIGHT % CELLSIZE == 0, \"Window height must be a multiple of cell size.\"\r\nCELLWIDTH = int(WINDOWWIDTH \/ CELLSIZE)\r\nCELLHEIGHT = int(WINDOWHEIGHT \/ CELLSIZE)\r\n\r\n# R G B\r\nWHITE = (255, 255, 255)\r\nBLACK = ( 0, 0, 0)\r\nRED = (255, 0, 0)\r\nGREEN = ( 0, 255, 0)\r\nDARKGREEN = ( 0, 155, 0)\r\nDARKGRAY = ( 40, 40, 40)\r\nBGCOLOR = BLACK\r\n\r\nUP = 'up'\r\nDOWN = 'down'\r\nLEFT = 'left'\r\nRIGHT = 'right'\r\n\r\nHEAD = 0 # syntactic sugar: index of the worm's head\r\n\r\ndef main():\r\n global FPSCLOCK, DISPLAYSURF, BASICFONT\r\n\r\n pygame.init()\r\n FPSCLOCK = pygame.time.Clock()\r\n DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))\r\n BASICFONT = pygame.font.Font('freesansbold.ttf', 18)\r\n pygame.display.set_caption('py_serpent.py')\r\n\r\n showStartScreen()\r\n while True:\r\n runGame()\r\n showGameOverScreen()\r\n\r\n\r\ndef runGame():\r\n # Set a random start point.\r\n startx = random.randint(5, CELLWIDTH - 6)\r\n starty = random.randint(5, CELLHEIGHT - 6)\r\n wormCoords = [{'x': startx, 'y': starty},\r\n {'x': startx - 1, 'y': starty},\r\n {'x': startx - 2, 'y': starty}]\r\n direction = RIGHT\r\n\r\n # Start the apple in a random place.\r\n apple = getRandomLocation()\r\n\r\n while True: # main game loop\r\n for event in pygame.event.get(): # event handling loop\r\n if event.type == QUIT:\r\n terminate()\r\n elif event.type == KEYDOWN:\r\n if (event.key == K_LEFT or event.key == K_a) and direction != RIGHT:\r\n direction = LEFT\r\n elif (event.key == K_RIGHT or event.key == K_d) and direction != LEFT:\r\n direction = RIGHT\r\n elif (event.key == K_UP or event.key == K_w) and direction != DOWN:\r\n direction = UP\r\n elif (event.key == K_DOWN or event.key == K_s) and direction != UP:\r\n direction = DOWN\r\n elif event.key == K_ESCAPE:\r\n terminate()\r\n\r\n # check if the worm has hit itself or the edge\r\n if wormCoords[HEAD]['x'] == -1 or wormCoords[HEAD]['x'] == CELLWIDTH or wormCoords[HEAD]['y'] == -1 or wormCoords[HEAD]['y'] == CELLHEIGHT:\r\n return # game over\r\n for wormBody in wormCoords[1:]:\r\n if wormBody['x'] == wormCoords[HEAD]['x'] and wormBody['y'] == wormCoords[HEAD]['y']:\r\n return # game over\r\n\r\n # check if worm has eaten an apply\r\n if wormCoords[HEAD]['x'] == apple['x'] and wormCoords[HEAD]['y'] == apple['y']:\r\n # don't remove worm's tail segment\r\n apple = getRandomLocation() # set a new apple somewhere\r\n else:\r\n del wormCoords[-1] # remove worm's tail segment\r\n\r\n # move the worm by adding a segment in the direction it is moving\r\n if direction == UP:\r\n newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] - 1}\r\n elif direction == DOWN:\r\n newHead = {'x': wormCoords[HEAD]['x'], 'y': wormCoords[HEAD]['y'] + 1}\r\n elif direction == LEFT:\r\n newHead = {'x': wormCoords[HEAD]['x'] - 1, 'y': wormCoords[HEAD]['y']}\r\n elif direction == RIGHT:\r\n newHead = {'x': wormCoords[HEAD]['x'] + 1, 'y': wormCoords[HEAD]['y']}\r\n wormCoords.insert(0, newHead)\r\n DISPLAYSURF.fill(BGCOLOR)\r\n drawGrid()\r\n drawWorm(wormCoords)\r\n drawApple(apple)\r\n drawScore(len(wormCoords) - 3)\r\n pygame.display.update()\r\n FPSCLOCK.tick(FPS)\r\n\r\ndef drawPressKeyMsg():\r\n pressKeySurf = BASICFONT.render('Press a key to play.', True, DARKGRAY)\r\n pressKeyRect = pressKeySurf.get_rect()\r\n pressKeyRect.topleft = (WINDOWWIDTH - 200, WINDOWHEIGHT - 30)\r\n DISPLAYSURF.blit(pressKeySurf, pressKeyRect)\r\n\r\n\r\ndef checkForKeyPress():\r\n if len(pygame.event.get(QUIT)) &gt; 0:\r\n terminate()\r\n\r\n keyUpEvents = pygame.event.get(KEYUP)\r\n if len(keyUpEvents) == 0:\r\n return None\r\n if keyUpEvents[0].key == K_ESCAPE:\r\n terminate()\r\n return keyUpEvents[0].key\r\n\r\n\r\ndef showStartScreen():\r\n titleFont = pygame.font.Font('freesansbold.ttf', 100)\r\n titleSurf1 = titleFont.render('Ready!', True, WHITE, DARKGREEN)#\u6e38\u620f\u5f00\u59cb\u63d0\u793a\r\n titleSurf2 = titleFont.render('GO!', True, GREEN)#\u6e38\u620f\u5f00\u59cb\u63d0\u793a\r\n\r\n degrees1 = 0\r\n degrees2 = 0\r\n while True:\r\n DISPLAYSURF.fill(BGCOLOR)\r\n rotatedSurf1 = pygame.transform.rotate(titleSurf1, degrees1)\r\n rotatedRect1 = rotatedSurf1.get_rect()\r\n rotatedRect1.center = (WINDOWWIDTH \/ 2, WINDOWHEIGHT \/ 2)\r\n DISPLAYSURF.blit(rotatedSurf1, rotatedRect1)\r\n\r\n rotatedSurf2 = pygame.transform.rotate(titleSurf2, degrees2)\r\n rotatedRect2 = rotatedSurf2.get_rect()\r\n rotatedRect2.center = (WINDOWWIDTH \/ 2, WINDOWHEIGHT \/ 2)\r\n DISPLAYSURF.blit(rotatedSurf2, rotatedRect2)\r\n\r\n drawPressKeyMsg()\r\n\r\n if checkForKeyPress():\r\n pygame.event.get() # clear event queue\r\n return\r\n pygame.display.update()\r\n FPSCLOCK.tick(FPS)\r\n degrees1 += 3 # rotate by 3 degrees each frame\r\n degrees2 += 7 # rotate by 7 degrees each frame\r\n\r\n\r\ndef terminate():\r\n pygame.quit()\r\n sys.exit()\r\n\r\n\r\ndef getRandomLocation():\r\n return {'x': random.randint(0, CELLWIDTH - 1), 'y': random.randint(0, CELLHEIGHT - 1)}\r\n\r\n\r\ndef showGameOverScreen():\r\n gameOverFont = pygame.font.Font('freesansbold.ttf', 150)\r\n gameSurf = gameOverFont.render('Game', True, WHITE)#\u6e38\u620f\u7ed3\u675f\u63d0\u793a\r\n overSurf = gameOverFont.render('Over', True, WHITE)#\u6e38\u620f\u7ed3\u675f\u63d0\u793a\r\n gameRect = gameSurf.get_rect()\r\n overRect = overSurf.get_rect()\r\n gameRect.midtop = (WINDOWWIDTH \/ 2, 10)\r\n overRect.midtop = (WINDOWWIDTH \/ 2, gameRect.height + 10 + 25)\r\n\r\n DISPLAYSURF.blit(gameSurf, gameRect)\r\n DISPLAYSURF.blit(overSurf, overRect)\r\n drawPressKeyMsg()\r\n pygame.display.update()\r\n pygame.time.wait(500)\r\n checkForKeyPress() # clear out any key presses in the event queue\r\n\r\n while True:\r\n if checkForKeyPress():\r\n pygame.event.get() # clear event queue\r\n return\r\n\r\ndef drawScore(score):\r\n scoreSurf = BASICFONT.render('Score: %s' % (score), True, WHITE)\r\n scoreRect = scoreSurf.get_rect()\r\n scoreRect.topleft = (WINDOWWIDTH - 120, 10)\r\n DISPLAYSURF.blit(scoreSurf, scoreRect)\r\n\r\n\r\ndef drawWorm(wormCoords):\r\n for coord in wormCoords:\r\n x = coord['x'] * CELLSIZE\r\n y = coord['y'] * CELLSIZE\r\n wormSegmentRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)\r\n pygame.draw.rect(DISPLAYSURF, DARKGREEN, wormSegmentRect)\r\n wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, CELLSIZE - 8, CELLSIZE - 8)\r\n pygame.draw.rect(DISPLAYSURF, GREEN, wormInnerSegmentRect)\r\n\r\n\r\ndef drawApple(coord):\r\n x = coord['x'] * CELLSIZE\r\n y = coord['y'] * CELLSIZE\r\n appleRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)\r\n pygame.draw.rect(DISPLAYSURF, RED, appleRect)\r\n\r\n\r\ndef drawGrid():\r\n for x in range(0, WINDOWWIDTH, CELLSIZE): # draw vertical lines\r\n pygame.draw.line(DISPLAYSURF, DARKGRAY, (x, 0), (x, WINDOWHEIGHT))\r\n for y in range(0, WINDOWHEIGHT, CELLSIZE): # draw horizontal lines\r\n pygame.draw.line(DISPLAYSURF, DARKGRAY, (0, y), (WINDOWWIDTH, y))\r\n\r\n\r\nif __name__ == '__main__':\r\n main()<\/pre>\n","protected":false},"excerpt":{"rendered":"<p># Wormy (a Nibbles clone) # By Al Sweigart al@inventwit [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[20],"tags":[352],"class_list":["post-518","post","type-post","status-publish","format-standard","hentry","category-python","tag-python"],"_links":{"self":[{"href":"https:\/\/byy3.com\/index.php?rest_route=\/wp\/v2\/posts\/518","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/byy3.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/byy3.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/byy3.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/byy3.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=518"}],"version-history":[{"count":0,"href":"https:\/\/byy3.com\/index.php?rest_route=\/wp\/v2\/posts\/518\/revisions"}],"wp:attachment":[{"href":"https:\/\/byy3.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=518"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/byy3.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=518"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/byy3.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=518"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}