Python 新手村

用 Python 打造你的遊戲

2020

小草、RexWu

Part 5

ctl12345

dict-字典

(dictionary)

dict-字典

key - value

value 可以有多種型態

key 只能為 string

dict - 字典 可以做什麼

  • 個人檔案(名字: Rex)

  • 摩斯密碼對照(密碼: 明碼)

  • 菜單(餐點: 價錢)

  • Others...?

dict 長這樣

{"name": "Rex", "age": 19, "student?": True}

"name": "Rex"

key

value

生成字典

dic = {'name': 'Rex', 'age': 19, 'student?': True}

dic = {}

dic = dict()

print 字典

dic = {'name': 'Rex', 'age': 19, 'student?': True}

print(dic)
#{'name': 'Rex', 'age': 19, 'student?': True}

print(dic['name'])
#Rex

print 字典 + for loop

dic = {'name': 'Rex', 'age': 19, 'student?': True}

for key in dic:
	print(key)
#name
#age
#student?

for key in dic:
	print(dic[key])
#Rex
#19
#True

增加元素

dic = {}

dic.update({'name': 'Rex', 'age': 19})

實作一下

生成一個字典

再使用 for 分別 print key 和 value

 

內容:個人資料 、 成績、菜單

編輯字典

dic = {'name': 'Rex', 'age': 19}

dict['age'] = 20

刪除字典

dic = {'name': 'Rex', 'age': 19}

dic.pop('name')
#'Rex'

del dic['age']

dic.clear()
#清空字典內所有元素

取所有 key/value

dic = {'name': 'Rex', 'age': 19}

dic.keys()
#dict_keys(['name', 'age'])

dic.value()
#dict_values(['Rex', 19])

試試看

再來買一次早餐吧

這次加上 list 和 dict 做點變化

set & tuple

Other "containers"

"containers"

來專業一下

list

dict

set

tuple

set

不重複、無序的 list

# 裡面有值
a = {1, 2, 3}
b = {2, 4, 6}

# 空的
s = set()

生成set

a = {1, 2, 3}
b = {4, 5, 6}

# 新增值
a.add(value)

# 刪除值
a.discard(value)

# 隨機刪除值
a.pop()

set的操作

# 連集
a | b # = a.union(b)
# 交集
a & b # = a.intersection(b)
# 差集
a - b # = a.difference(b)
# 補集
a ^ b # = a.symmetric_difference(b)
# 判斷 a 是否為 b 的子集合
a.issubset(b)

試試看

好吧,繼續點菜但是

這次菜單上的東西都有限量

而且只限一個

tuple vs list

  • tuple 中的項目是不可變更
  • list 想怎麼改就怎麼改
  • list 比 tuple 更常使用到

簡單來說 tuple 就是不可變更的 list

create tuple

tuples = 'dog', 'cat', 'fish'
a, b, c = tuples
list = ['dog', 'cat', 'fish']
tuple(list)

Container 總整理

List

Set

  • 有順序
  • 可改變
  • Access by index
  • 存放可重複的東西
  • e.g. 玩家背包
  • 無順序
  • 可改變
  • Access by logical express
  • 存放不可重複的東西
  • e.g. 抽卡遊戲的卡夾

Tuple

Dict

  • 有順序
  • 不可改變
  • Access by index
  • 存放永遠不會變動的東西
  • e.g. 遊戲世界設定的常數
  • 有順序
  • 可改變、更新
  • Access by key
  • 存放有對應 key 的資料
  • e.g. 玩家清單 (id - 玩家背包)

function

函數

之前的

print()

dict()

list()

input()

.time()

set()

tuple()

len()

.pop()

.push()

.push()

都是"function"

你也可以自己定義各種 function

function basic

def setName(name):
  if(name != None):
    return name
  else:
    print("ERROR! 名字不能為空白!")
    return ""

print(setName())
print(setName("小草"))

function basic

def setName(name):

函數

名稱

參數

(可以空白)

function basic

return name

回傳的變數

可以是任意型態

function basic

def funcArg(val):
  print("沒有參數")
  print("參數是 " + str(val))

def funcWithNoArg():
  print("沒有參數的函數")
  
def funcWithReturnValue():
  return "有回傳值的函數"

def funcWithNoReturnValue():
  print("沒有回傳值的函數")

接住 function 回傳的值

def funcWithReturnValue():
  return "有回傳值的函數"

r = funcWithReturnValue()
print(r)

why function?

如果某些動作需要重複執行 只要寫一次就好

讓程式變得簡潔許多

def greet(name):
  print("Hello, " + str(name))
  
# main
n = input("請告訴我你的名字")
greet(n)

Greet again!

做個小遊戲

圈圈叉叉

例外處理

Try & except

x = int(input('請輸入 x :'))
y = int(input('請輸入 y :'))
print(x + y)

整數相加

如果輸入非整數呢?

結果是 => ValueError:

try:
  x = int(input('請輸入 x :'))
  y = int(input('請輸入 y :'))
  print(x + y)
except:
  print('輸入錯誤 請輸入整數')

所以要處理例外狀況

使用 「try」和 「except」

def add():
    try:
        x = int(input('請輸入 x :'))
        y = int(input('請輸入 y :'))
        print(x + y)
    except:
        print('輸入錯誤 請輸入整數')
        add()
add()

發生例外就結束程式了?

加上 function 看看

class

物件 - 概念

什麼是 "class"

物件

一位玩家

屬性

  • HP

  • ATK

  • DEF

  • 背包

一位玩家

功能

  • 攻擊

  • 防禦

  • 補血

  • 撿東西

class

物件 - 實作

class Player:

  def __init__(self, hp, atk, def_, inventory):
    self.hp = hp
    self.atk = atk
    self.def_ = def_
    self.inventory = inventory

  def attack(self, target):
    target.hp = target.def_ - self.atk

簡單的 Player 物件

init "初始化"

  def __init__(self, hp, atk, def_, inventory):

物件本體

參數們

init "初始化"

    self.hp = hp
    self.atk = atk
    self.def_ = def_
    self.inventory = inventory

設定玩家的 hp

設定玩家的 atk

設定玩家的 def

設定玩家的 物品欄

下課囉~

來點個名

 

Python 新手村 2020 Part 5

By Rex Wu

Python 新手村 2020 Part 5

  • 72