"""保卫萝卜 示例程序 pgzero carrot example program """
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
self.direction_dict = {
'up':(0, -1), 'down':(0, 1), 'left':(-1, 0), 'right':(1, 0), '0':(0, 0)}
self.bg = Actor('grass960')
self.monster_list = [
Actor('barnacle', topleft=(self.CELL_SIZE*1, self.CELL_SIZE*1))]
self.datetime_str = ''
self.hp = 10
self.map_list = self.read_csv('p003_carrot.csv')
def read_csv(self, csv_filename:str):
"""读取csv"""
lst = []
with open(csv_filename) as f:
for line in f:
lst.append(line.rstrip().split(','))
return lst
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))
WIDTH=ctx.CELL_SIZE*12
HEIGHT=ctx.CELL_SIZE*9
TITLE='Carrot'
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)
pgzrun.go()