Example #1
0
 def setUp(self):
     self.pygame = MagicMock()
     Graphics.pygame = self.pygame
     self.lib = MagicMock()
     self.window = MagicMock()
     self.graphics = Graphics.Graphics(self.lib)
     self.graphics.init(self.window)
Example #2
0
 def __init__(self, canvas, pixels, mainBoard):
     self.width = (int(canvas['width'])) // pixels
     self.height = int(canvas['height']) // pixels
     self.graphics = Graphics(self, canvas, pixels)
     self.isMain = mainBoard
     self.board = []
     self.initBoard(self.board)
Example #3
0
 def new(self):
     '''
         New is used to delete all the existing work.
     '''
     if MainApp.flag:
         del self.graphics
         self.graphics = Graphics()
         self.scene = self.graphics.getScene()
         self.graphicsView.setScene(self.scene)
         self.graphicsView.setMouseTracking(True)
         self.graphicsView.keyPressEvent = self.deleteCall
Example #4
0
 def __init__(self):
     super().__init__()
     self.__players = ('W', 'B')
     self.__turn = self.__players[0]
     self.__graphics = Graphics()
     self.__board = Board()
     self.__board.initializePieces('g')
     self.__selectedPiece = None
     self.__jump = False
     self.__buttonActions = ['Reset', 'Menu']
     self.__backMenu = False
     self.__buttonSize = [200, 50]
     self.__endGame = False
Example #5
0
 def __init__(self, msgbrowser):
     self.unitOp = []
     self.thermoPackage = None
     self.compounds = None
     self.flowsheet = None
     self.conn = defaultdict(list)
     self.op = defaultdict(list)
     self.ip = defaultdict(list)
     self.msg = msgbrowser
     self.msg.setText("")
     self.opl = []
     self.result = []
     self.graphics = Graphics(self.unitOp)
 def __init__(self,msgbrowser, graphicsView):
     self.unit_operations = []
     self.thermo_package = None
     self.compounds = None
     self.flowsheet = None
     self.conn = defaultdict(list)
     self.op=defaultdict(list)
     self.ip=defaultdict(list)
     self.msg = msgbrowser
     self.graphicsView = graphicsView
     self.msg.setText("")
     self.opl=[]
     self.result=[]
     self.graphics = Graphics(self.unit_operations, self.graphicsView)
     self.scene = self.graphics.get_scene()
Example #7
0
    def __init__(self):
        '''
            Initializing the application
        '''
        QMainWindow.__init__(self)
        self.setupUi(self)
        self.zoomcount = 0

        self.graphics = Graphics()
        self.scene = self.graphics.getScene()
        Graphics.flag = MainApp.flag

        self.previewBtn.setChecked(True)
        self.editingBtn.toggled.connect(lambda: self.btnState(self.previewBtn))
        self.previewBtn.toggled.connect(lambda: self.btnState(self.editingBtn))

        self.graphicsView.setScene(self.scene)
        self.graphicsView.setMouseTracking(True)
        self.graphicsView.keyPressEvent = self.deleteCall

        self.menuBar()
        self.unitOperationListInit()
Example #8
0
	def __init__(self, screen_size, fps):
		self._tmx_root = None  # Will be used to store the currently loaded tmx-file:
		self._fps = fps # Save fps
		self._CLOCK = pygame.time.Clock() # Create pygame.Clock for fps-control
		self._draw_tile_ids = False # DEBUG: Draw all ids:

		# Create instance of Graphics-Engine:
		self.graphics = Graphics(self,screen_size)
		# Create instance of World:
		self.world = World(self)
		# Create instance of input-engine
		self.input = Input(self)
		# Create actors-controller
		self.actors = GameActorController(self)
		# Create sound-controller (not jet programmed...)
		self.sound = Sound(self)

		# Finally, first map (temporary):
		self._load_tmx("Forest_N1_1.tmx")

		# Var changed by self.load_new_level. If not false, in the next update cycle, the level gets loaded.
		self._load_new_level = False
Example #9
0
import pygame
from PointVectorSector import *
from Graphics import *
from Map import *
import pygame.gfxdraw

graphics = Graphics([1000, 1000])

ScaleFactor = 100
Offset = Point(-50, -50)
WorldSize = [10, 10]
graphics.DrawGrid(ScaleFactor, WorldSize, Offset)
VectorMap = Map(WorldSize)

IsDragging = False
while True:
    events = pygame.event.get()
    for event in events:

        if event.type == pygame.QUIT:
            pygame.quit()
        # Is mouse moving? If mousing over a dot then colour
        # Get the new position of the mouse and draw it on screen
        # If Dragging then move a line to the mouse prosition
        if event.type == pygame.MOUSEMOTION:
            graphics.MouseSprite.ChangeText(str(pygame.mouse.get_pos()),
                                            pygame.Color('black'))
            graphics.IsMouseOverGrid(10)
            if IsDragging == True:
                graphics.LineDrag.UpdatePoint2(Point(*pygame.mouse.get_pos()))
            graphics.DrawSprites()
