"""保卫萝卜 示例程序 pgzero carrot example program """
# 导入 imports
import pgzrun
from pgzero.builtins import *
import random
import pgzero.screen
screen:pgzero.screen.Screen
import json
from datetime import datetime
class Context():
"""上下文 类"""
def __init__(self):
"""初始化"""
### 常量 ###
self.CELL_SIZE=80 #格子大小 cell size
self.direction_dict = { #方向字典 direction
'up':(0, -1), 'down':(0, 1), 'left':(-1, 0), 'right':(1, 0), '0':(0, 0)}
### 上下文变量 ###
self.bg = Actor('grass960') #背景 background
self.monster_list = [ #怪物列表
Actor('barnacle', topleft=(self.CELL_SIZE*1, self.CELL_SIZE*1))]
self.datetime_str = '' #更新时间(上次,年月日时分秒)
self.hp = 10 #生命值 health point
self.map_list = self.read_csv('p003_carrot.csv') #地图列表 map list
def read_csv(self, csv_filename:str):
"""读取csv"""
lst = []
with open(csv_filename) as f:
for line in f:
lst.append(line.rstrip().split(','))
#print(self.map_list)
return lst
# 全局变量 global variables
ctx = Context()
def road_draw():
"""道路绘制 road draw"""
for cy in range(len(ctx.map_list)):
for cx in range(len(ctx.map_list[cy])):
if ctx.map_list[cy][cx] != '0': #不是空的含义是路
screen.draw.filled_rect(Rect((ctx.CELL_SIZE*cx, ctx.CELL_SIZE*cy), (ctx.CELL_SIZE, ctx.CELL_SIZE)), (0, 128, 0))
# pgzero全局变量 pgzero global variables
WIDTH=ctx.CELL_SIZE*12
HEIGHT=ctx.CELL_SIZE*9
TITLE='Carrot'
# pgzero函数 pgzero functions(update, draw, on key ... , on mouse ...)
def update():
"""更新 update"""
# 每秒执行:校验与存储的上一秒时间不同时执行
now_str = datetime.strftime(datetime.now(), "%Y%m%dT%H:%M:%S")
if now_str != ctx.datetime_str:
ctx.datetime_str = now_str
# 对每个怪物
for monster in ctx.monster_list:
#找到网格下
cx = int(monster.x // ctx.CELL_SIZE)
cy = int(monster.y // ctx.CELL_SIZE)
#获取地图格子
direction = ctx.map_list[cy][cx]
print(f"direction {direction}, x {monster.x}, y {monster.y}")
if direction == 'stop': #停
ctx.monster_list.remove(monster)
continue
elif direction == '0': #空
pass
else: #路
monster.x += ctx.direction_dict[direction][0]*ctx.CELL_SIZE
monster.y += ctx.direction_dict[direction][1]*ctx.CELL_SIZE
def draw():
"""draw"""
screen.fill((255,255,255)) #画
ctx.bg.draw() #背景
road_draw() #路
for monster in ctx.monster_list: #怪物
monster.draw()
screen.draw.text('HP: ' + str(ctx.hp), (15,10), color=(255,255,255), fontsize=30) #生命值
# pgzero startup
pgzrun.go()
【游戏】Pgzero塔防示例程序
最新推荐文章于 2025-02-19 22:47:08 发布