最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

保姆級(jí)python教程寫個(gè)貪吃蛇大冒險(xiǎn)

 更新時(shí)間:2021年09月18日 10:02:01   作者:顧木子吖  
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)雙人模式的貪吃蛇小游戲,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

導(dǎo)語 ​

圖片

貪吃蛇,大家應(yīng)該都玩過。當(dāng)初第一次接觸貪吃蛇的時(shí)候 ,還是我爸的數(shù)字手機(jī),考試成績(jī)比較好,就會(huì)得到一些小獎(jiǎng)勵(lì),玩手機(jī)游戲肯定也在其中首位,畢竟小孩子天性都喜歡~

當(dāng)時(shí)都能玩的不亦樂乎。今天,我們用Python編程一個(gè)貪吃蛇游戲哦~

正文

1.將使用兩個(gè)主要的類(蛇和立方體)。

#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.創(chuàng)造游戲循環(huán):

在所有的游戲中,我們都有一個(gè)叫做“主循環(huán)”或“游戲循環(huán)”的循環(huán)。該循環(huán)將持續(xù)運(yùn)行,直到游戲退出。它主要負(fù)責(zé)檢查事件,并基于這些事件調(diào)用函數(shù)和方法。

我們將在main()功能。在函數(shù)的頂部聲明一些變量,然后進(jìn)入while循環(huán),這將代表我們的游戲循環(huán)。

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.更新屏幕:通常,在一個(gè)函數(shù)或方法中繪制所有對(duì)象是一種很好的做法。我們將使用重繪窗口函數(shù)來更新顯示。我們?cè)谟螒蜓h(huán)中每一幀調(diào)用一次這個(gè)函數(shù)。稍后我們將向該函數(shù)添加更多內(nèi)容。然而,現(xiàn)在我們將簡(jiǎn)單地繪制網(wǎng)格線。

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.繪制網(wǎng)格:現(xiàn)在將繪制代表20x20網(wǎng)格的線條。

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.現(xiàn)在當(dāng)我們運(yùn)行程序時(shí),我們可以看到網(wǎng)格線被畫出來。

pygame snake tutorial

6.開始制作貪吃蛇:蛇對(duì)象將包含一個(gè)代表蛇身體的立方體列表。我們將把這些立方體存儲(chǔ)在一個(gè)名為body的列表中,它將是一個(gè)類變量。我們還將有一個(gè)名為turns的類變量。為了開始蛇類,對(duì)__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.這款游戲最復(fù)雜的部分就是翻蛇。我們需要記住我們把我們的蛇轉(zhuǎn)向了哪里和哪個(gè)方向,這樣當(dāng)頭部后面的立方體到達(dá)那個(gè)位置時(shí),我們也可以把它們轉(zhuǎn)向。這就是為什么每當(dāng)我們轉(zhuǎn)向時(shí),我們會(huì)將頭部的位置添加到轉(zhuǎn)向字典中,其中值是我們轉(zhuǎn)向的方向。這樣,當(dāng)其他立方體到達(dá)這個(gè)位置時(shí),我們就知道如何轉(zhuǎn)動(dòng)它們了。

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.畫蛇:我們只需畫出身體中的每個(gè)立方體對(duì)象。我們將在蛇身上做這個(gè)繪制()方法。

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.結(jié)束游戲當(dāng)我們的蛇物體與自己碰撞時(shí),我們就輸了。為了檢查這一點(diǎn),我們?cè)趍ain()游戲循環(huán)中的功能。

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.蛇類–重置()方法現(xiàn)在我們將對(duì)重置()方法。所有這些將會(huì)做的是重置蛇,這樣我們可以在之后再次玩。

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

下面我們先看看效果:

snake image pygame tutorial

總結(jié)

好了🐍蛇蛇大作戰(zhàn)就寫完啦!

