-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame.py
93 lines (72 loc) · 2.71 KB
/
game.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
from __future__ import annotations
import pickle
import random
from typing import Dict, Optional
from warnings import warn
from pyworld.basic import Vector
from pyworld.player import Player
from pyworld.world import Continuum, World
class Core:
def __init__(self, save_file_path: str | None = None) -> None:
world: Optional[World] = None
if save_file_path is not None:
# Have path param, try to open it
try:
with open(save_file_path, mode='rb') as f:
world = pickle.load(f)
assert isinstance(world, World)
except AssertionError:
raise TypeError('Pickled object is not valid World type.')
except pickle.UnpicklingError:
raise TypeError('Save file is invalid.')
except FileNotFoundError:
warn('Save file path is not exist. Create one.')
with open(save_file_path, mode='wb') as f:
pass
except EOFError:
warn('Save file path is broken. Create a new one.')
return self.__init__()
else:
# Set new file path.
rnd_id: int = random.randint(100000, 999999)
save_file_path = "./save-{0}.bin".format(rnd_id)
print("Auto generate new save file: {}".format(save_file_path))
self.ct: Continuum = Continuum(world=world)
self.save_file_path: str = save_file_path
def start(self) -> None:
self.ct.start()
def stop(self, save: bool = True) -> None:
self.ct.stop()
if save:
self.save()
def save(self) -> None:
with open(self.save_file_path, mode="wb") as f:
self.ct.pause()
pickle.dump(self.ct.world, f, protocol=5)
self.ct.resume()
def register(self, username: str, passwd: str) -> Player:
"""
Register a new player entity in the world,
Use random position and username, passwd given.
Return the player object.
"""
p: Player = self.ct.world.world_new_entity(
cls=Player,
pos=Vector.random(),
username=username,
passwd=passwd,
world=self.ct.world,
)
return p
def check_login(self, username: str, passwd: str) -> bool:
"""Check username and passwd is valid"""
if username not in self.ct.world.player_dict:
return False
else:
return (
self.player_dict[username].passwd == passwd
)
@property
def player_dict(self) -> Dict[str, Player]:
"""Shorten the self.ct.world.player_dict."""
return self.ct.world.player_dict