Python入門筆記

Python入門筆記

視頻學習網址http://blog.fishc.com/category/python

目錄


語法:

字符串 ——————單引號 ” 或者 雙引號 “”
轉義符號—————–\
原始字符串—————r” ,自動添加轉義符號
長字符串—————–”’ ”’ 三重引號,可以自動添加換行符
e記法——————–*e(), *10的次方值
隨機整數 random.randint(start,end)

數據轉換

int()——————–轉換成整數,輸入爲浮點型時,採用去尾法
str()——————–轉換成字符串
float()——————轉換成浮點數

獲取變量類型

type()——————-獲取變量類型
isinstance( , object)—-判斷是否爲object指定的變量類型
dir()獲取某個類的所有方法

操作符及優先級:

冪運算—————– **
正負號—————- + -
算數操作符———- * / // + -
比較操作符——– < <= > >= == !=
邏輯運算符——- not and or

if — else

if :
tab鍵
else :
tab鍵

for 循環

for each in []
range([start,] stop[, step=1])
—[]中的內容可選
—生成從 start 到 stop 前一個的一個列表,步進爲 step

數組:

初始化:

= [ , , ] 數組的元素可以爲任意不同的類

方法:

remove(元素名)
pop() -----------------彈出最後的元素
pop(index)------------彈出index位置的元素
[start : end]----------獲取從start位置開始到end前一個的數組分片
    ---[:]---------------用於獲取列表拷貝
count() ---------------獲取某個元素在列表中出現的次數
index() ---------------獲取某個元素出現的第一個位置
reverse() -------------翻轉數組
sort() ----------------從小到大排序
sort(reverse = true)---從大到小排序
sort(func, key)--------

操作符:

in :判斷某個元素是否在數組中
not in:判斷某個元素是否不在數組中

元組(tuple):

元組中元素不可更改,其餘和數組很像
初始化:( , , )

字符串:

capitalize()————-首字母大寫
center()—————–輸入爲文本居中後的長度,首尾補足空格
count(”)—————-尋找輸入字符串出現的個數

字符串格式化輸出:

format()
str中含有{0} {1} {2} 等位置參數,用format(”, ”, ”)的輸入替換該相應的位置參數
str中含有{a} {b} {c} 等關鍵字參數,用format(a=”, b=”, c=”)輸入替換該相應的位置參數

{f} 表示 浮點數
{m.n}m是顯示的最小總寬度,n是小數點後位數

函數:

關鍵字參數:賦值時直接使用參數形參的名字賦值,可以不用考慮形參的順序,既 形參 = ”
參數列表:在函數定義時,def func(*params)這種形式可以傳入一個元組參數

定義形式:

def func:

全局變量與局部變量

global 關鍵字
函數內部無法改變全局變量的值,試圖使用全局變量時,會自動生成一個同名的局部變量
若需要修改全局變量,則需要在變量前加 global 關鍵字

內嵌函數:

在函數內部定義的函數,只允許在內部調用

閉包寫法:

函數返回值爲其內部函數的方式

lambda關鍵字 :匿名函數 類似define,

字典(dict):

key和value對應,
可以讓兩個數組一個爲key,一個爲value,例如a[b.index(元素)]或輸出a數組對應的index的元素
另一種賦值方式 {key:value, key:value},訪問時使用 [key]

集合(set):

集合是無序的,不可以用index索引訪問
賦值方式 = { ,,,}
或者 set([ ]), frozenset()—–不可更改的集合

添加元素:
add()
訪問方式:
for方式
用 in 和 not in判斷是否存在

由attr和func構成

attr方法:
hasattr(object, name)—————-是否含有某個attr
getattr(object, name[, default])—–獲取某個attr
setattr(object, name, value)
delattr(object, name)

x = property(fget, fset, fdel, doc),將某個attr賦值到x中,使得x 通過 = del可以直接操作 某個attr

類的魔法方法:*(self[, …])

繼承 class classname(father class)

初始化 init(self, [])
構造 new(class, []), new 方法第一個調用
析構 del(self)

算數運算:

add(self, other),
add +
sub -
mul *
truediv /
flordiv //
mod %
pow **
shift <<
rshift >>
and &
xor ^
or |

yield 與 next()
func內部可以寫過個 yield 關鍵字,當調用next時會依次執行到相應的next

GUI:tkinter

窗口顯示:tkinter.Tk().mainloop()
窗口標題:tkinter.Tk().title(‘cui ui’)
按鈕:tkinter.Button(Master, text = ‘button’, fg = ‘red’, command = button_behavier)button_behavier爲點擊調用方法

顯示圖片 imageLable = Label(Master, image = PhotoImage(file = ‘18.gif’)),PhotoImage只能加載gif圖片好像