Example #10
0
from Graphics import*
from Board import*
from Player import*
from Game import*
from Human import*
from AgentMinimax import*
from SimpleBoard import*
import time

board = [[0]*8 for i in range(8)]



graph=Graphics(600, 504,board)
b=Board(board,graph)
p1=Human(b,graph,True)
p2=AgentMinimax(board,False)
g=Game(p1,p2,b,graph)




Example #11
0
import sys

import numpy as np
import cv2

sys.path.append("./")
import Graphics

activity = [4, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0]

gui = Graphics.Graphics()

for i in range(1000):
    gui.displayConfig((3, 3), activity)
    cv2.waitKey(2)
    if i > 500:
        activity = [7, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]

cv2.destroyAllWindows()
Example #12
0
 def __init__(self):
     self.graphics = Graphics()
     self.board = Board()
def Simulate(Mol, Simulations):

    if 'Graphics' in Simulations:
        #Save a graph of the molecule and the 4 states around the Fermi Energy
        Graph = Graphics()
        Graph.SetMolecule(Mol)
        Graph.Save(Mol.szOutputFolder + Mol.Name + " - Molecule.png",
                   part='Molecule')
        Graph.UpdateAtomSel(
            np.array([
                np.real(Mol.eigvec[0][:, Mol.N / 2 - 2] *
                        np.conjugate(Mol.eigvec[0][:, Mol.N / 2 - 2])),
                np.zeros(Mol.N)
            ]))
        Graph.Save(Mol.szOutputFolder + Mol.Name + " - Orbital - H**O 2.png",
                   part='Molecule')
        Graph.UpdateAtomSel(
            np.array([
                np.real(Mol.eigvec[0][:, Mol.N / 2 - 1] *
                        np.conjugate(Mol.eigvec[0][:, Mol.N / 2 - 1])),
                np.zeros(Mol.N)
            ]))
        Graph.Save(Mol.szOutputFolder + Mol.Name + " - Orbital - H**O 1.png",
                   part='Molecule')
        Graph.UpdateAtomSel(
            np.array([
                np.real(Mol.eigvec[0][:, Mol.N / 2 - 0] *
                        np.conjugate(Mol.eigvec[0][:, Mol.N / 2 - 0])),
                np.zeros(Mol.N)
            ]))
        Graph.Save(Mol.szOutputFolder + Mol.Name + " - Orbital - LUMO 1.png",
                   part='Molecule')
        Graph.UpdateAtomSel(
            np.array([
                np.real(Mol.eigvec[0][:, Mol.N / 2 + 1] *
                        np.conjugate(Mol.eigvec[0][:, Mol.N / 2 + 1])),
                np.zeros(Mol.N)
            ]))
        Graph.Save(Mol.szOutputFolder + Mol.Name + " - Orbital - LUMO 2.png",
                   part='Molecule')

    if 'Lifting' in Simulations:
        #Set up the plots
        fig = plt.figure()
        axLift, axOrbs = [fig.add_subplot(1, 2, 1), fig.add_subplot(1, 2, 2)]

        #Load and plot the experimental data if available
        for root, dirs, files in os.walk(Mol.szOutputFolder +
                                         'Experimental Data/'):
            for file in files:
                print(file)
                header, values = ImportData(Mol.szOutputFolder +
                                            'Experimental Data/' + file)
                axLift.plot(10 * values[:, 0],
                            values[:, 1],
                            'k',
                            marker='.',
                            lw=0,
                            label=file,
                            alpha=0.1)

        #Create MD folder if it did not already exists
        if not os.path.exists(Mol.szOutputFolder + 'MD'):
            os.makedirs(Mol.szOutputFolder + 'MD')

        #Perform lifting simulation
        MD = MD_Lifting(Mol)
        dz = np.linspace(0, np.max(Mol.Atom[:, 1]) - 0.1, 50)
        #        Mol.SetBias(0.01)
        I = MD.PerformLifting(dz, export=['param', 'dzI', 'xyz'], axOrb=axOrbs)

        #Plot tweaking and saving
        axLift.plot(dz,
                    np.log(I),
                    color='midnightblue',
                    label='Simulated',
                    lw=2,
                    alpha=0.8)
        axLift.plot(dz,
                    np.log(I),
                    color='midnightblue',
                    label='Simulated',
                    lw=0,
                    alpha=0.8,
                    marker='o',
                    markersize=10)
        #        axLift.legend()
        #        axLift.set_title('Lifting')
        axLift.set_xlabel('$\Delta \ z [A]$')
        axLift.set_ylabel('$ln(I)$')
        axLift.set_xlim([np.min(dz), np.max(dz)])
        ymin, ymax = np.min(np.log(I)), np.max(np.log(I))
        axLift.set_ylim(
            [ymin - 0.1 * (ymax - ymin), ymax + 0.1 * (ymax - ymin)])

        #        #Plot Beta factor
        #        axBeta = axLift.twinx()
        #        axBeta.plot((dz[0:-4]+dz[4:])/2, (np.log(I[0:-4])-np.log(I[4:]))/(dz[4]-dz[0])*10, c='r', alpha=0.5, lw=2)
        #        axBeta.set_ylabel('$Beta$')

        axOrbs.set_title('Orbitals')
        axOrbs.set_xlabel('$\Delta z [A]$')
        axOrbs.set_ylabel('$E_{Fermi} [eV]$')
        axOrbs.legend(['H**O 2', 'H**O 1', 'LUMO 1', 'LUMO 2'])

        fig.set_size_inches(20.5, 6.5)
        mpl.rcParams.update({'font.size': 20})
        fig.savefig(Mol.szOutputFolder + Mol.Name +
                    ' - Lifting vs Current.png',
                    dpi=fig.dpi)

    if 'LiftingSpectroscopy' in Simulations:
        #Set up parameters and perform simulation
        MD = MD_Lifting(Mol)
        dz = np.linspace(0, np.max(Mol.Atom[:, 1]) - 0.1, 50)
        neg_bias = -np.linspace(0.015, 0.5, 100)[::-1]
        pos_bias = np.linspace(0.005, 0.5, 100)
        I = MD.PerformLiftingSpectroscopy(dz,
                                          np.concatenate((neg_bias, pos_bias)),
                                          export=['dz-V-I'])
        I = [I[:, 0:len(neg_bias)], I[:, len(neg_bias):]]

        #Set up the figure
        c = mcolors.ColorConverter().to_rgb
        fig = plt.figure()
        axI, axdIdV, axBeta = [
            fig.add_subplot(1, 3, 1),
            fig.add_subplot(1, 3, 2),
            fig.add_subplot(1, 3, 3)
        ]

        #Plot ln(I) data
        BIAS, DZ = [[None, None], [None, None]]
        for i, bias in enumerate([neg_bias, pos_bias]):
            BIAS[i], DZ[i] = np.meshgrid(bias, dz)
        im = axI.contourf(np.concatenate([DZ[0], DZ[1]], axis=1),
                          np.concatenate([BIAS[0], BIAS[1]], axis=1),
                          np.log(abs(np.concatenate([I[0], I[1]], axis=1))),
                          100,
                          cmap=make_colormap([c('white'),
                                              c('midnightblue')]))
        axI.set_ylabel('$Bias$ [$V$]')
        axI.set_xlabel('$\Delta z \ [\AA{}]$')
        fig.colorbar(im, ax=axI, label='$ln(I)$')

        #Plot dI/dV data
        dIdV, mBIAS, mDZ = [[None, None], [None, None], [None, None]]
        for i, bias in enumerate([neg_bias, pos_bias]):
            dIdV[i] = (I[i][:, 1:] - I[i][:, 0:-1]) / (bias[1] - bias[0])
            mBIAS[i], mDZ[i] = np.meshgrid(0.5 * (bias[1:] + bias[0:-1]), dz)
        im = axdIdV.contourf(np.concatenate([mDZ[0], mDZ[1]], axis=1),
                             np.concatenate([mBIAS[0], mBIAS[1]], axis=1),
                             np.log(np.concatenate([dIdV[0], dIdV[1]],
                                                   axis=1)),
                             100,
                             cmap=make_colormap([c('white'),
                                                 c('darkgreen')]))
        axdIdV.set_ylabel('$Bias$ [$V$]')
        axdIdV.set_xlabel('$\Delta z \  [\AA{}]$')
        fig.colorbar(im, ax=axdIdV, label='$ln(dI/dV)$')

        #Plot beta factor
        Beta, BIAS, DZ = [[None, None], [None, None], [None, None]]
        for i, bias in enumerate([neg_bias, pos_bias]):
            Beta[i] = (np.log(abs(I[i][1:, :])) -
                       np.log(abs(I[i][0:-1, :]))) / (dz[1] - dz[0])
            BIAS[i], DZ[i] = np.meshgrid(bias, 0.5 * (dz[1:] + dz[0:-1]))
        im = axBeta.contourf(np.concatenate([DZ[0], DZ[1]], axis=1),
                             np.concatenate([BIAS[0], BIAS[1]], axis=1),
                             np.concatenate([Beta[0], Beta[1]], axis=1),
                             100,
                             cmap=make_colormap([c('darkred'),
                                                 c('white')]))
        axBeta.set_ylabel('$Bias$ [$V$]')
        axBeta.set_xlabel('$\Delta \ z$ [$\AA{}]$')
        fig.colorbar(im, ax=axBeta, label='$Beta factor$')
        mpl.rcParams.update({'font.size': 42})
        fig.set_size_inches(100.5, 13.5)
        fig.savefig(Mol.szOutputFolder + Mol.Name +
                    ' - LiftingSpectroscopy.png',
                    dpi=fig.dpi)

    if 'MD' in Simulations:
        #Perform a molecular dynamics simulation only
        MD = MD_Lifting(Mol)
        MD.PerformLiftingMD(np.linspace(0,
                                        np.max(Mol1.Atom[:, 1]) - 0.1, 50),
                            export=['xyz'])
