读书笔记:<<python游戏设计案例>>

159 阅读5分钟

每天摸摸鱼,快乐摆烂每一天。

本人用spyder开发,cpp代码写多了,写写py再复习一下。

一、环境配置

笔记

先查看已安装的python版本

import sys
print(sys.version)

我的输出: 3.9.7 (default, Sep 16 2021, 16:59:28) [MSC v.1916 64 bit (AMD64)]

再来了解下Python的帮助功能:help(对象)

import os
help(max)#看内置函数和类型的帮助信息
help(os.fdopen)#看成员函数信息
help(os)#看整个模块的信息
helo("modules")#查看python中所有的modules

课后题

def answer(n):
    if n%5 == 0 and n%7 == 0:
        print("%d 可以同时被5和7整除" % n)
    else:
        print("%d 不可以同时被5和7整除"%n)
n = int(input("请输入"))
answer(n)
def answer(n):
    if n > 100 or n < 0:
        print("成绩作废")
        return 
    elif n >= 90:
        print("成绩为A")
    elif n >= 80:
        print("成绩为B")
    elif n >= 70:
        print("成绩为C")
    elif n >= 60:
        print("成绩为D")
    else:
        print("成绩为E")

n = int(input("请输入成绩"))
answer(n)
def answer(n):
    if n >= 5000:
        print("价格是 %f" % (n * 0.8))
    elif n >= 3000:
        print("价格是 %f"% (n * 0.85))
    elif n >= 2000:
        print("价格是 %f"% (n * 0.9))
    elif n >= 1000:
        print("价格是 %f"% (n * 0.95))
    else:
        print("价格是 %f"% n)

n = float(input("请输花销"))
answer(n)
def answer(n):
    if n == 1:
        return 1;
    a = n*(n+1)/2;
    return a+answer(n-1)
n = int(input("请输入"))
print(answer(n))
def answer(n):
    for a in range(1,int(n/3) + 1):
        for b in range(1,int((n - a)/2)):
            c = 100 - a - b;
            if a + b + c ==100 and 3*a + 2*b + c/2 == 100:
                print(f'大马{a}匹,中马{b}匹,小马{c}匹。')
n = int(input("请输入"))
print(answer(n))
def answer(n,i,j,k,m):
    if k>=m : return n
    n = n + 1
    return answer(n,j,k,(i+j+k)/2,m)
n = int(input("请输入"))
print(answer(3,1,2,3,n))
def answer():
    for i in range(1,101):
        if i/10 < 10 and (i*i)%10 == i:
            print("%d 是同构数"% i)
        elif i/100 < 10 and (i*i)%100 == i: 
            print("%d 是同构数"% i)
answer()
def answer(n):
    for i in range(1,n+1):
        print(' '*(n-i)+'+'*(2*i-1))
n=int(input("请输入金字塔层数"))
answer(n)
def answer(n):
    an = 0;
    for i in range(1,n):
        if n % i == 0:
            an = an + i;
    print("结果是",an)
n=int(input("请输入"))
answer(n)
def answer():
    hello = open("hello.txt", "r") 
    hello1 = open("hello1.txt", "w")
    hello1.write(hello.read())
    hello.close()
    hello1.close()
answer()
def answer():
    hello = open("hello.txt", "r") 
    file = ""
    i = 0
    j = 0
    Max = 0;
    Min = 0;
    ii = 0;
    jj = 0;
    while True:
        line = hello.readline()
        
        if not line:
            break
        if i == 0:
            Max = len(line)
            Min = Max
        else:
            if len(line) > Max:
                Max = len(line)
                ii = i
            if len(line) < Min:
                Min = len(line)
                jj = i
                
        i = i + 1;
        if line[0]  == 'P':
            j = j+1;
        file = file + line;
    print("总共有%d行" % i)
    print("大写字母P开头的有%d行" % j)
    print("包含字符最多的在%d和最少的在%d" % (ii+1,jj+1))
    hello.close()
answer()

二.猜单词游戏

笔记

import random
def game():
    words = ("Evolutionarily","python","easy","predictive","Sprite")
    print(
        """
                 欢迎参加猜单词的小游戏
              请把字母组合成一个正确的单词。
        """
        )
    an = 'y'
    while an == 'y' or an =='Y':
        word = random.choice(words)
        correct = word
        jumble = ""
        while word:
            position = random.randrange(len(word))
            jumble = jumble + word[position]
            word = word[:position]+word[(position+1):]
        print("乱序后的单词:",jumble)
        guess = input("\n请输入你的答案")
        while guess !=  correct and guess != "":
            print("小朋友打错了,再接再厉!")
            guess = input("\n继续猜测,如果不想猜,就什么也不输入")
        if guess == correct:
            print("恭喜小朋友!你答对了!")
        an = input("\n是否继续(Y/N)")
            
