class GameArea: Height = 200 Width = 300 def __init__(self, canvas): self.canvas = canvas self.rand = Random() self.RedrawScreen(0) def addLine(self, _from, to): line = Line() line.X1 = _from[0] line.Y1 = _from[1] line.X2 = to[0] line.Y2 = to[1] line.Stroke = Brushes.White line.StrokeThickness = 2.0 self.canvas.Children.Add(line) def isCollision(self, x, y): width = self.Width height = self.Height if y <= 0 or y >= height: return True if x >= width: return not ((height / 2 + 15) > y > (height / 2 - 15)) for star in self.stars: testX = x - Canvas.GetLeft(star) testY = y - Canvas.GetTop(star) if mvvm.CheckCollisionPoint(Point(testX, testY), star): return True def AddNewPosition(self, x, y): self.polyline.Points.Add(Point(x, y)) if self.isCollision(x, y): return False return True def drawBorders(self, width, height): self.addLine((0, 0), (width, 0)) #line across top self.addLine((0, height), (width, height)) # line across botom self.addLine((width, 0), (width, height / 2 - 15)) self.addLine((width, height / 2 + 15), (width, height)) def RedrawScreen(self, level): self.canvas.Children.Clear() self.drawBorders(self.Width, self.Height) self.stars = [] for n in range(level * 3): star = mvvm.XamlLoader('star.xaml').Root self.stars.append(star) Canvas.SetLeft(star, self.rand.Next(10, self.Width - 10)) Canvas.SetTop(star, self.rand.Next(2, self.Height - 10)) self.canvas.Children.Add(star) self.polyline = Polyline() self.polyline.Stroke = Brushes.Yellow self.polyline.StrokeThickness = 2.0 self.canvas.Children.Add(self.polyline)
def __init__(self, canvas): self.canvas = canvas self.findRootVisual() self.rand = Random() self.RedrawScreen(0) wc = WebClient() wc.DownloadStringCompleted += self.xamlDownloaded wc.DownloadStringAsync(Uri('star.xaml', UriKind.Relative))
def createPoint3d(rgFace, fMinDistFromBorder=None, bDebug=False): """ Parameters: rgFace: BrepFace fMinDistFromBorder: float Returns: Point3d on success, None on failure """ if fMinDistFromBorder is None: fMinDistFromBorder = 10.0 * sc.doc.ModelAbsoluteTolerance rgBrep = rgFace.Brep iDomainU = rgFace.Domain(0) iDomainV = rgFace.Domain(1) areaMassProp = Rhino.Geometry.AreaMassProperties.Compute(rgFace) if areaMassProp is None: print "Face[{}]'s AreaMassProperties cannot be calculated.".format( rgFace.FaceIndex) u = iDomainU.Mid v = iDomainV.Mid else: ptCentrdW = areaMassProp.Centroid bSuccess, u, v = rgFace.ClosestPoint(ptCentrdW) rgEdges = [rgBrep.Edges[idxEdge] for idxEdge in rgFace.AdjacentEdges()] rand = Random() for i in xrange(10000): pointFaceRelation = rgFace.IsPointOnFace(u, v) if bDebug: sEval = "pointFaceRelation" print sEval + ':', eval(sEval) if pointFaceRelation == rg.PointFaceRelation.Interior: pt = rgFace.PointAt(u, v) # If point is not at least fMinDistFromBorder from border (all edges), # continue searching. for rgEdge in rgEdges: b, t = rgEdge.ClosestPoint(pt) if b: dist = pt.DistanceTo(rgEdge.PointAt(t)) if dist < fMinDistFromBorder: break # to get another u and v. else: # Good point map(lambda x: x.Dispose(), rgEdges) rgFace.Dispose() return pt # Get new parameters for point. u = rand.NextDouble() * iDomainU.Length + iDomainU.Min v = rand.NextDouble() * iDomainV.Length + iDomainV.Min
def randtest(doc): #生成1w个测试点 with dbtrans(doc) as tr: btr = tr.opencurrspace() from System import Guid, Random r = Random(Guid.NewGuid().GetHashCode()) for i in range(10000): tr.addentity( btr, acdb.DBPoint(acge.Point3d(r.Next(0, 1000), r.Next(0, 1000), 0)))
def encode_job(self, job): random_bytes = Array.CreateInstance(Byte, 2) Random().NextBytes(random_bytes) data = Encoding.UTF8.GetBytes(JavaScriptSerializer().Serialize(job)) with MemoryStream(data.Length) as initialStream: initialStream.Write(data, 0, data.Length) initialStream.Seek(0, SeekOrigin.Begin) with MemoryStream() as resultStream: with GZipStream(resultStream, CompressionMode.Compress) as zipStream: buffer = Array.CreateInstance(Byte, 4096) bytesRead = initialStream.Read(buffer, 0, buffer.Length) zipStream.Write(buffer, 0, bytesRead) while bytesRead != 0: bytesRead = initialStream.Read(buffer, 0, buffer.Length) zipStream.Write(buffer, 0, bytesRead) result = resultStream.ToArray() result[:2] = random_bytes return { Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring( 0, 8): Convert.ToBase64String(Guid.NewGuid().ToByteArray()), "data": Convert.ToBase64String(result) }
class FlippingGame(object): def __init__(self, bankroll=500, history=[], seed=None): self.history = history self.bankroll = self.initial_bankroll = bankroll self.rand = Random(seed) if seed is not None else Random() def check_wager(self, wager): if wager < 1: return "You must wager at least one credit." if wager > self.bankroll: return "You cannot wager more than your bankroll." def flip(self, guess, wager): assert 1 <= wager <= self.bankroll assert guess in "TH" result = self._do_flip() self.history.append((result, guess, wager)) if result == guess: self.bankroll += wager return True, result else: self.bankroll -= wager return False, result def _do_flip(self): return "TH"[self.rand.Next(2)]
def __init__(self, maxsize): self._maxsize = maxsize self._data = Array.CreateInstance(System.Byte, self._maxsize) Random().NextBytes(self._data) self._log = StringBuilder() self._currentoffset = 0 self._currentlength = 0
def onClose(sender, args): global digits closeTimer.Stop() storyboard = Storyboard() def onCurrentStateInvalidated(sender, args): if sender.CurrentState == ClockState.Filling: for element in grid1.Children: element.Opacity = 0 storyboard.Remove(contentControl) tickTimer.Stop() window.Close() storyboard.CurrentStateInvalidated += onCurrentStateInvalidated r = Random(Environment.TickCount) for i in range(digits.Length): beginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds( r.Next(500))) for element in grid1.Children: if Grid.GetColumn(element) == i: doubleAnimation = DoubleAnimation( element.Opacity, 0, TimeSpan.FromMilliseconds(500)) doubleAnimation.BeginTime = beginTime sineEase = SineEase() sineEase.EasingMode = EasingMode.EaseIn doubleAnimation.EasingFunction = sineEase storyboard.Children.Add(doubleAnimation) Storyboard.SetTarget(doubleAnimation, element) Storyboard.SetTargetProperty( doubleAnimation, PropertyPath(UIElement.OpacityProperty)) contentControl.BeginStoryboard( storyboard, HandoffBehavior.SnapshotAndReplace, True) closeTimer.Tag = False
def Shuffle(self): allTiles = [] for i in range(0, self.gridDimension): for j in range(0, self.gridDimension): if not self.grid[i][j] is None: allTiles += [self.grid[i][j]] allTiles += [None] # dummy tile, used for empty space from System import Random rand = Random() for i in range(0, self.gridDimension): for j in range(0, self.gridDimension): idx = rand.Next(len(allTiles)) if allTiles[idx] is None: self.grid[i][j] = None else: self.grid[i][j] = allTiles[idx] self.grid[i][j].currentRow = i self.grid[i][j].currentCol = j self.grid[i][j].Location = self.GetLocation(i, j) allTiles = allTiles[:idx] + allTiles[idx + 1:]
def __init__(self): print '__init__' self.LoadComponent() self.StartPoint = None self.Randomizer = Random(DateTime.Now.Millisecond) self.Generator = mandelbrotbase.MandelbrotGenerator( self, int(self.Content.FractalArea.Width), int(self.Content.FractalArea.Height)) self.Generator.Completed += self.Generator_Completed # commands self.Content.ResetButton.Click += lambda sender, e: self.Reset() self.Content.ZoomInButton.Click += lambda sender, e: self.ZoomIn() self.Content.ZoomOutButton.Click += lambda sender, e: self.ZoomOut() self.Content.PanLeftButton.Click += lambda sender, e: self.Pan(-50, 0) self.Content.PanRightButton.Click += lambda sender, e: self.Pan(50, 0) self.Content.PanUpButton.Click += lambda sender, e: self.Pan(0, -50) self.Content.PanDownButton.Click += lambda sender, e: self.Pan(0, 50) self.Content.RandomButton.Click += lambda sender, e: self.Randomize() self.Content.FractalArea.MouseLeftButtonDown += self.area_MouseLeftButtonDown self.Content.FractalArea.MouseLeftButtonUp += self.area_MouseLeftButtonUp self.Content.FractalArea.MouseMove += self.area_MouseMove
class Mandelbrot(UserControl): DefaultXS = -2.1 DefaultYS = -1.3 DefaultXE = 1.0 DefaultYE = 1.3 def __init__(self): print '__init__' self.LoadComponent() self.StartPoint = None self.Randomizer = Random(DateTime.Now.Millisecond) self.Generator = mandelbrotbase.MandelbrotGenerator( self, int(self.Content.FractalArea.Width), int(self.Content.FractalArea.Height)) self.Generator.Completed += self.Generator_Completed # commands self.Content.ResetButton.Click += lambda sender, e: self.Reset() self.Content.ZoomInButton.Click += lambda sender, e: self.ZoomIn() self.Content.ZoomOutButton.Click += lambda sender, e: self.ZoomOut() self.Content.PanLeftButton.Click += lambda sender, e: self.Pan(-50, 0) self.Content.PanRightButton.Click += lambda sender, e: self.Pan(50, 0) self.Content.PanUpButton.Click += lambda sender, e: self.Pan(0, -50) self.Content.PanDownButton.Click += lambda sender, e: self.Pan(0, 50) self.Content.RandomButton.Click += lambda sender, e: self.Randomize() self.Content.FractalArea.MouseLeftButtonDown += self.area_MouseLeftButtonDown self.Content.FractalArea.MouseLeftButtonUp += self.area_MouseLeftButtonUp self.Content.FractalArea.MouseMove += self.area_MouseMove def LoadComponent(self): print 'LoadComponent' xaml = DynamicApplication.LoadComponentFromString( open("mandelbrot.xaml").read()) xaml.Loaded += self.UserControl_Loaded self.Content = xaml def Generator_Completed(self, sender, e): self.Content.image.ImageSource = e.Image self.SetEnabled(True) def UserControl_Loaded(self, sender, e): print 'UserControl_Loaded' self.Reset() def ZoomIn(self): self.Redraw(50, 50, self.Content.FractalArea.Width - 50, self.Content.FractalArea.Height - 50) def ZoomOut(self): self.Redraw(-50, -50, self.Content.FractalArea.Width + 50, self.Content.FractalArea.Height + 50) def Pan(self, panX, panY): self.Redraw(0 + panX, 0 + panY, self.Content.FractalArea.Width + panX, self.Content.FractalArea.Height + panY) def Randomize(self): self.CurrentXS = Mandelbrot.DefaultXS self.CurrentYS = Mandelbrot.DefaultYS self.CurrentXE = Mandelbrot.DefaultXE self.CurrentYE = Mandelbrot.DefaultYE xs = self.Randomizer.Next(0, int(self.Content.FractalArea.Width)) ys = self.Randomizer.Next(0, int(self.Content.FractalArea.Height)) w = self.Randomizer.Next(3, 100) h = int( w / (self.Content.FractalArea.Width / self.Content.FractalArea.Height)) self.Redraw(xs, ys, xs + w, ys + h) def Reset(self): print 'Reset' self.CurrentXS = Mandelbrot.DefaultXS self.CurrentYS = Mandelbrot.DefaultYS self.CurrentXE = Mandelbrot.DefaultXE self.CurrentYE = Mandelbrot.DefaultYE self.Redraw(0, 0, self.Content.FractalArea.Width, self.Content.FractalArea.Height) def area_MouseLeftButtonDown(self, sender, e): self.StartPoint = e.GetPosition(self.Content.FractalArea) self.Content.selection.Visibility = Visibility.Visible self.Content.selection.Width = 0 self.Content.selection.Height = 0 Canvas.SetLeft(self.Content.selection, self.StartPoint.X) Canvas.SetTop(self.Content.selection, self.StartPoint.Y) self.Content.FractalArea.CaptureMouse() def area_MouseLeftButtonUp(self, sender, e): if self.StartPoint is not None: currentPoint = e.GetPosition(self.Content.FractalArea) if currentPoint != self.StartPoint: if currentPoint.X > self.StartPoint.X: xs = self.StartPoint.X else: xs = currentPoint.X if currentPoint.Y > self.StartPoint.Y: ys = self.StartPoint.Y else: ys = currentPoint.Y xe = xs + self.Content.selection.Width ye = ys + self.Content.selection.Height self.Redraw(xs, ys, xe, ye) self.StartPoint = None self.Content.selection.Visibility = Visibility.Collapsed self.Content.FractalArea.ReleaseMouseCapture() def area_MouseMove(self, sender, e): if self.StartPoint is not None: currentPoint = e.GetPosition(self.Content.FractalArea) if currentPoint.X < 0: currentPoint.X = 0 if currentPoint.Y < 0: currentPoint.Y = 0 if currentPoint.X > self.Content.FractalArea.Width: currentPoint.X = self.Content.FractalArea.Width if currentPoint.Y > self.Content.FractalArea.Height: currentPoint.Y = self.Content.FractalArea.Height self.Content.selection.Width = Math.Abs(currentPoint.X - self.StartPoint.X) self.Content.selection.Height = self.Content.selection.Width / ( self.Content.FractalArea.Width / self.Content.FractalArea.Height) if currentPoint.X > self.StartPoint.X: canvasLeft = self.StartPoint.X else: canvasLeft = currentPoint.X if currentPoint.Y > self.StartPoint.Y: canvasTop = self.StartPoint.Y else: canvasTop = currentPoint.Y Canvas.SetLeft(self.Content.selection, canvasLeft) Canvas.SetTop(self.Content.selection, canvasTop) def Redraw(self, xs, ys, xe, ye): print 'Redraw' self.SetEnabled(False) w = self.CurrentXE - self.CurrentXS h = self.CurrentYE - self.CurrentYS xsp = (xs * 100 / self.Content.FractalArea.Width) cxs = (w / 100 * xsp) + self.CurrentXS xep = (xe * 100 / self.Content.FractalArea.Width) cxe = (w / 100 * xep) + self.CurrentXS ysp = (ys * 100 / self.Content.FractalArea.Height) cys = (h / 100 * ysp) + self.CurrentYS yep = (ye * 100 / self.Content.FractalArea.Height) cye = (h / 100 * yep) + self.CurrentYS self.CurrentXS = cxs self.CurrentXE = cxe self.CurrentYS = cys self.CurrentYE = cye self.Generator.Generate(self.CurrentXS, self.CurrentYS, self.CurrentXE, self.CurrentYE) def SetEnabled(self, enabled): self.Content.PanDownButton.IsEnabled = enabled self.Content.PanLeftButton.IsEnabled = enabled self.Content.PanRightButton.IsEnabled = enabled self.Content.PanUpButton.IsEnabled = enabled self.Content.ZoomInButton.IsEnabled = enabled self.Content.ZoomOutButton.IsEnabled = enabled self.Content.ResetButton.IsEnabled = enabled self.Content.RandomButton.IsEnabled = enabled
zipArchive.Dispose() except Exception, e: continue finally: if fs is not None: fs.Close() ms = None fs = None try: ms = MemoryStream() characters = Array.CreateInstance(Character, 1) characters[0] = characterList[Random(Environment.TickCount).Next( characterList.Count)] serializer = XmlSerializer(characters.GetType()) serializer.Serialize(ms, characters) ms.Seek(0, SeekOrigin.Begin) fs = FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read) buffer = ms.ToArray() fs.Write(buffer, 0, buffer.Length) fs.Flush() finally: if fs is not None: fs.Close() if ms is not None: ms.Close()
def Initialize(self, level): rnd = Random() self._name = "Sword" self._damage = rnd.Next(10, 20) * level
#### for IronPython from System import Random robj = Random(15) r = 0 for i in range(1000000): r = robj.Next() print r
from System import Random rand = Random() def randomBool(): if rand.Next(0, 2) < 1: return "True" else: return "False" def run_script(): print("(" + randomBool() + ", " + randomBool() + ", " + randomBool() + ")")
def __init__(self, bankroll=500, history=[], seed=None): self.history = history self.bankroll = self.initial_bankroll = bankroll self.rand = Random(seed) if seed is not None else Random()
def make_move(world, uav, m, m_idx, V, V_occ): row = uav.pos_pt.row col = uav.pos_pt.col new_pos = 0 uav.alt_c = 0 # control altitude at steady state #========================================================= # Possible Final Vehicle Attitude Options #========================================================= # attOptions is being used as direction of next target space. # get possible directions based on current uav attitude (-90, -45, 0, 45, 90) attOptionsRaw = [uav.attitude - 2, uav.attitude - 1, uav.attitude, uav.attitude + 1, uav.attitude + 2] attOptions = [] # make sure the range is between 0-7 for att in attOptionsRaw: if (att < 0): attOptions.append(8 + att) elif (att > 7): attOptions.append(att - 8) else: attOptions.append(att) nextAttConcent = [] nextAttitude = [] # move aircraft to open space, otherwise move to an unoccupied space, otherwise stay until next round #========================================================= # Select Favorable Target Space Directions #========================================================= # When vehicle is at starting space and there's no # pheromone concentration, look for unoccupied target # spaces. If the vehicle is surrounded then stay until # the other vehicles have moved. # When everything is normal, append all probable target # space with a positive pheromone concentration into list. #========================================================= if uav.pos_pt == uav.path[0]: # Find open space with gradient for att in attOptions: if (V_occ[att] > 0): nextAttConcent.append(V_occ[att]) nextAttitude.append(att) # Find an unoccupied space if not nextAttitude: nextAttitude = get_attitude_range(world, attOptions, uav) # Stay in the starting location until next iteration if not nextAttitude: uav.path.append(uav.pos_pt) return else: # check for possible new position. Get value to find gradient for att in attOptions: if (V_occ[att] > 0): nextAttConcent.append(V_occ[att]) nextAttitude.append(att) # if list is empty, find a space that is not occupied #========================================================= # Select Target Space Directions with No Gradient #========================================================= # When the vehicle is not at the starting space and there # is no positive pheromone gradient within the all the # possible direction list (nextAttitude list is empty), # check for spaces not occupied within the attOptions list. # # When there are no spaces available, check if the # options are within bounds and append that as a possible # target position. Climb to higher altitude in order to # avoid collision. Direction is then chosen at random # from the list of possible occupied target spaces. #========================================================= if not nextAttitude: nextAttitude = get_attitude_range(world, attOptions, uav) # if surrounded, check if spots are within map bounds if not nextAttitude: for att in attOptions: if att == 0: new_pos = gridpoint.GridPoint(row+1, col) if (within_bounds(world, new_pos)): nextAttitude.append(att) if att == 1: new_pos = gridpoint.GridPoint(row+1, col+1) if (within_bounds(world, new_pos)): nextAttitude.append(att) if att == 2: new_pos = gridpoint.GridPoint(row, col+1) if (within_bounds(world, new_pos)): nextAttitude.append(att) if att == 3: new_pos = gridpoint.GridPoint(row-1, col+1) if (within_bounds(world, new_pos)): nextAttitude.append(att) if att == 4: new_pos = gridpoint.GridPoint(row-1, col) if (within_bounds(world, new_pos)): nextAttitude.append(att) if att == 5: new_pos = gridpoint.GridPoint(row-1, col-1) if (within_bounds(world, new_pos)): nextAttitude.append(att) if att == 6: new_pos = gridpoint.GridPoint(row, col-1) if (within_bounds(world, new_pos)): nextAttitude.append(att) if att == 7: new_pos = gridpoint.GridPoint(row+1, col-1) if (within_bounds(world, new_pos)): nextAttitude.append(att) uav.alt_c = 50 # increase alt by 50m to avoid collisions # When gradient approach was not available if not nextAttConcent: # choose a random direction from recently visited or possible occupied spaces rand = Random() idx = rand.Next(0, len(nextAttitude)) m_idx = nextAttitude[idx] else: # find gradient to follow and/or choose a random direction of multiple equal gradients m = max(nextAttConcent) m_idx = [i for i, j in enumerate(V_occ) if j == m] rand = Random() idx = rand.Next(0, len(m_idx)) m_idx = m_idx[idx] attAngle = m_idx uav.prevAttitude = uav.attitude # Get direction of space location if (attAngle == attOptions[0]): uav.turnAngle = -90 uav.attitude = uav.attitude - 2 if (uav.attitude < 0): uav.attitude = 8 + uav.attitude if (uav.attitude > 7): uav.attitude = uav.attitude - 8 elif (attAngle == attOptions[1]): uav.turnAngle = -45 uav.attitude = uav.attitude - 0 if (uav.attitude < 0): uav.attitude = 8 + uav.attitude elif (attAngle == attOptions[2]): uav.turnAngle = 0 elif (attAngle == attOptions[3]): uav.turnAngle = 45 uav.attitude = uav.attitude + 0 if (uav.attitude > 7): uav.attitude = uav.attitude - 8 elif (attAngle == attOptions[4]): uav.turnAngle = 90 uav.attitude = uav.attitude + 2 if (uav.attitude > 7): uav.attitude = uav.attitude - 8 if (uav.attitude < 0): uav.attitude = 8 + uav.attitude else: print ('out of turning bounds', m_idx, attOptions[0], attOptions[1], attOptions[2], attOptions[3], attOptions[4], m_idx == attOptionsRaw[0], m_idx == attOptionsRaw[1], m_idx == attOptionsRaw[2], m_idx == attOptionsRaw[3], m_idx == attOptionsRaw[4], type(m_idx), type(attOptions[0])) # Create point for new position if m_idx == 0: # UP new_pos = gridpoint.GridPoint(row+1, col) elif m_idx == 1: # TOP-RIGHT new_pos = gridpoint.GridPoint(row+1, col+1) elif m_idx == 2: # RIGHT new_pos = gridpoint.GridPoint(row, col+1) elif m_idx == 3: # BOTTOM-RIGHT new_pos = gridpoint.GridPoint(row-1, col+1) elif m_idx == 4: # DOWN new_pos = gridpoint.GridPoint(row-1, col) elif m_idx == 5: # BOTTOM-LEFT new_pos = gridpoint.GridPoint(row-1, col-1) elif m_idx == 6: # LEFT new_pos = gridpoint.GridPoint(row, col-1) elif m_idx == 7: # TOP-LEFT new_pos = gridpoint.GridPoint(row+1, col-1) drop_flavor(world, world.visit_grid, new_pos, 1, 1, uav.repel) # make current space available for other units to move into space = grid.get_cell(world.searched_grid, uav.pos_pt) space.occupied = False grid.set_cell(world.searched_grid, uav.pos_pt, space) # change values of next space space = grid.get_cell(world.searched_grid, new_pos) space.visited = True space.occupied = True grid.set_cell(world.searched_grid, new_pos, space) uav.prev_pt = uav.pos_pt uav.pos_pt = new_pos uav.path.append(new_pos)
def Roomba(): int = Random().Next(8) # 0-7 if not Walk(Direction('self')): Turn(dir[int]) return
# Generate VISA-style numbers with a Luhn checksum import clr clr.AddReference("System") from System import Random random = Random() def choice(l): return l[random.Next(len(l))] def completed_number(prefix, length): # Given a prefix and a desired length, fill in the number up # to the desired length, using Luhn to compute the checksum ccnumber = list(prefix) # Generate digits for _ in range(length - len(prefix) - 1): ccnumber.append(choice('0123456789')) # Calculate sum sum = pos = 0 reversedCCnumber = list(reversed(ccnumber)) while pos < length - 1: odd = int(reversedCCnumber[pos]) * 2 if odd > 9: odd -= 9 if pos != (length - 2): sum += int(reversedCCnumber[pos + 1]) sum += odd pos += 2
def Initialize(self, level): rnd = Random() self._name = "TestArmor" self._health = rnd.Next(100, 150) * level self._heal = rnd.Next(5, 10) * level
def __init__(self, canvas): self.canvas = canvas self.rand = Random() self.RedrawScreen(0)
def Initialize(self, level): rnd = Random() self._name = "TestShield" self._block = rnd.Next(5, 15) * level
def createPoint3dOnInterior(rgFace, fMinDistFromBorder=None, bDebug=False): """ Parameters: rgFace: BrepFace fMinDistFromBorder: float or (None to loop through various) Returns: Point3d on success, None on failure """ fMinDistFromBorder_In = fMinDistFromBorder rgB_1F = rgFace.DuplicateFace(duplicateMeshes=False) rgB_1F.Faces.ShrinkFaces() rgB_1F.Compact() # Is this cecessary to remove duplicate surfaces? rgSrf_Shrunk = rgB_1F.Surfaces[0] domU_Shrunk = rgSrf_Shrunk.Domain(0) domV_Shrunk = rgSrf_Shrunk.Domain(1) #areaMassProp = rg.AreaMassProperties.Compute(rgFace.DuplicateFace(True)) # Otherwise, Compute uses underlying Surface for BrepFace. #if areaMassProp is None: # print "Face[{}]'s AreaMassProperties cannot be calculated.".format( # rgFace.FaceIndex) # u = domU_Shrunk.Mid # v = domV_Shrunk.Mid #else: # ptCentrdW = areaMassProp.Centroid # bSuccess, u, v = rgFace.ClosestPoint(ptCentrdW) u_Shrunk = domU_Shrunk.Mid v_Shrunk = domV_Shrunk.Mid # To3dCurve will include curves of seams. This is advantageous in this circumstance. rgCrvs_fromLoops = [loop.To3dCurve() for loop in rgFace.Loops] rand = Random() if fMinDistFromBorder_In is None: rangeTol = (10.0 * sc.doc.ModelAbsoluteTolerance, sc.doc.ModelAbsoluteTolerance, 0.5 * sc.doc.ModelAbsoluteTolerance) else: rangeTol = fMinDistFromBorder_In, for fMinDistFromBorder in rangeTol: for i in xrange(1000): pt = rgSrf_Shrunk.PointAt(u_Shrunk, v_Shrunk) b, u, v = rgFace.ClosestPoint(pt) if not b: raise ValueError("ClosestPoint failed in createPointOnFace.") ptFaceRel = rgFace.IsPointOnFace(u, v) #sc.doc.Objects.AddPoint(pt); sc.doc.Views.Redraw() if bDebug: sEval = "ptFaceRel" print sEval + ':', eval(sEval) if ptFaceRel == rg.PointFaceRelation.Interior: # If point is not at least fMinDistFromBorder from border (all edges), # continue searching. for c in rgCrvs_fromLoops: b, t = c.ClosestPoint(pt) if not b: raise ValueError( "ClosestPoint failed in createPointOnFace.") dist = pt.DistanceTo(c.PointAt(t)) if dist < fMinDistFromBorder: break # to get another u and v. else: # Good point for c in rgCrvs_fromLoops: c.Dispose() rgB_1F.Dispose() if bDebug: sEval = "i" print sEval + ':', eval(sEval) return pt # Get new parameters for point. u_Shrunk = rand.NextDouble() * domU_Shrunk.Length + domU_Shrunk.Min v_Shrunk = rand.NextDouble() * domV_Shrunk.Length + domV_Shrunk.Min # sc.doc.Objects.AddBrep(rgFace.DuplicateFace(duplicateMeshes=True)) # sc.doc.Views.Redraw() raise ValueError("Failed to find an interior point on face[{}].".format( rgFace.FaceIndex))
# by the terms of the Apache License, Version 2.0. # # You must not remove this notice, or any other, from this software. # # ##################################################################################### #------------------------------------------------------------------------------ #--INSERTS RANDOM SQUARES from System.Windows.Controls import Canvas from System.Windows.Shapes import * from System.Windows.Media import * from System import Random rand = Random() for i in xrange(100): rect = Rectangle(Width=20, Height=20, Fill=Brushes.Blue) Application.Painting.Children.Add(rect) Canvas.SetLeft(rect, rand.Next(Application.Painting.ActualWidth)) Canvas.SetTop(rect, rand.Next(Application.Painting.ActualHeight)) #------------------------------------------------------------------------------ #--INSERT A CIRCLE CONSISTING OF SQUARES OF DIFFERENT COLORS # setup circle from System.Windows.Controls import Canvas from System.Windows.Shapes import * from System.Windows.Media import * import math
class GameArea: Height = 200 Width = 300 starXaml = """ <Path xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" Stroke="White" StrokeThickness="2" StrokeStartLineCap="Round" StrokeEndLineCap="Round" StrokeLineJoin="Round" Data="M 0,0 l 5,0 l 2.5,-5 l 2.5,5 l 5,0 l -3.5,5 l 1,5 l -5,-2.5 l -5,2.5 l 1,-5 Z"> <Path.RenderTransform> <ScaleTransform ScaleX="0.8" ScaleY="0.8" /> </Path.RenderTransform> </Path>""" def __init__(self, canvas): self.canvas = canvas self.findRootVisual() self.rand = Random() self.RedrawScreen(0) wc = WebClient() wc.DownloadStringCompleted += self.xamlDownloaded wc.DownloadStringAsync(Uri('star.xaml', UriKind.Relative)) def findRootVisual(self): self.rootVisual = self.canvas while self.rootVisual.Parent: self.rootVisual = self.rootVisual.Parent def xamlDownloaded(self, sender, args): if not args.Error: self.starXaml = args.Result else: pass #raise args.Error def addLine(self, _from, to): line = Line() line.X1 = _from[0] line.Y1 = _from[1] line.X2 = to[0] line.Y2 = to[1] line.Stroke = SolidColorBrush(Color.FromArgb(255, 255, 255, 255)) # Brushes.White line.StrokeThickness = 2.0 self.canvas.Children.Add(line) def isCollision(self, x, y): width = self.Width height = self.Height if y <= 0 or y >= height: return True if x >= width: return not ((height / 2 + 15) > y > (height / 2 - 15)) testPoint = Point(x, y) hostPoint = self.canvas.TransformToVisual( self.rootVisual).Transform(testPoint) #Debug.WriteLine('Test Point: {0}, Host Point: {1}'.format(testPoint,hostPoint)) if mvvm.CheckCollisionPoint(hostPoint, self.canvas): return True def AddNewPosition(self, x, y): self.polyline.Points.Add(Point(x, y)) if self.isCollision(x, y): return False return True def drawBorders(self, width, height): self.addLine((0, 0), (width, 0)) #line across top self.addLine((0, height), (width, height)) # line across botom self.addLine((width, 0), (width, height / 2 - 15)) self.addLine((width, height / 2 + 15), (width, height)) def RedrawScreen(self, level): self.canvas.Children.Clear() self.drawBorders(self.Width, self.Height) self.stars = [] for n in range(level * 3): star = mvvm.XamlLoader(self.starXaml).Root self.stars.append(star) Canvas.SetLeft(star, self.rand.Next(10, self.Width - 10)) Canvas.SetTop(star, self.rand.Next(2, self.Height - 10)) self.canvas.Children.Add(star) self.polyline = Polyline() self.polyline.Stroke = SolidColorBrush(Color.FromArgb( 255, 255, 255, 0)) # Brushes.Yellow self.polyline.StrokeThickness = 2.0 self.canvas.Children.Add(self.polyline)
def Initialize(self, level): rnd = Random() self._windup = False self._name = "Hammer" self._damage = rnd.Next(20, 50) * level
gameDir = util.getGameDirectory() import System from System.Diagnostics import Stopwatch from System import TimeSpan sw = Stopwatch.StartNew() import TESVSnip.Domain import ListItems plugins = TESVSnip.Domain.Model.PluginList.All excludeList = 'RGDL;CLDC;PWAT;SCOL;SCPT;HAIR;REGN;NAVI;WRLD;DIAL;CELL;IMAD;WTHR'.Split( ';') filter = System.Func[str, bool](lambda x: x not in excludeList) pluginList = util.loadMasterPluginIndex() from System import Random rand = Random() pluginName = pluginList.items()[rand.Next(0, len(pluginList) - 1)][0] plugins.AddRecord(TESVSnip.Domain.Model.Plugin(gameDir + pluginName, filter)) #plugins.AddRecord(TESVSnip.Domain.Model.Plugin(gameDir + 'skyrim.esm', filter)) print ListItems.generateItemList(plugins) import ModWeight print ModWeight.listNPCWeights(plugins) print ModWeight.modifyNPCWeights(plugins) sw.Stop() t = TimeSpan.FromMilliseconds(sw.ElapsedMilliseconds) print 'Script took', t, 'to complete'
def onLoaded(sender, args): global rectList, digits storyboard = Storyboard() def onCurrentStateInvalidated(sender, args): if sender.CurrentState == ClockState.Filling: for element in grid1.Children: element.Opacity = 1 storyboard.Remove(contentControl) if not grid1.Tag: closeTimer.Start() storyboard.CurrentStateInvalidated += onCurrentStateInvalidated r = Random(Environment.TickCount) dateTime = DateTime.Now digits[0] = dateTime.Hour / 10 digits[1] = dateTime.Hour % 10 digits[2] = dateTime.Minute / 10 digits[3] = dateTime.Minute % 10 digits[4] = dateTime.Second / 10 digits[5] = dateTime.Second % 10 for i in range(digits.Length): beginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds( r.Next(500))) for element1 in grid1.Children: if Grid.GetColumn(element1) == i: doubleAnimation = DoubleAnimation( element1.Opacity, 1, TimeSpan.FromMilliseconds(500)) doubleAnimation.BeginTime = beginTime sineEase = SineEase() sineEase.EasingMode = EasingMode.EaseOut doubleAnimation.EasingFunction = sineEase storyboard.Children.Add(doubleAnimation) Storyboard.SetTarget(doubleAnimation, element1) Storyboard.SetTargetProperty( doubleAnimation, PropertyPath(UIElement.OpacityProperty)) if Grid.GetRow(element1) == 0: scale1 = Math.Max( element1.ActualWidth / maxWidth, element1.ActualHeight / maxHeight) if rectList[digits[Grid.GetColumn( element1 )]].Width > maxWidth and rectList[digits[ Grid.GetColumn( element1)]].Height > maxHeight: translateX = Math.Round( -(rectList[digits[Grid.GetColumn( element1)]].X + (rectList[digits[Grid.GetColumn( element1)]].Width - maxWidth) / 2.0)) translateY = Math.Round( -(rectList[digits[Grid.GetColumn( element1)]].Y + (rectList[digits[Grid.GetColumn( element1)]].Height - maxHeight) / 2.0)) elif rectList[digits[Grid.GetColumn( element1)]].Width > maxWidth: translateX = Math.Round( -(rectList[digits[Grid.GetColumn( element1)]].X + (rectList[digits[Grid.GetColumn( element1)]].Width - maxWidth) / 2.0)) translateY = Math.Round(-rectList[digits[ Grid.GetColumn(element1)]].Y) elif rectList[digits[Grid.GetColumn( element1)]].Height > maxHeight: translateX = Math.Round(-rectList[digits[ Grid.GetColumn(element1)]].X) translateY = Math.Round( -(rectList[digits[Grid.GetColumn( element1)]].Y + (rectList[digits[Grid.GetColumn( element1)]].Height - maxHeight) / 2.0)) else: translateX = Math.Round(-rectList[digits[ Grid.GetColumn(element1)]].X) translateY = Math.Round(-rectList[digits[ Grid.GetColumn(element1)]].Y) scale2 = Math.Max( maxWidth / rectList[digits[Grid.GetColumn( element1)]].Width, maxHeight / rectList[digits[Grid.GetColumn( element1)]].Height) if scale2 > 1: scale2 = 1 for element2 in element1.Child.Children: transformGroup1 = TransformGroup() transformGroup1.Children.Add( TranslateTransform( (element2.ActualWidth - maxWidth) / 2, (element2.ActualHeight - maxHeight) / 2)) transformGroup1.Children.Add( ScaleTransform( scale1, scale1, element2.ActualWidth / 2, element2.ActualHeight / 2)) element2.RenderTransform = transformGroup1 for element3 in element2.Children: transformGroup2 = TransformGroup() transformGroup2.Children.Add( TranslateTransform( translateX, translateY)) transformGroup2.Children.Add( ScaleTransform( scale2, scale2, maxWidth / 2, maxHeight / 2)) element3.RenderTransform = transformGroup2 contentControl.BeginStoryboard( storyboard, HandoffBehavior.SnapshotAndReplace, True) tickTimer.Start()