用Python寫貪吃蛇遊戲的程式碼實例
這篇文章主要為大家詳細介紹了Python貪吃蛇遊戲的編寫程式碼,具有一定的參考價值,有興趣的小夥伴們可以參考一下
最近在學Python,想做點什麼來練練手,命令行的貪吃蛇一般是C的練手項目,但是一時之間找不到別的,就先做個貪吃蛇來練練簡單的語法。
由於Python監聽鍵盤很麻煩,沒有C語言的kbhit(),所以這條貪吃蛇不會自己動,運作效果如下:
要求:用#表示邊框,用*表示食物,o表示蛇的身體,O表示蛇頭,使用wsad來移動
Python版本:3.6.1
#系統環境:Win10
類別:
board:棋盤,也就是遊戲區域
snake:貪吃蛇,透過記錄身體每個點來記錄蛇的狀態
game:遊戲類別
本來還想要個food類的,但是food只需要一個座標,和一個新建,所以乾脆使用list來保存座標,新建food放在game裡面,從邏輯上也沒有太大問題
源碼:
# Write By Guobao # 2017/4//7 # # 贪吃蛇 # 用#做边界,*做食物,o做身体和头部 # python 3.6.1 import copy import random import os import msvcrt # the board class, used to put everything class board: __points =[] def __init__(self): self.__points.clear() for i in range(22): line = [] if i == 0 or i == 21: for j in range(22): line.append('#') else: line.append('#') for j in range(20): line.append(' ') line.append('#') self.__points.append(line) def getPoint(self, location): return self.__points[location[0]][location[1]] def clear(self): self.__points.clear() for i in range(22): line = [] if i == 0 or i == 21: for j in range(22): line.append('#') else: line.append('#') for j in range(20): line.append(' ') line.append('#') self.__points.append(line) def put_snake(self, snake_locations): # clear the board self.clear() # put the snake points for x in snake_locations: self.__points[x[0]][x[1]] = 'o' # the head x = snake_locations[len(snake_locations) - 1] self.__points[x[0]][x[1]] = 'O' def put_food(self, food_location): self.__points[food_location[0]][food_location[1]] = '*' def show(self): os.system("cls") for i in range(22): for j in range(22): print(self.__points[i][j], end='') print() # the snake class class snake: __points = [] def __init__(self): for i in range(1, 6): self.__points.append([1, i]) def getPoints(self): return self.__points # move to the next position # give the next head def move(self, next_head): self.__points.pop(0) self.__points.append(next_head) # eat the food # give the next head def eat(self, next_head): self.__points.append(next_head) # calc the next state # and return the direction def next_head(self, direction='default'): # need to change the value, so copy it head = copy.deepcopy(self.__points[len(self.__points) - 1]) # calc the "default" direction if direction == 'default': neck = self.__points[len(self.__points) - 2] if neck[0] > head[0]: direction = 'up' elif neck[0] < head[0]: direction = 'down' elif neck[1] > head[1]: direction = 'left' elif neck[1] < head[1]: direction = 'right' if direction == 'up': head[0] = head[0] - 1 elif direction == 'down': head[0] = head[0] + 1 elif direction == 'left': head[1] = head[1] - 1 elif direction == 'right': head[1] = head[1] + 1 return head # the game class game: board = board() snake = snake() food = [] count = 0 def __init__(self): self.new_food() self.board.clear() self.board.put_snake(self.snake.getPoints()) self.board.put_food(self.food) def new_food(self): while 1: line = random.randint(1, 20) column = random.randint(1, 20) if self.board.getPoint([column, line]) == ' ': self.food = [column, line] return def show(self): self.board.clear() self.board.put_snake(self.snake.getPoints()) self.board.put_food(self.food) self.board.show() def run(self): self.board.show() # the 'w a s d' are the directions operation_dict = {b'w': 'up', b'W': 'up', b's': 'down', b'S': 'down', b'a': 'left', b'A': 'left', b'd': 'right', b'D': 'right'} op = msvcrt.getch() while op != b'q': if op not in operation_dict: op = msvcrt.getch() else: new_head = self.snake.next_head(operation_dict[op]) # get the food if self.board.getPoint(new_head) == '*': self.snake.eat(new_head) self.count = self.count + 1 if self.count >= 15: self.show() print("Good Job") break else: self.new_food() self.show() # 反向一Q日神仙 elif new_head == self.snake.getPoints()[len(self.snake.getPoints()) - 2]: pass # rush the wall elif self.board.getPoint(new_head) == '#' or self.board.getPoint(new_head) == 'o': print('GG') break # normal move else: self.snake.move(new_head) self.show() op = msvcrt.getch() game().run()
筆記:
1.Python 沒有Switch case語句,可以利用dirt來實作
2.Python的=號是複製,複製引用,深複製需要使用copy的deepcopy()函數來實作
3 .即使在成員函數內,也需要使用self來存取成員變量,這和C++、JAVA很不一樣
以上是用Python寫貪吃蛇遊戲的程式碼實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

熱門話題

HadiDB:輕量級、高水平可擴展的Python數據庫HadiDB(hadidb)是一個用Python編寫的輕量級數據庫,具備高度水平的可擴展性。安裝HadiDB使用pip安裝:pipinstallhadidb用戶管理創建用戶:createuser()方法創建一個新用戶。 authentication()方法驗證用戶身份。 fromhadidb.operationimportuseruser_obj=user("admin","admin")user_obj.

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

直接通過 Navicat 查看 MongoDB 密碼是不可能的,因為它以哈希值形式存儲。取回丟失密碼的方法:1. 重置密碼;2. 檢查配置文件(可能包含哈希值);3. 檢查代碼(可能硬編碼密碼)。

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

MySQL數據庫性能優化指南在資源密集型應用中,MySQL數據庫扮演著至關重要的角色,負責管理海量事務。然而,隨著應用規模的擴大,數據庫性能瓶頸往往成為製約因素。本文將探討一系列行之有效的MySQL性能優化策略,確保您的應用在高負載下依然保持高效響應。我們將結合實際案例,深入講解索引、查詢優化、數據庫設計以及緩存等關鍵技術。 1.數據庫架構設計優化合理的數據庫架構是MySQL性能優化的基石。以下是一些核心原則:選擇合適的數據類型選擇最小的、符合需求的數據類型,既能節省存儲空間,又能提升數據處理速度

作為數據專業人員,您需要處理來自各種來源的大量數據。這可能會給數據管理和分析帶來挑戰。幸運的是,兩項 AWS 服務可以提供幫助:AWS Glue 和 Amazon Athena。

啟動 Redis 服務器的步驟包括:根據操作系統安裝 Redis。通過 redis-server(Linux/macOS)或 redis-server.exe(Windows)啟動 Redis 服務。使用 redis-cli ping(Linux/macOS)或 redis-cli.exe ping(Windows)命令檢查服務狀態。使用 Redis 客戶端,如 redis-cli、Python 或 Node.js,訪問服務器。

要從 Redis 讀取隊列,需要獲取隊列名稱、使用 LPOP 命令讀取元素,並處理空隊列。具體步驟如下:獲取隊列名稱:以 "queue:" 前綴命名,如 "queue:my-queue"。使用 LPOP 命令:從隊列頭部彈出元素並返回其值,如 LPOP queue:my-queue。處理空隊列:如果隊列為空,LPOP 返回 nil,可先檢查隊列是否存在再讀取元素。