Example #14
0
MAGENTA = (255, 0, 255)
TRANS = (1, 1, 1)

pygame.init()

cameraPosition = gameMath.Vector2(0, 0)
zoom = 1
relativeZoom = 1
cameraOnSnake = 0
menuScreen = True
infoScreen = False
startGameTime = 0
lastInfo = 0
debugTime = 0

graphics = Graphics(windowWidth, windowHeight, pixelScale)
game = Game()
clock = pygame.time.Clock()
font = pygame.font.SysFont("Arial", 12)

gameSpeed = 1
realTime = 0
fps = 0

running = True
while running:
    # ----------------- EVENTS ------------------------

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
Example #15
0
from Pente import *

import time

moveSequence = input('Enter the move sequence: ')
delay = int(input('Enter the time delay (0 to wait for user input): '))
size = int(input('Enter the width of the graphics window (0 for text mode): '))
if size > 0:
   from Graphics import *
   g = Graphics(size)
else:
   g = None

state = Pente()
print(state)
if delay > 0:
   time.sleep(delay)
else:
   input('Hit enter to continue')
  
for m in moveSequence.strip().split():
   a = ( ord(m[0]) - ord('A'), ord(m[1]) - ord('A') )
   state = state.result(a)
  
   if state.getTurn() % 2 == 0:
      print(f'White moves {m}')
   else:
      print(f'Black moves {m}')
    
   print()
   print(state)
