您好,登錄后才能下訂單哦!
如何使用python制作貪吃蛇大冒險,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
貪吃蛇,大家應該都玩過。當初第一次接觸貪吃蛇的時候 ,還是我爸的數字手機,考試成績比較好,就會得到一些小獎勵,玩手機游戲肯定也在其中首位,畢竟小孩子天性都喜歡~
當時都能玩的不亦樂乎。今天,我們用Python編程一個貪吃蛇游戲哦~
1.將使用兩個主要的類(蛇和立方體)。
#Snake Tutorial Python import math import random import pygame import tkinter as tk from tkinter import messagebox class cube(object): rows = 20 w = 500 def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)): pass def move(self, dirnx, dirny): pass def draw(self, surface, eyes=False): pass class snake(object): def __init__(self, color, pos): pass def move(self): pass def reset(self, pos): pass def addCube(self): pass def draw(self, surface): pass def drawGrid(w, rows, surface): pass def redrawWindow(surface): pass def randomSnack(rows, item): pass def message_box(subject, content): pass def main(): pass main()
2.創造游戲循環:
在所有的游戲中,我們都有一個叫做“主循環”或“游戲循環”的循環。該循環將持續運行,直到游戲退出。它主要負責檢查事件,并基于這些事件調用函數和方法。
我們將在main()功能。在函數的頂部聲明一些變量,然后進入while循環,這將代表我們的游戲循環。
def main(): global width, rows, s width = 500 # Width of our screen height = 500 # Height of our screen rows = 20 # Amount of rows win = pygame.display.set_mode((width, height)) # Creates our screen object s = snake((255,0,0), (10,10)) # Creates a snake object which we will code later clock = pygame.time.Clock() # creating a clock object flag = True # STARTING MAIN LOOP while flag: pygame.time.delay(50) # This will delay the game so it doesn't run too quickly clock.tick(10) # Will ensure our game runs at 10 FPS redrawWindow(win) # This will refresh our screen
3.更新屏幕:通常,在一個函數或方法中繪制所有對象是一種很好的做法。我們將使用重繪窗口函數來更新顯示。我們在游戲循環中每一幀調用一次這個函數。稍后我們將向該函數添加更多內容。然而,現在我們將簡單地繪制網格線。
def redrawWindow(surface): surface.fill((0,0,0)) # Fills the screen with black drawGrid(surface) # Will draw our grid lines pygame.display.update() # Updates the screen
4.繪制網格:現在將繪制代表20x20網格的線條。
def drawGrid(w, rows, surface): sizeBtwn = w // rows # Gives us the distance between the lines x = 0 # Keeps track of the current x y = 0 # Keeps track of the current y for l in range(rows): # We will draw one vertical and one horizontal line each loop x = x + sizeBtwn y = y + sizeBtwn pygame.draw.line(surface, (255,255,255), (x,0),(x,w)) pygame.draw.line(surface, (255,255,255), (0,y),(w,y))
5.現在當我們運行程序時,我們可以看到網格線被畫出來。
6.開始制作貪吃蛇:蛇對象將包含一個代表蛇身體的立方體列表。我們將把這些立方體存儲在一個名為body的列表中,它將是一個類變量。我們還將有一個名為turns的類變量。為了開始蛇類,對__init__()方法并添加類變量。
class snake(object): body = [] turns = {} def __init__(self, color, pos): self.color = color self.head = cube(pos) # The head will be the front of the snake self.body.append(self.head) # We will add head (which is a cube object) # to our body list # These will represent the direction our snake is moving self.dirnx = 0 self.dirny = 1
7.這款游戲最復雜的部分就是翻蛇。我們需要記住我們把我們的蛇轉向了哪里和哪個方向,這樣當頭部后面的立方體到達那個位置時,我們也可以把它們轉向。這就是為什么每當我們轉向時,我們會將頭部的位置添加到轉向字典中,其中值是我們轉向的方向。這樣,當其他立方體到達這個位置時,我們就知道如何轉動它們了。
class snake(object): ... def move(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() keys = pygame.key.get_pressed() for key in keys: if keys[pygame.K_LEFT]: self.dirnx = -1 self.dirny = 0 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_RIGHT]: self.dirnx = 1 self.dirny = 0 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_UP]: self.dirnx = 0 self.dirny = -1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] elif keys[pygame.K_DOWN]: self.dirnx = 0 self.dirny = 1 self.turns[self.head.pos[:]] = [self.dirnx, self.dirny] for i, c in enumerate(self.body): # Loop through every cube in our body p = c.pos[:] # This stores the cubes position on the grid if p in self.turns: # If the cubes current position is one where we turned turn = self.turns[p] # Get the direction we should turn c.move(turn[0],turn[1]) # Move our cube in that direction if i == len(self.body)-1: # If this is the last cube in our body remove the turn from the dict self.turns.pop(p) else: # If we are not turning the cube # If the cube reaches the edge of the screen we will make it appear on the opposite side if c.dirnx == -1 and c.pos[0] <= 0: c.pos = (c.rows-1, c.pos[1]) elif c.dirnx == 1 and c.pos[0] >= c.rows-1: c.pos = (0,c.pos[1]) elif c.dirny == 1 and c.pos[1] >= c.rows-1: c.pos = (c.pos[0], 0) elif c.dirny == -1 and c.pos[1] <= 0: c.pos = (c.pos[0],c.rows-1) else: c.move(c.dirnx,c.dirny) # If we haven't reached the edge just move in our current direction
8.畫蛇:我們只需畫出身體中的每個立方體對象。我們將在蛇身上做這個繪制()方法。
class snake(object): ... def draw(self): for i, c in enumerate(self.body): if i == 0: # for the first cube in the list we want to draw eyes c.draw(surface, True) # adding the true as an argument will tell us to draw eyes else: c.draw(surface) # otherwise we will just draw a cube
9.結束游戲當我們的蛇物體與自己碰撞時,我們就輸了。為了檢查這一點,我們在main()游戲循環中的功能。
for x in range(len(s.body)): if s.body[x].pos in list(map(lambda z:z.pos,s.body[x+1:])): # This will check if any of the positions in our body list overlap print('Score: ', len(s.body)) message_box('You Lost!', 'Play again...') s.reset((10,10)) break
10.蛇類–重置()方法現在我們將對重置()方法。所有這些將會做的是重置蛇,這樣我們可以在之后再次玩。
class snake(): ... def reset(self, pos): self.head = cube(pos) self.body = [] self.body.append(self.head) self.turns = {} self.dirnx = 0 self.dirny = 1
下面我們先看看效果:
好了?蛇蛇大作戰就寫完啦!
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注億速云行業資訊頻道,感謝您對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。