Best Python code snippet using sure_python
test_qgsshortcutsmanager.py
Source:test_qgsshortcutsmanager.py
1# -*- coding: utf-8 -*-2"""QGIS Unit tests for QgsActionManager.3.. note:: This program is free software; you can redistribute it and/or modify4it under the terms of the GNU General Public License as published by5the Free Software Foundation; either version 2 of the License, or6(at your option) any later version.7"""8__author__ = 'Nyall Dawson'9__date__ = '28/05/2016'10__copyright__ = 'Copyright 2016, The QGIS Project'11import qgis # NOQA12from qgis.core import QgsSettings13from qgis.gui import QgsShortcutsManager, QgsGui14from qgis.PyQt.QtCore import QCoreApplication15from qgis.PyQt.QtWidgets import QWidget, QAction, QShortcut16from qgis.testing import start_app, unittest17class TestQgsShortcutsManager(unittest.TestCase):18 @classmethod19 def setUpClass(cls):20 """Run before all tests"""21 QCoreApplication.setOrganizationName("QGIS_Test")22 QCoreApplication.setOrganizationDomain("QGIS_TestPyQgsWFSProviderGUI.com")23 QCoreApplication.setApplicationName("QGIS_TestPyQgsWFSProviderGUI")24 QgsSettings().clear()25 start_app()26 def testInstance(self):27 """ test retrieving global instance """28 self.assertTrue(QgsGui.shortcutsManager())29 # register an action to the singleton30 action = QAction('test', None)31 QgsGui.shortcutsManager().registerAction(action)32 # check that the same instance is returned33 self.assertEqual(QgsGui.shortcutsManager().listActions(), [action])34 s2 = QgsShortcutsManager()35 self.assertEqual(s2.listActions(), [])36 def testConstructor(self):37 """ test constructing managers"""38 s = QgsShortcutsManager(None, '/my_path/')39 self.assertEqual(s.settingsPath(), '/my_path/')40 def testSettingsPath(self):41 """ test that settings path is respected """42 QgsSettings().clear()43 s1 = QgsShortcutsManager(None, '/path1/')44 s2 = QgsShortcutsManager(None, '/path2/')45 action1 = QAction('action', None)46 s1.registerAction(action1)47 s1.setKeySequence(action1, 'B')48 action2 = QAction('action', None)49 s2.registerAction(action2)50 s2.setKeySequence(action2, 'C')51 # test retrieving52 r1 = QgsShortcutsManager(None, '/path1/')53 r2 = QgsShortcutsManager(None, '/path2/')54 raction1 = QAction('action', None)55 r1.registerAction(raction1)56 raction2 = QAction('action', None)57 r2.registerAction(raction2)58 self.assertEqual(raction1.shortcut().toString(), 'B')59 self.assertEqual(raction2.shortcut().toString(), 'C')60 def testRegisterAction(self):61 """ test registering actions """62 QgsSettings().clear()63 s = QgsShortcutsManager(None)64 action1 = QAction('action1', None)65 action1.setShortcut('x')66 self.assertTrue(s.registerAction(action1, 'A'))67 action2 = QAction('action2', None)68 action2.setShortcut('y')69 self.assertTrue(s.registerAction(action2, 'B'))70 self.assertCountEqual(s.listActions(), [action1, action2])71 # try re-registering an existing action - should fail, but leave action registered72 self.assertFalse(s.registerAction(action2, 'B'))73 self.assertCountEqual(s.listActions(), [action1, action2])74 # actions should have been set to default sequences75 self.assertEqual(action1.shortcut().toString(), 'A')76 self.assertEqual(action2.shortcut().toString(), 'B')77 # test that adding an action should set its shortcut automatically78 s.setKeySequence('action1', 'C')79 s.setKeySequence('action2', 'D')80 s = QgsShortcutsManager(None)81 self.assertTrue(s.registerAction(action1, 'A'))82 self.assertTrue(s.registerAction(action2, 'B'))83 # actions should have been set to previous shortcuts84 self.assertEqual(action1.shortcut().toString(), 'C')85 self.assertEqual(action2.shortcut().toString(), 'D')86 # test registering an action containing '&' in name87 s = QgsShortcutsManager(None)88 action = QAction('&action1', None)89 self.assertTrue(s.registerAction(action))90 self.assertEqual(action1.shortcut().toString(), 'C')91 def testRegisterShortcut(self):92 """ test registering shortcuts """93 QgsSettings().clear()94 s = QgsShortcutsManager(None)95 shortcut1 = QShortcut(None)96 shortcut1.setKey('x')97 shortcut1.setObjectName('shortcut1')98 self.assertTrue(s.registerShortcut(shortcut1, 'A'))99 shortcut2 = QShortcut(None)100 shortcut2.setKey('y')101 shortcut2.setObjectName('shortcut2')102 self.assertTrue(s.registerShortcut(shortcut2, 'B'))103 # shortcuts should have been set to default sequences104 self.assertEqual(shortcut1.key().toString(), 'A')105 self.assertEqual(shortcut2.key().toString(), 'B')106 # test that adding a shortcut should set its sequence automatically107 s.setKeySequence(shortcut1, 'C')108 s.setKeySequence(shortcut2, 'D')109 s = QgsShortcutsManager(None)110 self.assertTrue(s.registerShortcut(shortcut1, 'A'))111 self.assertTrue(s.registerShortcut(shortcut2, 'B'))112 # shortcuts should have been set to previous sequences113 self.assertEqual(shortcut1.key().toString(), 'C')114 self.assertEqual(shortcut2.key().toString(), 'D')115 def testRegisterAll(self):116 """ test registering all children """117 w = QWidget()118 action1 = QAction('action1', w)119 shortcut1 = QShortcut(w)120 shortcut1.setObjectName('shortcut1')121 w2 = QWidget(w)122 action2 = QAction('action2', w2)123 shortcut2 = QShortcut(w2)124 shortcut2.setObjectName('shortcut2')125 # recursive126 s = QgsShortcutsManager()127 s.registerAllChildActions(w, True)128 self.assertEqual(set(s.listActions()), set([action1, action2]))129 s.registerAllChildShortcuts(w, True)130 self.assertEqual(set(s.listShortcuts()), set([shortcut1, shortcut2]))131 # non recursive132 s = QgsShortcutsManager()133 s.registerAllChildActions(w, False)134 self.assertEqual(set(s.listActions()), set([action1]))135 s.registerAllChildShortcuts(w, False)136 self.assertEqual(set(s.listShortcuts()), set([shortcut1]))137 # recursive138 s = QgsShortcutsManager()139 s.registerAllChildren(w, True)140 self.assertEqual(set(s.listActions()), set([action1, action2]))141 self.assertEqual(set(s.listShortcuts()), set([shortcut1, shortcut2]))142 # non recursive143 s = QgsShortcutsManager()144 s.registerAllChildren(w, False)145 self.assertEqual(set(s.listActions()), set([action1]))146 self.assertEqual(set(s.listShortcuts()), set([shortcut1]))147 def testUnregister(self):148 """ test unregistering from manager """149 QgsSettings().clear()150 s = QgsShortcutsManager(None)151 shortcut1 = QShortcut(None)152 shortcut1.setKey('x')153 shortcut1.setObjectName('shortcut1')154 shortcut2 = QShortcut(None)155 shortcut2.setKey('y')156 shortcut2.setObjectName('shortcut2')157 action1 = QAction('action1', None)158 action1.setShortcut('x')159 action2 = QAction('action2', None)160 action2.setShortcut('y')161 # try unregistering objects not registered in manager162 self.assertFalse(s.unregisterShortcut(shortcut1))163 self.assertFalse(s.unregisterAction(action1))164 # try unregistering objects from manager165 s.registerShortcut(shortcut1)166 s.registerShortcut(shortcut2)167 s.registerAction(action1)168 s.registerAction(action2)169 self.assertEqual(set(s.listActions()), set([action1, action2]))170 self.assertEqual(set(s.listShortcuts()), set([shortcut1, shortcut2]))171 self.assertTrue(s.unregisterAction(action1))172 self.assertTrue(s.unregisterShortcut(shortcut1))173 self.assertEqual(set(s.listActions()), set([action2]))174 self.assertEqual(set(s.listShortcuts()), set([shortcut2]))175 self.assertTrue(s.unregisterAction(action2))176 self.assertTrue(s.unregisterShortcut(shortcut2))177 def testList(self):178 """ test listing registered objects """179 QgsSettings().clear()180 s = QgsShortcutsManager(None)181 self.assertEqual(s.listActions(), [])182 self.assertEqual(s.listShortcuts(), [])183 self.assertEqual(s.listAll(), [])184 shortcut1 = QShortcut(None)185 shortcut2 = QShortcut(None)186 action1 = QAction('action1', None)187 action2 = QAction('action2', None)188 s.registerShortcut(shortcut1)189 s.registerShortcut(shortcut2)190 s.registerAction(action1)191 s.registerAction(action2)192 self.assertEqual(set(s.listActions()), set([action1, action2]))193 self.assertEqual(set(s.listShortcuts()), set([shortcut1, shortcut2]))194 self.assertEqual(set(s.listAll()), set([action1, action2, shortcut1, shortcut2]))195 def testDefault(self):196 """ test retrieving default sequences """197 QgsSettings().clear()198 s = QgsShortcutsManager(None)199 shortcut1 = QShortcut(None)200 shortcut2 = QShortcut(None)201 action1 = QAction('action1', None)202 action2 = QAction('action2', None)203 # test while not yet registered204 self.assertEqual(s.defaultKeySequence(shortcut1), '')205 self.assertEqual(s.defaultKeySequence(action1), '')206 self.assertEqual(s.objectDefaultKeySequence(shortcut1), '')207 self.assertEqual(s.objectDefaultKeySequence(action1), '')208 # now register them209 s.registerShortcut(shortcut1, 'A')210 s.registerShortcut(shortcut2, 'B')211 s.registerAction(action1, 'C')212 s.registerAction(action2, 'D')213 self.assertEqual(s.defaultKeySequence(shortcut1), 'A')214 self.assertEqual(s.defaultKeySequence(shortcut2), 'B')215 self.assertEqual(s.defaultKeySequence(action1), 'C')216 self.assertEqual(s.defaultKeySequence(action2), 'D')217 self.assertEqual(s.objectDefaultKeySequence(shortcut1), 'A')218 self.assertEqual(s.objectDefaultKeySequence(shortcut2), 'B')219 self.assertEqual(s.objectDefaultKeySequence(action1), 'C')220 self.assertEqual(s.objectDefaultKeySequence(action2), 'D')221 def testSetSequence(self):222 """ test setting key sequences """223 QgsSettings().clear()224 s = QgsShortcutsManager(None)225 shortcut1 = QShortcut(None)226 shortcut1.setObjectName('shortcut1')227 shortcut2 = QShortcut(None)228 shortcut2.setObjectName('shortcut2')229 action1 = QAction('action1', None)230 action2 = QAction('action2', None)231 s.registerShortcut(shortcut1, 'A')232 s.registerShortcut(shortcut2, 'B')233 s.registerAction(action1, 'C')234 s.registerAction(action2, 'D')235 # test setting by action/shortcut236 self.assertTrue(s.setKeySequence(shortcut1, 'E'))237 self.assertTrue(s.setKeySequence(shortcut2, 'F'))238 self.assertTrue(s.setKeySequence(action1, 'G'))239 self.assertTrue(s.setKeySequence(action2, 'H'))240 # test that action/shortcuts have been updated241 self.assertEqual(shortcut1.key().toString(), 'E')242 self.assertEqual(shortcut2.key().toString(), 'F')243 self.assertEqual(action1.shortcut().toString(), 'G')244 self.assertEqual(action2.shortcut().toString(), 'H')245 # new manager246 s = QgsShortcutsManager(None)247 # new shortcuts248 shortcut1 = QShortcut(None)249 shortcut1.setObjectName('shortcut1')250 shortcut2 = QShortcut(None)251 shortcut2.setObjectName('shortcut2')252 action1 = QAction('action1', None)253 action2 = QAction('action2', None)254 # register them255 s.registerShortcut(shortcut1, 'A')256 s.registerShortcut(shortcut2, 'B')257 s.registerAction(action1, 'C')258 s.registerAction(action2, 'D')259 # check that previously set sequence has been restored260 self.assertEqual(shortcut1.key().toString(), 'E')261 self.assertEqual(shortcut2.key().toString(), 'F')262 self.assertEqual(action1.shortcut().toString(), 'G')263 self.assertEqual(action2.shortcut().toString(), 'H')264 # same test, using setObjectKeySequence265 QgsSettings().clear()266 s = QgsShortcutsManager(None)267 shortcut1 = QShortcut(None)268 shortcut1.setObjectName('shortcut1')269 action1 = QAction('action1', None)270 s.registerShortcut(shortcut1, 'A')271 s.registerAction(action1, 'C')272 self.assertTrue(s.setObjectKeySequence(shortcut1, 'E'))273 self.assertTrue(s.setObjectKeySequence(action1, 'G'))274 self.assertEqual(shortcut1.key().toString(), 'E')275 self.assertEqual(action1.shortcut().toString(), 'G')276 s = QgsShortcutsManager(None)277 shortcut1 = QShortcut(None)278 shortcut1.setObjectName('shortcut1')279 action1 = QAction('action1', None)280 s.registerShortcut(shortcut1, 'A')281 s.registerAction(action1, 'C')282 self.assertEqual(shortcut1.key().toString(), 'E')283 self.assertEqual(action1.shortcut().toString(), 'G')284 # same test, using setKeySequence by name285 QgsSettings().clear()286 s = QgsShortcutsManager(None)287 shortcut1 = QShortcut(None)288 shortcut1.setObjectName('shortcut1')289 action1 = QAction('action1', None)290 s.registerShortcut(shortcut1, 'A')291 s.registerAction(action1, 'C')292 self.assertFalse(s.setKeySequence('invalid_name', 'E'))293 self.assertTrue(s.setKeySequence('shortcut1', 'E'))294 self.assertTrue(s.setKeySequence('action1', 'G'))295 self.assertEqual(shortcut1.key().toString(), 'E')296 self.assertEqual(action1.shortcut().toString(), 'G')297 s = QgsShortcutsManager(None)298 shortcut1 = QShortcut(None)299 shortcut1.setObjectName('shortcut1')300 action1 = QAction('action1', None)301 s.registerShortcut(shortcut1, 'A')302 s.registerAction(action1, 'C')303 self.assertEqual(shortcut1.key().toString(), 'E')304 self.assertEqual(action1.shortcut().toString(), 'G')305 def testBySequence(self):306 """ test retrieving by sequence """307 QgsSettings().clear()308 shortcut1 = QShortcut(None)309 shortcut1.setObjectName('shortcut1')310 shortcut2 = QShortcut(None)311 shortcut2.setObjectName('shortcut2')312 action1 = QAction('action1', None)313 action2 = QAction('action2', None)314 s = QgsShortcutsManager(None)315 self.assertFalse(s.actionForSequence('E'))316 self.assertFalse(s.objectForSequence('F'))317 s.registerShortcut(shortcut1, 'E')318 s.registerShortcut(shortcut2, 'A')319 s.registerAction(action1, 'F')320 s.registerAction(action2, 'B')321 # use another way of registering sequences322 self.assertTrue(s.setKeySequence(shortcut2, 'G'))323 self.assertTrue(s.setKeySequence(action2, 'H'))324 self.assertEqual(s.objectForSequence('E'), shortcut1)325 self.assertEqual(s.objectForSequence('F'), action1)326 self.assertEqual(s.objectForSequence('G'), shortcut2)327 self.assertEqual(s.objectForSequence('H'), action2)328 self.assertFalse(s.objectForSequence('A'))329 self.assertFalse(s.objectForSequence('B'))330 self.assertEqual(s.shortcutForSequence('E'), shortcut1)331 self.assertFalse(s.shortcutForSequence('F'))332 self.assertEqual(s.shortcutForSequence('G'), shortcut2)333 self.assertFalse(s.shortcutForSequence('H'))334 self.assertFalse(s.actionForSequence('E'))335 self.assertEqual(s.actionForSequence('F'), action1)336 self.assertFalse(s.actionForSequence('G'))337 self.assertEqual(s.actionForSequence('H'), action2)338 def testByName(self):339 """" test retrieving actions and shortcuts by name """340 QgsSettings().clear()341 shortcut1 = QShortcut(None)342 shortcut1.setObjectName('shortcut1')343 shortcut2 = QShortcut(None)344 shortcut2.setObjectName('shortcut2')345 action1 = QAction('action1', None)346 action2 = QAction('action2', None)347 s = QgsShortcutsManager(None)348 self.assertFalse(s.actionByName('action1'))349 self.assertFalse(s.shortcutByName('shortcut1'))350 s.registerShortcut(shortcut1)351 s.registerShortcut(shortcut2)352 s.registerAction(action1)353 s.registerAction(action2)354 self.assertEqual(s.shortcutByName('shortcut1'), shortcut1)355 self.assertFalse(s.shortcutByName('action1'))356 self.assertEqual(s.shortcutByName('shortcut2'), shortcut2)357 self.assertFalse(s.shortcutByName('action2'))358 self.assertFalse(s.actionByName('shortcut1'))359 self.assertEqual(s.actionByName('action1'), action1)360 self.assertFalse(s.actionByName('shortcut2'))361 self.assertEqual(s.actionByName('action2'), action2)362 def testTooltip(self):363 """" test action tooltips """364 action1 = QAction('action1', None)365 action1.setToolTip('my tooltip')366 action2 = QAction('action2', None)367 action2.setToolTip('my multiline\ntooltip')368 action3 = QAction('action3', None)369 action3.setToolTip('my tooltip (Ctrl+S)')370 s = QgsShortcutsManager(None)371 s.registerAction(action1)372 s.registerAction(action2)373 s.registerAction(action3, 'Ctrl+S')374 self.assertEqual(action1.toolTip(), '<b>my tooltip</b>')375 self.assertEqual(action2.toolTip(), '<b>my multiline</b><p>tooltip</p>')376 self.assertEqual(action3.toolTip(), '<b>my tooltip </b> (Ctrl+S)')377if __name__ == '__main__':...
agent.py
Source:agent.py
1import numpy as np2import tensorflow as tf3class DQNAgent:4 """Class implementing DQN."""5 def __init__(self,6 online_model,7 target_model,8 memory,9 num_actions,10 gamma,11 target_update_freq,12 update_target_params_ops,13 batch_size,14 learning_rate):15 self._online_model = online_model16 self._target_model = target_model17 self._memory = memory18 self._num_actions = num_actions19 self._gamma = gamma20 self._target_update_freq = target_update_freq21 self._update_target_params_ops = update_target_params_ops22 self._batch_size = batch_size23 self._learning_rate = learning_rate24 self._update_times = 025 self._action1_ph = tf.placeholder(tf.int32, [None, 2], name='action1_ph')26 self._action2_ph = tf.placeholder(tf.int32, [None, 2], name='action2_ph')27 self._reward_ph = tf.placeholder(tf.float32, name='reward_ph')28 self._is_terminal_ph = tf.placeholder(tf.float32, name='is_terminal_ph')29 self._action1_chosen_by_online_ph = tf.placeholder(tf.int32, [None, 2], name='action1_chosen_by_online_ph')30 self._action2_chosen_by_online_ph = tf.placeholder(tf.int32, [None, 2], name='action2_chosen_by_online_ph')31 self._error_op, self._train_op = self._get_error_and_train_op(self._reward_ph,32 self._is_terminal_ph,33 self._action1_ph,34 self._action2_ph,35 self._action1_chosen_by_online_ph,36 self._action2_chosen_by_online_ph)37 def select_action(self, sess, state, model):38 """Select the action based on the current state."""39 feed_dict = {model['input_frames']: [state]}40 action1 = sess.run(model['action1'], feed_dict=feed_dict)41 action2 = sess.run(model['action2'], feed_dict=feed_dict)42 return action1, action243 def get_mean_max_Q(self, sess, samples):44 mean_max1, mean_max2 = [], []45 INCREMENT = 100046 for i in range(0, len(samples), INCREMENT):47 feed_dict = {self._online_model['input_frames']:48 samples[i: i + INCREMENT].astype(np.float32)}49 mean_max1.append(sess.run(self._online_model['mean_max_Q1'],50 feed_dict=feed_dict))51 mean_max2.append(sess.run(self._online_model['mean_max_Q2'],52 feed_dict=feed_dict))53 return np.mean(mean_max1), np.mean(mean_max2)54 def minimize_and_clip(self, optimizer, objective, total_n_streams):55 gradients = optimizer.compute_gradients(objective)56 for i, (grad, var) in enumerate(gradients):57 if grad is not None:58 common_net_coeff = 1.0 / total_n_streams59 if 'common' in var.name:60 grad *= common_net_coeff61 gradients[i] = (grad, var)62 return optimizer.apply_gradients(gradients)63 def _get_error_and_train_op(self,64 reward_ph,65 is_terminal_ph,66 action1_ph,67 action2_ph,68 action1_chosen_by_online_ph,69 action2_chosen_by_online_ph):70 """Train the network"""71 Q_values_target1 = self._target_model['q_values1']72 Q_values_online1 = self._online_model['q_values1']73 Q_values_target2 = self._target_model['q_values2']74 Q_values_online2 = self._online_model['q_values2']75 max_q1 = tf.gather_nd(Q_values_target1, action1_chosen_by_online_ph)76 max_q2 = tf.gather_nd(Q_values_target2, action2_chosen_by_online_ph)77 target1 = reward_ph + (1.0 - is_terminal_ph) * self._gamma * max_q178 target2 = reward_ph + (1.0 - is_terminal_ph) * self._gamma * max_q279 gathered_outputs1 = tf.gather_nd(Q_values_online1, action1_ph, name='gathered_outputs1')80 gathered_outputs2 = tf.gather_nd(Q_values_online2, action2_ph, name='gathered_outputs2')81 loss1 = tf.reduce_mean(tf.square(target1 - gathered_outputs1))82 loss2 = tf.reduce_mean(tf.square(target2 - gathered_outputs2))83 loss3 = tf.reduce_mean(tf.square(gathered_outputs1 - gathered_outputs2))84 loss = loss1 * 0.4 + loss2 * 0.4 + loss3 * 0.285 train_optimizer = tf.train.AdamOptimizer(self._learning_rate)86 train_op = self.minimize_and_clip(train_optimizer, loss, 2)87 error_op1 = tf.abs(gathered_outputs1 - target1, name='abs_error1')88 error_op2 = tf.abs(gathered_outputs2 - target2, name='abs_error2')89 error_op = error_op1 * 0.5 + error_op2 * 0.590 return error_op, train_op91 def evaluate(self, sess, env):92 """Evaluate online model."""93 reward_total = 094 rewards_list = []95 num_finished_episode = 096 env.Reset()97 while num_finished_episode < 5:98 old_state, action1, action2, reward, new_state, is_terminal = env.GetState()99 next_action1, next_action2 = self.select_action(sess, new_state, self._online_model)100 env.TakeAction(next_action1, next_action2)101 if not is_terminal:102 reward_total += reward103 else:104 reward_total += reward105 if reward_total > -9:106 rewards_list.append(reward_total)107 num_finished_episode += 1108 reward_total = 0109 return np.mean(rewards_list), np.std(rewards_list), np.max(rewards_list), np.min(rewards_list), rewards_list110 def get_sample(self, env, sess):111 old_state, action1, action2, reward, new_state, is_terminal = env.GetState()112 next_action1, next_action2 = self.select_action(sess, new_state, self._online_model)113 env.TakeAction(next_action1, next_action2)114 return old_state, action1, action2, reward, new_state, float(is_terminal)115 def fit(self, sess, env, num_iterations, do_train=True):116 """Train using batch environment."""117 for t in range(num_iterations):118 # Prepare sample119 old_state, action1, action2, reward, new_state, is_terminal = self.get_sample(env, sess)120 self._memory.append(old_state, action1, action2, reward, new_state, is_terminal)121 # train.122 if do_train:123 old_state_list, action1_list, action2_list, reward_list, new_state_list, is_terminal_list = self._memory.sample(self._batch_size)124 feed_dict = {self._target_model['input_frames']: new_state_list.astype(np.float32),125 self._online_model['input_frames']: old_state_list.astype(np.float32),126 self._action1_ph: list(enumerate(action1_list)),127 self._action2_ph: list(enumerate(action2_list)),128 self._reward_ph: np.array(reward_list).astype(np.float32),129 self._is_terminal_ph: np.array(is_terminal_list).astype(np.float32),130 }131 action1_chosen_by_online, action2_chosen_by_online = sess.run([self._online_model['action1'], self._online_model['action2']], feed_dict={self._online_model['input_frames']: new_state_list.astype(np.float32)})132 feed_dict[self._action1_chosen_by_online_ph] = list(enumerate(action1_chosen_by_online))133 feed_dict[self._action2_chosen_by_online_ph] = list(enumerate(action2_chosen_by_online))134 sess.run(self._train_op, feed_dict=feed_dict)135 self._update_times += 1136 if self._update_times % self._target_update_freq == 0:...
working-2SG.py
Source:working-2SG.py
1# importing Numpy for some necessary operations2import numpy as np3# =============================4# Welcome to the 2 Squares Game! 5# ------------------------------6#|| 01 | 02 | 03 | 04 || 7# ---------------------------8#|| 05 | 06 | 07 | 08 || 9# ---------------------------10#|| 09 | 10 | 11 | 12 || 11# ---------------------------12#|| 13 | 14 | 15 | 16 || 13# =============================14# Author: CS112 - 2022 & | Moustafa Aly Hashem | ID: 2021039415# Version: 1.016# Date: 10 March 202217# 1- Build game board18# 2- Display game board19# 3- nActions = 020# 4- While (nActions != 8) 21# 5- Get player X action22# 6- Update game board23# 7- Get player O action24# 8- Update game board25# 9- If 2 cells are left26# - see their values27# - if adjacent -> x wins28# - if not -> o wins29# 10- if (nActions == 8)30# 10.a Break31# 11- nActions += 132# 12- Print ("Draw")33board = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', \34 '14', '15', '16']35# Displaying the board 1st time...36def display_board():37 print (" =============================")38 print (" Welcome to the 2 Squares Game! ")39 print (" ------------------------------")40 print ("|| " , board[0], " | ", board[1], " | ", board[2], " | ", board[3], " || ")41 print (" ---------------------------")42 print ("|| " , board[4], " | ", board[5], " | ", board[6], " | ", board[7], " || ")43 print (" ---------------------------")44 print ("|| ", board[8], " | ", board[9], " | ", board[10], " | ", board[11], " || ")45 print (" ---------------------------")46 print ("|| ", board[12], " | ", board[13], " | ", board[14], " | ", board[15], " || ")47 #print (" ---------------------------")48 print (" =============================")49# Get 1st response from player50def get_player_action1 (player):51 is_valid = False52 message1 = "Please choose 1st cell from 1 to 16 for player " + player + ": "53 global action154 while (not is_valid):55 action1 = input (message1)56 if not (action1).isdigit():57 continue58 else:59 is_valid = True60 action1 = int(action1)61 is_valid = is_valid and int(action1) > 0 and int(action1) <= 1662 is_valid = is_valid and board[action1 -1] != 'X'63 return action164#temp = action165# Get 2nd response from player66def get_player_action2 (player):67 is_valid = False68 message2 = "Please choose 2nd cell from 1 to 16 for player " + player + ": "69 while (not is_valid):70 action2 = input (message2)71 if not (action2).isdigit():72 continue73 else:74 is_valid = True75 action2 = int(action2)76 is_valid = is_valid and int(action2) > 0 and int(action2) <= 1677 is_valid = is_valid and board[action2 -1] != 'X'78 #Goto label;79 return action280def update_game_board (action1, action2, player):81 board [action1 - 1] = player82 board [action2 - 1] = player83 display_board()84def is_winner():85 counter = 086 for i in board:87 temp1 = np.zeros(16)88 if (i != 'XX'):89 counter = counter + 190 temp1[counter] = i91 if (counter == 2):92 if ((abs(temp1[1] - temp1[2]) != 1) and \93 (abs(temp1[1] - temp1[2]) != 4)):94 cond = True95 else:96 cond = False97 return cond98def play_game():99 display_board()100 n_actions = 0101 while (n_actions != 8):102 # Flags initialization103 flag_x = True104 flag_o = True105 boarders1 = False106 boarders2 = False107 action1 = get_player_action1 ('X')108 action2 = get_player_action2 ('X')109 #=================================110 # wrong input from player X111 #=================================112 while(flag_x):113 if ((int(action1)==4 or int(action1)==8 or int(action1)==12) and \114 (int(action2)==5 or int(action2)==9 or int(action2)==13)):115 boarders1 = True116 elif ((int(action2)==4 or int(action2)==8 or int(action2)==12) and \117 (int(action1)==5 or int(action1)==9 or int(action1)==13)):118 boarders2 = True119 else:120 boarders1 = False121 boarders2 = False122 if ((abs(int(action1) - int(action2)) > 1) and \123 (abs(int(action1) - int(action2)) != 4)):124 print ('Attention! 2nd input is not valid! please enter an adjacent cell')125 action2 = get_player_action2 ('X')126 elif(boarders1 or boarders2):127 print ('Attention! 2nd input is not valid! please enter an adjacent cell')128 action2 = get_player_action2 ('X')129 elif(abs(int(action1) == int(action2))):130 print ('Attention! 2nd input was entered before! please choose another cell')131 action2 = get_player_action2 ('X')132 else:133 flag_x = False134 #=================================135 # updating the board with actions from player X136 update_game_board (action1, action2, 'XX')137 if (is_winner()):138 print ('X wins! CONGRATULATIONS!!')139 break140 n_actions += 1141 if (n_actions == 8):142 break143 # Getting actions from player O144 action1 = get_player_action1 ('O')145 action2 = get_player_action2 ('O')146 #=================================147 # wrong input from player O148 #=================================149 while(flag_o):150 if ((int(action1)==4 or int(action1)==8 or int(action1)==12) and \151 (int(action2)==5 or int(action2)==9 or int(action2)==13)):152 boarders1 = True153 elif ((int(action2)==4 or int(action2)==8 or int(action2)==12) and \154 (int(action1)==5 or int(action1)==9 or int(action1)==13)):155 boarders2 = True156 else:157 boarders1 = False158 boarders2 = False159 if ((abs(int(action1) - int(action2)) > 1) and \160 (abs(int(action1) - int(action2)) != 4)):161 print ('Attention! 2nd input is not valid! please enter an adjacent cell')162 action2 = get_player_action2 ('X')163 elif((boarders1 or boarders2)):164 print ('Attention! 2nd input is not valid! please enter an adjacent cell')165 action2 = get_player_action2 ('X')166 elif(abs(int(action1) == int(action2))):167 print ('Attention! 2nd input was entered before! please choose another cell')168 action2 = get_player_action2 ('X')169 else:170 flag_o = False171 #=================================172 # updating the board with actions from player O173 update_game_board (action1, action2, 'XX')174 if (is_winner()):175 print ('O wins! CONGRATULATIONS!!')176 break177 n_actions += 1178 if (not is_winner()):179 print ('Draw')180#############################...
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!