game()

课后题

import random
def game():
    words = {"hello":"你好","Sprite":"雪碧","China":"中国","english":"英语","snow":"雪"}
    print(
        """
                 欢迎使用词典,输入下面的数字得到不同的功能
                             1.翻译功能
                             2.小游戏
        """
        )
    ch = int(input("\n请输入您的功能:"))
    if ch == 1:
        ch = int(input("\n英->汉请输入0,汉->英请输入1:"))
        if ch == 0:
            english = input("\n请输入您要翻译的英文:")
            print("翻译的结果是:",words[english])
        if ch == 1:
            key_list=[]
            value_list=[]
            chinese = input("\n请输入您要翻译的中文:")
            for key,value in words.items():
                key_list.append(key)
                value_list.append(value)
            print("翻译的结果是:",key_list[value_list.index(chinese)])
    if ch == 2:
        num = 0
        key_list=[]
        value_list=[]
        for key,value in words.items():
            key_list.append(key)
            value_list.append(value)
        print("游戏开始")
        for i in range(0,5):
             position = random.randrange(len(key_list))
             correct = value_list[position]
             guess = input("\n请输入"+key_list[position]+"的翻译:")
             if guess !=  correct and guess != "":
                  print("小朋友打错了,再接再厉!")
             if guess == correct:
                 print("恭喜小朋友!你答对了!")
                 num = num + 1;
        print("你的准确率是%f" % (float(num)/5.0 *100) + "%")
game()

三.发牌游戏

笔记

import random
class Card():
    RANKS = ["A","2","3","4","5","6","7","8",
             "9","10","J","Q","K"]
    SUITS = ["梅花","方块","红桃","黑桃"]
    def __init__(self,rank,suit,face_up = True):
        self.rank = rank;
        self.suit = suit;
        self.is_face_up = face_up
        
    def __str__(self):
        if self.is_face_up:
            rep = self.suit+self.rank
        else:
            rep = "XX"
        return rep
    def pic_order(self):
        if self.rank == "A":
            FaceNum = 1;
        elif self.rank == "J":
            FaceNum = 11;
        elif self.rank == "Q":
            FaceNum = 12;
        elif self.rank == "K":
            FaceNum = 13;
        else:
            FaceNum = int(self.rank)
        if self.suit =="梅花":
            Suit = 1
        elif self.suit =="方块":
            Suit = 2
        elif self.suit =="红桃":
            Suit = 3
        else:
            Suit = 4
        return (Suit - 1)*13 + FaceNum
    def flip(self):
        self.is_face_up = not self.is_face_up
class Hand():
    def __init__(self):
        self.cards = []
    def __str__(self):
        if self.cards:
            rep = ""
            for card in self.cards:
                rep+=str(card)+"\t"
        else:
            rep = "没有牌了"
        return rep
    def clear(self):
        self.cards =[]
    def add(self,card):
        self.cards.append(card)
    def give(self,card,other_hand):
        self.cards.remove(card)
        other_hand.add(card)
class Poke(Hand):
    def populate(self):
        for suit in Card.SUITS:
            for rank in Card.RANKS:
                self.add(Card(rank,suit))
    def shuffle(self):
        random.shuffle(self.cards)
    def deal(self,hands,per_hand = 13):
        for rounds in range(per_hand):
            for hand in hands:
                if self.cards:
                    top_card = self.cards[0]
                    self.cards.remove(top_card)
                    hand.add(top_card)
                else:
                    print("不能继续发牌了")
if __name__ == "__main__":
    print("开始棋牌游戏")
    players =[Hand(),Hand(),Hand(),Hand()]
    pokel = Poke()
    pokel.populate()
    pokel.shuffle()
    pokel.deal(players,13)
    n = 1;
    for hand in players:
        print("牌手",n,end=":")
        print(hand)
        n=n+1
    input("\npress the enter key to exit")

课后题

import random
class Word():
    KEY = ["hello","Sprite","China","english","snow"]
    VALUE = ["你好","雪碧","中国","英语","雪"]
    def get_value(self,key):
        return self.VALUE[self.KEY.index(key)]
    def get_key(self,value):
        return self.KEY[self.VALUE.index(value)]
    def random_get_key(self):
        position = random.randrange(len(self.KEY))
        correct = self.VALUE[position]
        question = self.KEY[position]
        return correct,question