多選框:Checkbutton(Master, text=”, variable = IntVar())variable選中則爲1,未選中則爲0

單選框:Radiobuttob(Master, text=”,variable = IntVar(), value = 同一個master中的value不能相同),

輸入框:Entry(Master)

大量選擇框: Listbox(Master) ,用insert依次添加新的數據, delete()刪除。可以設置單選,多選

輸入框:Text()

排列方式:
pack(),定義位置
grid(row = , colum = ),按照網格定義位置

pygame

Surface對象,用來表示圖像

事件:獲取事件 ,pygame.event.get(). 退出按鈕 ptgame.QUIT,
方向鍵:event.type == KEYDOWN, event.key == K_LEFT/K_RIGHT/K_UP/K_DOWN

貪吃蛇小遊戲

import pygame
import sys
import random
import tkinter

class MaySnake:    

    snakeColor = (0,0,0)
    eatColor = (255, 255, 0)



    #速率
    interval = 20;


    def init(self, interval):
        #存儲貪吃蛇位置
        self.Location = []
        #食物位置
        self.moduleLocation = (0, 0)
        #前進方向
        self.moveDirection = (0, 0)
        self.flash = 0;

        #第一個貪食蛇位置        
        self.Location.append((random.randint(0,screenSize[0]), random.randint(0,screenSize[1])))
        self.creatModule()
        #print(self.moduleLocation)
        self.interval = interval

    #生成吃食的位置
    def creatModule(self):
        while True:
            self.moduleLocation = (random.randint(0,screenSize[0]), random.randint(0,screenSize[1]))
            if self.moduleLocation not in  self.Location:
                return self.moduleLocation

    def draw(self, surface, size):
        for each in self.Location:
            pygame.draw.rect(surface, self.snakeColor, (each[0]*size, each[1]*size, size, size), 0)

    def drawEat(self, surface, size):
        pygame.draw.rect(surface, self.eatColor, (self.moduleLocation[0]*size, self.moduleLocation[1]*size, size, size), 0)

    def move(self, direction):
        #print("move direction", direction, "location -1:", self.Location[-1])
        self.flash = self.flash + 1
        if self.flash < self.interval:
            return
        self.flash = 0
        self.moveDirection = direction
        if (self.moduleLocation[0] - self.Location[-1][0], self.moduleLocation[1] - self.Location[-1][1]) == direction:
            self.Location.append(self.moduleLocation)
            self.creatModule()
        else:
            #print("new location:", (self.Location[-1][0] + direction[0], self.Location[-1][1] + direction[1]))
            self.Location.append((self.Location[-1][0] + direction[0], self.Location[-1][1] + direction[1]))
            self.Location.pop(0)

    def checkOk(self):
        if self.Location[-1][0]<0 or self.Location[-1][0]>screenSize[0] or self.Location[-1][1]<0 or self.Location[-1][1] > screenSize[1]:
            return False
        for index in range(0, len(self.Location)-2):
            if self.Location[-1] == self.Location[index]:
                return False
        return True

direction = (0,1)
#屏幕模塊數目
screenSize = (30, 30)
screenColor = (255, 255, 255)
#貪吃蛇大小
moduleSize = (10, 10)
moduleColor = (0,0,0)



def main():
    direction = (0,1)
    #屏幕模塊數目
    screenSize = (30, 30)
    screenColor = (255, 255, 255)
    #貪吃蛇大小
    moduleSize = (10, 10)
    moduleColor = (0,0,0)
    pygame.init()
    screen = pygame.display.set_mode((screenSize[0]*moduleSize[0], screenSize[1]*moduleSize[1]))
    pygame.display.set_caption("貪吃蛇")

    maySnake = MaySnake()
    maySnake.init(10)

    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT and maySnake.moveDirection != (1, 0):
                        direction = (-1, 0)                    
                if event.key == pygame.K_RIGHT and maySnake.moveDirection != (-1, 0):
                         direction = (1, 0)
                if event.key == pygame.K_UP and maySnake.moveDirection != (0, 1):
                         direction = (0, -1)
                if event.key == pygame.K_DOWN and maySnake.moveDirection != (0, -1):
                         direction = (0, 1)
        #print ("direction:", direction)
        screen.fill(screenColor)

        if maySnake.checkOk() == False:
            #if tkinter.messagebox.askokcancel("game over", "restar?"):
                #print('restar')
                #main()
            print('game over')
            sys.exit()

        #pygame.draw.rect(screen, moduleColor, (150, 220, 10, 10), 1)
        #print(S.moduleLocation)
        maySnake.drawEat(screen, moduleSize[0])
        maySnake.draw(screen, moduleSize[0])
        maySnake.move(direction)

        pygame.display.flip()
        pygame.time.delay(40)

main()

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章