廢話不說,上代碼
反恐精英
import random # 定義隨機
class Person:
def __init__(self, name):
self.name = name
self.hp = 100 # 共有變數 hp
def __str__(self):
return "%s當前生命值為%d" % (self.name, self.hp) # 回傳物件呼叫return 顯示當前值
class Hero(Person):
def fire(self, p):
hit = random.randint(1,100) # 定義hit為命中率 產生亂數
if hit > 20: # 命中率為80
if p.hp == 0:
print("%s都死了不要打了" % p.name) # 判斷物件的血量如果等于0時輸出在鞭尸
else:
damage = random.randint(40, 60) # 判斷打中后 產生的隨機傷害值
print("%s向%s開了一槍,掉了%d血" % (self.name, p.name, damage))
if p.hp < damage: # 判斷血量小于傷害值時 血量賦值為0
p.hp = 0
else:
p.hp -= damage # 傷害值 - 血量值 = 當前血量值
else:
print("沒打中%s" % self.name)
def __str__(self):
state = "" # 定義一個字串state
if self.hp == 100:
state = "無傷"
elif self.hp > 70 and self.hp < 100:
state = "輕傷"
elif self.hp > 1 and self.hp < 70:
state = "重傷"
elif self.hp <= 0:
state = "掛了"
return "%s的當前狀態為%s" % (self.name, state)
class Bad(Person):
def fire(self, p):
damage = random.randint(1,10)
hit = random.randint(1,100)
if hit > 90:
print("%s向%s開了一槍,掉了%d血" % (self.name, p.name, damage))
if p.hp < damage:
p.hp = 0
else:
p.hp -= damage
else:
print("%s沒打中警察" % self.name)
def main():
h = Hero("警察")
bad1 = Bad("路人甲")
bad2 = Bad("土匪已")
bad3 = Bad("炮灰丙")
while True:
x = random.randint(1, 3) # 定義亂數,等于1 時向bad1開槍.....
if x == 1:
h.fire(bad1)
elif x == 2:
h.fire(bad2)
elif x == 3:
h.fire(bad3)
bad1.fire(h)
bad2.fire(h)
bad3.fire(h)
print(h)
print(bad1)
print(bad2)
print(bad3)
print()
if h.hp <= 0:
print("%s死亡,游戲結束" % h.name)
break
if bad1.hp <= 0 and bad2.hp <= 0 and bad3.hp <= 0:
print("恐怖分子全部死亡")
break
main()
貪吃蛇(須登入)
先是登入界面
import pygame
import tkinter as tk
import pickle
import tkinter.messagebox
from PIL import Image, ImageTk
# 設定視窗---最開始的母體視窗
window = tk.Tk() # 建立一個視窗
window.title('歡迎登錄')
window.geometry('500x500') # 視窗大小為300x200
# 畫布
canvas = tk.Canvas(window, height=200, width=900)
# 兩個文字標簽,用戶名和密碼兩個部分
tk.Label(window, text='用戶名').place(x=100, y=150)
tk.Label(window, text='密 碼').place(x=100, y=190)
var_usr_name = tk.StringVar() # 講文本框的內容,定義為字串型別
var_usr_name.set('123') # 設定默認值
var_usr_pwd = tk.StringVar()
# 第一個輸入框-用來輸入用戶名的,
# textvariable 獲取文本框的內容
entry_usr_name = tk.Entry(window, textvariable=var_usr_name)
entry_usr_name.place(x=160, y=150)
# 第二個輸入框-用來輸入密碼的,
entry_usr_pwd = tk.Entry(window, textvariable=var_usr_pwd, show='*')
entry_usr_pwd.place(x=160, y=190)
def usr_login():
usr_name = var_usr_name.get()
usr_pwd = var_usr_pwd.get()
try:
with open('usrs_info.pickle', 'rb') as usr_file:
usrs_info = pickle.load(usr_file)
except FileNotFoundError:
with open('usrs_info.pickle', 'wb') as usr_file:
usrs_info = {'admin': 'admin'}
pickle.dump(usrs_info, usr_file)
if usr_name in usrs_info:
if usr_pwd == usrs_info[usr_name]:
tk.messagebox.showinfo(
title='歡迎光臨', message=usr_name + ': 關閉開始界面就可進入游戲')
else:
tk.messagebox.showinfo(message='錯誤提示:密碼不對,請重試')
else:
is_sign_up = tk.messagebox.askyesno('提示', '你還沒有注冊,請先注冊')
print(is_sign_up)
if is_sign_up:
usr_sign_up()
# 注冊按鈕
def usr_sign_up():
def sign_to_Mofan_Python():
np = new_pwd.get()
npf = new_pwd_confirm.get()
nn = new_name.get()
# 上面是獲取資料,下面是查看一下是否重復注冊過
with open('usrs_info.pickle', 'rb') as usr_file:
exist_usr_info = pickle.load(usr_file)
if np != npf:
tk.messagebox.showerror('錯誤提示', '密碼和確認密碼必須一樣')
elif nn in exist_usr_info:
tk.messagebox.showerror('錯誤提示', '用戶名早就注冊了!')
else:
exist_usr_info[nn] = np
with open('usrs_info.pickle', 'wb') as usr_file:
pickle.dump(exist_usr_info, usr_file)
tk.messagebox.showinfo('歡迎', '你已經成功注冊了')
window_sign_up.destroy()
# 點擊注冊之后,會彈出這個視窗界面,
window_sign_up = tk.Toplevel(window)
window_sign_up.title('歡迎注冊')
window_sign_up.geometry('360x200') # 中間是x,而不是*號
# 用戶名框--這里輸入用戶名框,
new_name = tk.StringVar()
new_name.set('123') # 設定的是默認值
tk.Label(window_sign_up, text='用戶名').place(x=10, y=10)
entry_new_name = tk.Entry(window_sign_up, textvariable=new_name)
entry_new_name.place(x=100, y=10)
# 新密碼框--這里輸入注冊時候的密碼
new_pwd = tk.StringVar()
tk.Label(window_sign_up, text='密 碼').place(x=10, y=50)
entry_usr_pwd = tk.Entry(window_sign_up, textvariable=new_pwd, show='*')
entry_usr_pwd.place(x=100, y=50)
# 密碼確認框
new_pwd_confirm = tk.StringVar()
tk.Label(window_sign_up, text='確認密碼').place(x=10, y=90)
entry_usr_pwd_confirm = tk.Entry(
window_sign_up, textvariable=new_pwd_confirm, show='*')
entry_usr_pwd_confirm.place(x=100, y=90)
btn_confirm_sign_up = tk.Button(
window_sign_up, text=' 注 冊 ', command=sign_to_Mofan_Python)
btn_confirm_sign_up.place(x=120, y=130)
# 創建注冊和登錄按鈕
btn_login = tk.Button(window, text=' 登 錄 ', command=usr_login)
btn_login.place(x=150, y=230) # 用place來處理按鈕的位置資訊,
btn_sign_up = tk.Button(window, text=' 注 冊 ', command=usr_sign_up)
btn_sign_up.place(x=250, y=230)
window.mainloop()
再是游戲
from os import path
from sys import exit
from time import sleep
from random import choice
from itertools import product
from pygame.locals import QUIT, KEYDOWN
def direction_check(moving_direction, change_direction):
directions = [['up', 'down'], ['left', 'right']]
if moving_direction in directions[0] and change_direction in directions[1]:
return change_direction
elif moving_direction in directions[1] and change_direction in directions[0]:
return change_direction
return moving_direction
class Snake:
colors = list(product([0, 64, 128, 192, 255], repeat=3))[1:-1]
def __init__(self):
self.map = {(x, y): 0 for x in range(32) for y in range(24)}
self.body = [[100, 100], [120, 100], [140, 100]]
self.head = [140, 100]
self.food = []
self.food_color = []
self.moving_direction = 'right'
self.speed = 4
self.generate_food()
self.game_started = False
def check_game_status(self):
if self.body.count(self.head) > 1:
return True
if self.head[0] < 0 or self.head[0] > 620 or self.head[1] < 0 or self.head[1] > 460:
return True
return False
def move_head(self):
moves = {
'right': (20, 0),
'up': (0, -20),
'down': (0, 20),
'left': (-20, 0)
}
step = moves[self.moving_direction]
self.head[0] += step[0]
self.head[1] += step[1]
def generate_food(self):
self.speed = len(
self.body) // 16 if len(self.body) // 16 > 4 else self.speed
for seg in self.body:
x, y = seg
self.map[x // 20, y // 20] = 1
empty_pos = [pos for pos in self.map.keys() if not self.map[pos]]
result = choice(empty_pos)
self.food_color = list(choice(self.colors))
self.food = [result[0] * 20, result[1] * 20]
def main():
key_direction_dict = {
119: 'up', # W
115: 'down', # S
97: 'left', # A
100: 'right', # D
273: 'up', # UP
274: 'down', # DOWN
276: 'left', # LEFT
275: 'right', # RIGHT
}
fps_clock = pygame.time.Clock()
pygame.init()
pygame.mixer.init()
snake = Snake()
sound = False
if path.exists('eat.wav'):
sound_wav = pygame.mixer.Sound("eat.wav")
sound = True
title_font = pygame.font.SysFont('simsunnsimsun', 32)
welcome_words = title_font.render(
'貪吃蛇', True, (0, 0, 0), (255, 255, 255))
tips_font = pygame.font.SysFont('simsunnsimsun', 20)
start_game_words = tips_font.render(
'點擊開始', True, (0, 0, 0), (255, 255, 255))
close_game_words = tips_font.render(
'按ESC退出', True, (0, 0, 0), (255, 255, 255))
gameover_words = title_font.render(
'游戲結束', True, (205, 92, 92), (255, 255, 255))
win_words = title_font.render(
'蛇很長了,你贏了!', True, (0, 0, 205), (255, 255, 255))
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption('貪吃蛇')
new_direction = snake.moving_direction
while 1:
for event in pygame.event.get():
if event.type == QUIT:
exit()
elif event.type == KEYDOWN:
if event.key == 27:
exit()
if snake.game_started and event.key in key_direction_dict:
direction = key_direction_dict[event.key]
new_direction = direction_check(
snake.moving_direction, direction)
elif (not snake.game_started) and event.type == pygame.MOUSEBUTTONDOWN:
x, y = pygame.mouse.get_pos()
if 213 <= x <= 422 and 304 <= y <= 342:
snake.game_started = True
screen.fill((255, 255, 255))
if snake.game_started:
snake.moving_direction = new_direction # 在這里賦值,而不是在event事件的回圈中賦值,避免按鍵太快
snake.move_head()
snake.body.append(snake.head[:])
if snake.head == snake.food:
if sound:
sound_wav.play()
snake.generate_food()
else:
snake.body.pop(0)
for seg in snake.body:
pygame.draw.rect(screen, [0, 0, 0], [
seg[0], seg[1], 20, 20], 0)
pygame.draw.rect(screen, snake.food_color, [
snake.food[0], snake.food[1], 20, 20], 0)
if snake.check_game_status():
screen.blit(gameover_words, (241, 310))
pygame.display.update()
snake = Snake()
new_direction = snake.moving_direction
sleep(3)
elif len(snake.body) == 512:
screen.blit(win_words, (33, 210))
pygame.display.update()
snake = Snake()
new_direction = snake.moving_direction
sleep(3)
else:
screen.blit(welcome_words, (240, 150))
screen.blit(start_game_words, (246, 310))
screen.blit(close_game_words, (246, 350))
pygame.display.update()
fps_clock.tick(snake.speed)
if __name__ == '__main__':
main()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/293823.html
標籤:其他