def game():
    print(
        """
                 欢迎使用词典,输入下面的数字得到不同的功能
                             1.翻译功能
                             2.小游戏
        """
        )
    ch = int(input("\n请输入您的功能:"))
    if ch == 1:
        ch = int(input("\n英->汉请输入0,汉->英请输入1:"))
        if ch == 0:
            english = input("\n请输入您要翻译的英文:")
            w = Word()
            print("翻译的结果是:",w.get_value(english))
        if ch == 1:
            chinese = input("\n请输入您要翻译的中文:")
            w = Word()
            print("翻译的结果是:",w.get_key(chinese))
    if ch == 2:
        num = 0
        print("游戏开始")
        for i in range(0,5):
             w = Word()
             correct,question = w.random_get_key()
             guess = input("\n请输入"+question+"的翻译:")
             if guess !=  correct and guess != "":
                  print("小朋友打错了,再接再厉!")
             if guess == correct:
                 print("恭喜小朋友!你答对了!")
                 num = num + 1;
        print("你的准确率是%f" % (float(num)/5.0 *100) + "%")
game()

4.图形界面设计

猜数字游戏代码

import tkinter as tk
import random
number = random.randint(0,1024)
running = True
num = 0
nmaxn = 1024
nminn = 0
def eBtnGuess(event) :
    global nmaxn
    global nminn
    global num
    global running
    if running:
        val_a = int(entry_a.get())
        if val_a == number:
            labelqval("恭喜答对了! ")
            num+=1
            running = False
            numGuess()
        elif val_a< number:
            if val_a > nminn:
                nminn = val_a#修改提示猜测范围的最小数
                num+=1
                labelqval("小了哦,请输入"+str(nminn)+"到"+str(nmaxn)+"之间任意整数:")
        else:
            if val_a < nmaxn:
                    nmaxn = val_a#修改提示猜测范围的最大数
                    num+=1
                    labelqval("大了哦,请输入"+str(nminn)+"到"+str(nmaxn)+"之间任意整数:")
    else:
        labelqval('你已经答对啦……')
def numGuess():
    if num == 1:
        labelqval('厉害!一次答对!')
    elif num< 10:
        labelqval(' = =十次以内就答对了,很棒……尝试次数:'+str(num))
    else:
        labelqval('好吧,您都尝试了超过十次了……尝试次数:'+str(num))
def labelqval(vText) :
    label_val_q.config(label_val_q,text=vText)
def eBtnClose(event):
    root.destroy()
root = tk.Tk (className="猜数字游戏")
root.geometry("400x90+200+200")
label_val_q = tk.Label (root, width="80")
label_val_q.pack(side = "top")
entry_a = tk.Entry(root, width="40")
btnGuess = tk.Button(root,text="猜")
entry_a.pack(side = "left")
entry_a.bind('<Return>' , eBtnGuess)
btnGuess.bind('<Button-1>', eBtnGuess)
btnGuess.pack(side = "left")
btnClose = tk.Button (root,text="关闭")
btnClose.bind('<Button-1>',eBtnClose)    
btnClose.pack(side="left")
labelqval("请输入0~1024的任意整数:")
entry_a.focus_set()
print(number)
root.mainloop()

5.模拟抽牌

from tkinter import Tk,Canvas,PhotoImage
import random
n = 52
def gen_pocker(n):
    x=100
    while(x>0):
        x=x-1
        p1=random.randint(0, n-1)
        p2=random.randint(0,n-1)
        t=pocker[p1]
        pocker[p1]=pocker[p2]
        pocker[p2]=t
    return pocker
pocker=[i for i in range(n)]
pocker=gen_pocker(n)
print(pocker)
(player1,player2,player3,player4)=([],[],[],[])
(p4,p1,p2,p3) =([],[],[],[])
root = Tk()
cv = Canvas(root, bg = 'white', width = 700, height = 600)
imgs=[]
for i in range(1,5):
    for j in range(1,14):
        file1=str(i)+'-'+str(j)+'.gif'
        imgs.insert((i-1)*13+(j-1), PhotoImage(file = file1))
for x in range(13):
    m=x*4
    p1.append( pocker[m] )
    p2.append( pocker[m+1] )
    p3.append( pocker[m+2] )
    p4.append( pocker[m+3] )
p1.sort()
p2.sort()
p3.sort()
p4.sort()
for x in range(0,13):
    img=imgs[p1[x]]
    player1.append(cv.create_image ((200+20*x,80) , image=img))
    img=imgs[p2[x]]
    player2.append(cv.create_image((100,150+20*x),image=img))
    img=imgs[p3[x]]
    player3.append(cv.create_image((200+20*x,500) , image=img))
    img=imgs[p4[x]]
    player4.append(cv.create_image ((560,150+20*x), image=img))
print("player1 : " , player1)
print("player2: " , player2)
print("player3: " , player3)
print("player4:" ,player4)
cv.pack()
root.mainloop()
  1. 总结:主要是了解下游戏是怎么制作的跟复习一下python。整本书剩下的简单翻看了一下,也没有什么新东西。就没认真做题和写代码了。整本书很适合初学者,缺点是太基础。

  2. 建议:编程小白可以认真看一下。