-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom_player.py
More file actions
105 lines (86 loc) · 3.14 KB
/
Copy pathrandom_player.py
File metadata and controls
105 lines (86 loc) · 3.14 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
import json
import os
import random
import socket
import sys
sys.path.append(os.getcwd())
from lib.player_base import Player, PlayerShip
class RandomPlayer(Player):
def __init__(self, seed=0):
random.seed(seed)
# フィールドを2x2の配列として持っている.
self.field = [[i, j] for i in range(Player.FIELD_SIZE)
for j in range(Player.FIELD_SIZE)]
# 初期配置を非復元抽出でランダムに決める.
ps = random.sample(self.field, 3)
positions = {'w': ps[0], 'c': ps[1], 's': ps[2]}
super().__init__(positions)
#
# 移動か攻撃かランダムに決める.
# どれがどこへ移動するか,あるいはどこに攻撃するかもランダム.
#
def action(self):
act = random.choice(["move", "attack"])
if act == "move":
ship = random.choice(list(self.ships.values()))
to = random.choice(self.field)
while not ship.can_reach(to) or not self.overlap(to) is None:
to = random.choice(self.field)
return json.dumps(self.move(ship.type, to))
elif act == "attack":
to = random.choice(self.field)
while not self.can_attack(to):
to = random.choice(self.field)
return json.dumps(self.attack(to))
# 仕様に従ってサーバとソケット通信を行う.
def main(host, port, seed=0):
assert isinstance(host, str) and isinstance(port, int)
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
sock.connect((host, port))
with sock.makefile(mode='rw', buffering=1) as sockfile:
get_msg = sockfile.readline()
print(get_msg)
player = RandomPlayer()
sockfile.write(player.initial_condition()+'\n')
while True:
info = sockfile.readline().rstrip()
print(info)
if info == "your turn":
sockfile.write(player.action()+'\n')
get_msg = sockfile.readline()
player.update(get_msg)
elif info == "waiting":
get_msg = sockfile.readline()
player.update(get_msg)
elif info == "you win":
break
elif info == "you lose":
break
elif info == "even":
break
else:
raise RuntimeError("unknown information")
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser(description="Sample Player for Submaline Game")
parser.add_argument(
"host",
metavar="H",
type=str,
help="Hostname of the server. E.g., localhost",
)
parser.add_argument(
"port",
metavar="P",
type=int,
help="Port of the server. E.g., 2000",
)
parser.add_argument(
"--seed",
type=int,
help="Random seed of the player",
required=False,
default=0,
)
args = parser.parse_args()
main(args.host, args.port, seed=args.seed)