Example #16
0
        I *= 1 / (2 * np.pi) * 0.00662361795 * 10**9
        return I

if __name__ == '__main__':
    from Molecule import *
    from Graphics import Graphics

    #    Mol = CGNR(23, 8, 8, 1, 4)
    Mol = ZGNR(5, 100)
    Mol.SetGam_b(0.05)
    Mol.UpdateMolecule(bNext=False)
    Mol.UpdateSystem(bNext=False)
    Mol.UpdateGates(Gmin=-3 + Mol.Efermi, Gmax=3 + Mol.Efermi)
    Mol.GetDOS()

    Graph = Graphics()
    Graph.SetMolecule(Mol)
    plt.show()

#    Mol1 = Molecule()
#    Mol1.AddAtom('C', 0, 0, 0)
#    Mol1.AddAtom('C', 1.41, 0, 0)
#    Mol1.SetLead(0, 'Left')
#    Mol1.SetLead(0, 'Right')
#    Mol1.SetGam_LR(5.6, 5.6)
#    Mol1 = Graphene(3,3, 'Armchair')
#    Mol1 = Graphene(6,401, 'Zigzag')
#    Mol1 = Graphene(4, 41, 'Zigzag')
#    Atom, x, y, z = Mol1.GetCoord()
#    xavg = np.mean(x)
#    for i in reversed(range(len(x))):
Example #17
0
            # Any live cell with two or three live neighbours lives, unchanged, to the next generation.
            if _world[i][j] == 1 and (neg[i][j] == 2 or neg[i][j] == 3):
                _world[i][j] = 1

            # Any dead cell with exactly three live neighbours will come to life.
            if _world[i][j] == 0 and neg[i][j] == 3:
                _world[i][j] = 1

    return _world


def run(init, draw_every = 1, delay = 0.1, gen = 500):
    ui.draw(init, 1)
    for ev in range(1, gen):
        init = evolution(init)
        print("\rEvolution:\t", ev, sep = "", end = "")
        if ev % draw_every == 0:
            sleep(delay)
            ui.draw(init, ev)

    ui.wait()


world = flower # random_world(60, 60, prob = 0.5)
ui = Graphics(len(world), len(world[0]), box_width=12)

run(init = world,
    draw_every = 1,
    delay = 0.3,
    gen = 100)