到此這篇關(guān)于保姆級(jí)python教程寫個(gè)貪吃蛇大冒險(xiǎn)的文章就介紹到這了,更多相關(guān)python 貪吃蛇內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python中append函數(shù)用法講解

    python中append函數(shù)用法講解

    在本篇文章里小編給大家整理的是一篇關(guān)于python中append函數(shù)用法講解內(nèi)容,有興趣的朋友們可以學(xué)習(xí)下。
    2020-12-12
  • Pyspider中給爬蟲偽造隨機(jī)請(qǐng)求頭的實(shí)例

    Pyspider中給爬蟲偽造隨機(jī)請(qǐng)求頭的實(shí)例

    今天小編就為大家分享一篇Pyspider中給爬蟲偽造隨機(jī)請(qǐng)求頭的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-05-05
  • 淺談python函數(shù)調(diào)用返回兩個(gè)或多個(gè)變量的方法

    淺談python函數(shù)調(diào)用返回兩個(gè)或多個(gè)變量的方法

    今天小編就為大家分享一篇淺談python函數(shù)調(diào)用返回兩個(gè)或多個(gè)變量的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-01-01
  • 基于Python詞云分析政府工作報(bào)告關(guān)鍵詞

    基于Python詞云分析政府工作報(bào)告關(guān)鍵詞

    這篇文章主要介紹了基于Python詞云分析政府工作報(bào)告關(guān)鍵詞,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06
  • 解讀Python腳本的常見參數(shù)獲取和處理方式

    解讀Python腳本的常見參數(shù)獲取和處理方式

    這篇文章主要介紹了Python腳本的常見參數(shù)獲取和處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-09-09
  • 介紹Python的Django框架中的QuerySets

    介紹Python的Django框架中的QuerySets

    這篇文章主要介紹了Python的Django框架中的QuerySets,QuerySet是Django中的一個(gè)內(nèi)置對(duì)象列表,經(jīng)常被用于數(shù)據(jù)庫操作,需要的朋友可以參考下
    2015-04-04
  • Python實(shí)現(xiàn)控制臺(tái)輸入密碼的方法

    Python實(shí)現(xiàn)控制臺(tái)輸入密碼的方法

    這篇文章主要介紹了Python實(shí)現(xiàn)控制臺(tái)輸入密碼的方法,實(shí)例對(duì)比分析了幾種輸入密碼的方法,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-05-05
  • Python使用bs4獲取58同城城市分類的方法

    Python使用bs4獲取58同城城市分類的方法

    這篇文章主要介紹了Python使用bs4獲取58同城城市分類的方法,涉及Python使用BeautifulSoup庫解析html頁面的技巧,需要的朋友可以參考下
    2015-07-07
  • python分割列表(list)的方法示例

    python分割列表(list)的方法示例

    這篇文章主要給大家介紹了python分割列表(list)的方法,文中給出了詳細(xì)的示例代碼大家參考學(xué)習(xí),對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起看看吧。
    2017-05-05
  • 基于Python創(chuàng)建語音識(shí)別控制系統(tǒng)

    基于Python創(chuàng)建語音識(shí)別控制系統(tǒng)

    這篇文章主要介紹了通過Python實(shí)現(xiàn)創(chuàng)建語音識(shí)別控制系統(tǒng),能利用語音識(shí)別識(shí)別說出來的文字,根據(jù)文字的內(nèi)容來控制圖形移動(dòng),感興趣的同學(xué)可以關(guān)注一下
    2021-12-12

最新評(píng)論

通许县| 汪清县| 若羌县| 夹江县| 友谊县| 衡阳县| 格尔木市| 盈江县| 河间市| 治县。| 泾阳县| 宁河县| 曲周县| 高清| 邢台市| 志丹县| 错那县| 德格县| 威远县| 双辽市| 栾城县| 宜良县| 芜湖县| 抚顺市| 昌宁县| 桦南县| 河北区| 柞水县| 宁陵县| 阿拉尔市| 西丰县| 诏安县| 河北省| 宜春市| 冀州市| 望谟县| 兴安盟| 广安市| 明水县| 凤冈县| 庆阳市|