code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
package agent.planners; import java.util.ArrayList; import java.util.List; import java.util.Random; import utils.Utils; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; import LevelObjects.Level; import client.Command; import constants.Constants; import constants.Constants.dir; import datastructures.ActionSequence; import datastructures.AgentInState; import datastructures.BoxInState; import datastructures.GoalActionSequence; import datastructures.MoveActionSequence; import datastructures.State; public class AgentProgressionPlanner extends AgentPlanner { Level level; Random rand; private static final String name = "ProgressionPlanner"; public String getName() { return name; } public AgentProgressionPlanner(Level l) { this.level = l; rand = new Random(); } @Override public boolean goalABox(Agent agent, Box box, Goal goal) { // if this is not possible due to box in the way call: //agent.getHelpToMove(boxInTheWay) //reinsert the objective ArrayList<Field> blockedFields = new ArrayList<Field>(); blockedFields.add(box.getAtField()); // for (Agent tempAgent : level.agents) { // if(agent != tempAgent && agent.isNooping) blockedFields.add(agent.getAtField()); // } for (Agent tempAgent : level.agents) { blockedFields.add(tempAgent.getAtField()); } for (Box tempBox : level.boxes) { blockedFields.add(tempBox.getAtField()); } State newState = null; boxLoop: for (dir d : dir.values()) { Field neighbor = box.getAtField().neighborTo(d); if(neighbor == null) continue; MoveActionSequence moveAction = Utils.findRoute(level, agent.getAtField(), neighbor, blockedFields); if (moveAction == null) continue; //Here we have decided that we can get to a box. Now we must check if the box can get to a goal. //Because we are now moving the box, it's field is free. blockedFields.remove(box.getAtField()); if(!Utils.boxFitsGoal(box, goal))// Maybe this is the error? && (Field)goal != b.f) { // fits goal but is not the same goal as the box may be at already! continue; for (dir goalNeighbourDir : dir.values()) { Field goalNeighbor = goal.neighbours[goalNeighbourDir.ordinal()]; if (goalNeighbor == null) continue; GoalActionSequence routeToGoal = Utils.findGoalRoute(level, agent, box, box.getAtField().neighbours[d.ordinal()], goalNeighbor, box.getAtField(), goal, blockedFields); if (routeToGoal != null) { newState = new State(); newState.actionSequencesFromParent.add(moveAction); newState.actionSequencesFromParent.add(routeToGoal); break boxLoop; } } blockedFields.add(box.getAtField()); } if (newState == null){ for (Agent tempAgent : level.agents) { blockedFields.remove(tempAgent.getAtField()); } for (Box tempBox : level.boxes) { blockedFields.remove(tempBox.getAtField()); } boxLoop: for (dir d : dir.values()) { Field neighbor = box.getAtField().neighborTo(d); if(neighbor == null) continue; MoveActionSequence moveAction = Utils.findRouteIgnoreObstacles(level, agent, agent.getAtField(), neighbor, blockedFields); if (moveAction == null) continue; //Here we have decided that we can get to a box. Now we must check if the box can get to a goal. //Because we are now moving the box, it's field is free. blockedFields.remove(box.getAtField()); if(!Utils.boxFitsGoal(box, goal))// Maybe this is the error? && (Field)goal != b.f) { // fits goal but is not the same goal as the box may be at already! continue; for (dir goalNeighbourDir : dir.values()) { Field goalNeighbor = goal.neighbours[goalNeighbourDir.ordinal()]; if (goalNeighbor == null) continue; GoalActionSequence routeToGoal = Utils.findGoalRoute(level, agent, box, box.getAtField().neighbours[d.ordinal()], goalNeighbor, box.getAtField(), goal, blockedFields); if (routeToGoal != null) { newState = new State(); newState.actionSequencesFromParent.add(moveAction); newState.actionSequencesFromParent.add(routeToGoal); break boxLoop; } } blockedFields.add(box.getAtField()); } if (newState == null) return false; } for (ActionSequence actionSequence : newState.actionSequencesFromParent) { for (Command command : actionSequence.getCommands()) { agent.commandQueue.add(command); } } return true; } @Override public boolean move(Agent agent, List<Field> escapeFromFields, List<Field> blockedFields, int numberOfRounds) { Field toField = Utils.getFirstFreeField(agent.getAtField(), escapeFromFields, blockedFields, 20, true); if (toField == null) return false; MoveActionSequence moveAction = Utils.findRoute(level, agent.getAtField(), toField); if (moveAction == null) return false; for (Command command : moveAction.getCommands()) { agent.commandQueue.add(command); } return true; } @Override public boolean dock(Agent agent, Box box, Field field, List<Field> blockedFields, int numberOfRounds) { // We want to consider moving the box another place //Field freeField = Utils.getFreeField(level, a.a, b.b, a.f, b.f, blockedFields, 15); // TODO: change depth List<Field> freeFields = Utils.getFreeFields(box.getAtField(), blockedFields, 15, 8, false); blockedFields.remove(box.getAtField()); State newState = null; boxLoop: for (dir d : dir.values()) { //The following line will now find a path to adjacent boxes. MoveActionSequence moveAction = Utils.findRoute(level, agent.getAtField(), box.getAtField().neighbours[d.ordinal()], blockedFields); if (moveAction == null) continue; for (Field freeField : freeFields) { //System.err.println("Free field found for "+b.b.getId()+" at: " + freeField); for (dir goalNeighbourDir : dir.values()) { Field freeNeighbour = freeField.neighbours[goalNeighbourDir.ordinal()]; if (freeNeighbour == null) continue; //MoveBoxActionSequence mba = Utils.findEmptyFieldRoute(level, a.a, b.b, freeField, a.f, freeNeighbour, b.f, blockedFields); GoalActionSequence moveBoxAction = Utils.findGoalRoute(level, agent, box, box.getAtField().neighbours[d.ordinal()], freeNeighbour, box.getAtField(), freeField, blockedFields); if (moveBoxAction == null) continue; //If we get here, we have found a route to the goal. newState = new State(); if (moveBoxAction != null) { newState = new State(); newState.actionSequencesFromParent.add(moveAction); newState.actionSequencesFromParent.add(moveBoxAction); break boxLoop; } } } } for (ActionSequence actionSequence : newState.actionSequencesFromParent) { for (Command command : actionSequence.getCommands()) { agent.commandQueue.add(command); } } return true; } @Override public boolean wait(Agent agent, int numberOfRounds) { agent.isNooping = true; if (numberOfRounds>0) for(int i=0; i<numberOfRounds; i++) agent.commandQueue.add(Constants.NOOP); return true; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/agent/planners/AgentProgressionPlanner.java
Java
oos
7,468
package agent.planners; import java.util.List; import LevelObjects.Agent; import LevelObjects.Box; import LevelObjects.Field; import LevelObjects.Goal; public abstract class AgentPlanner { public abstract boolean goalABox(Agent agent, Box box, Goal goal); public abstract boolean move(Agent agent, List<Field> escapeFromFields, List<Field> blockedFields, int numberOfRounds); public abstract boolean dock(Agent agent, Box box, Field field, List<Field> blockedFields, int numberOfRounds); public abstract boolean wait(Agent agent, int numberOfRounds); }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/agent/planners/AgentPlanner.java
Java
oos
592
package agent.objectives; import java.util.List; import LevelObjects.*; public class Move extends Objective { public List<Field> blockedFields; public int numberOfRounds; public List<Field> escapeFromFields; public Move(List<Field> escapeFromField, List<Field> blockedFields, int numberOfRounds) { super(); this.blockedFields = blockedFields; this.escapeFromFields = escapeFromField; this.numberOfRounds = numberOfRounds; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/agent/objectives/Move.java
Java
oos
468
package agent.objectives; public abstract class Objective { }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/agent/objectives/Objective.java
Java
oos
69
package agent.objectives; import LevelObjects.*; public class GoalABox extends Objective { public GoalABox(Box b, Goal g) { goal = g; box = b; } public Goal goal; public Box box; }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/agent/objectives/GoalABox.java
Java
oos
208
package agent.objectives; import java.util.List; import LevelObjects.*; public class DockABox extends Objective { public Field field; public List<Field> blockedFields; public Box box; public int numberOfRounds; public DockABox(Field field, Box box, int numberOfRounds) { super(); this.field = field; this.box = box; this.numberOfRounds = numberOfRounds; } }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/agent/objectives/DockABox.java
Java
oos
399
package agent.objectives; import java.util.List; import LevelObjects.*; public class Wait extends Objective { public int numberOfRounds; public List<Field> blockedFields; }
02285-ai
trunk/ 02285-ai --username johan.beusekom@gmail.com/AI project/src/agent/objectives/Wait.java
Java
oos
191
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Constrict { public class ConstrictBlock { public const int CONSTRICT_BLOCK_SIZE = 16; public Rectangle boundedBox; private ConstrictBlockSideEnum side; private float xPos; public float constrictSpeed; public bool isMoving; public bool movingOut; public ConstrictBlock(int x, int y, ConstrictBlockSideEnum side) { boundedBox = new Rectangle(x, y, CONSTRICT_BLOCK_SIZE, CONSTRICT_BLOCK_SIZE); this.side = side; xPos = 0; constrictSpeed = 100; movingOut = true; isMoving = false; } public void Update(GameTime time) { UpdateWidth(time); CheckState(); } private void UpdateWidth(GameTime time) { if (isMoving) { if (movingOut) { xPos += constrictSpeed * (float)time.ElapsedGameTime.TotalSeconds; } else { xPos -= constrictSpeed * (float)time.ElapsedGameTime.TotalSeconds; } if (xPos < 0) { xPos = 0; } if (side == ConstrictBlockSideEnum.Left) { boundedBox.X = (int)xPos; } else { boundedBox.X = MainGame.SCREEN_WIDTH - MainGame.WALL_SIZE - (int)xPos; } } } private void CheckState() { if (xPos == 0 && !movingOut) { isMoving = false; } } public void Draw(SpriteBatch batch) { batch.Draw(MainGame.emptyTex, boundedBox, Color.Black); } } }
02-february-1gam-smoke-rush
branches/DPSFParticle/Constriction/Constriction/Constrict/ConstrictBlock.cs
C#
gpl3
2,045
namespace Constriction.Constrict { public enum ConstrictBlockSideEnum { Left = 0, Right = 1 } }
02-february-1gam-smoke-rush
branches/DPSFParticle/Constriction/Constriction/Constrict/ConstrictBlockSideEnum.cs
C#
gpl3
135
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; namespace Constriction.Constrict { public class ConstrictionManager { public List<ConstrictBlock> constrictBlocksLeft; public List<ConstrictBlock> constrictBlocksRight; private int numToConstrict; private int minConstrictSpeed, maxConstrictSpeed; public ConstrictionManager() { //72 Block Total in this configuration constrictBlocksLeft = new List<ConstrictBlock>(); constrictBlocksRight = new List<ConstrictBlock>(); FillConstrictBlocks(); numToConstrict = 5; minConstrictSpeed = 50; maxConstrictSpeed = 250; } private void FillConstrictBlocks() { //Left for (var y = 16; y < MainGame.SCREEN_HEIGHT - 16; y += ConstrictBlock.CONSTRICT_BLOCK_SIZE) { constrictBlocksLeft.Add(new ConstrictBlock(0, y, ConstrictBlockSideEnum.Left)); } //Right for (var y = 16; y < MainGame.SCREEN_HEIGHT - 16; y += ConstrictBlock.CONSTRICT_BLOCK_SIZE) { constrictBlocksRight.Add(new ConstrictBlock(MainGame.SCREEN_WIDTH - MainGame.WALL_SIZE, y, ConstrictBlockSideEnum.Right)); } } public void Update(GameTime gameTime) { int numMoving = 0; for (var i = 0; i < constrictBlocksLeft.Count; i++) { constrictBlocksLeft[i].Update(gameTime); constrictBlocksRight[i].Update(gameTime); if (constrictBlocksLeft[i].isMoving || constrictBlocksRight[i].isMoving) { numMoving++; } HandleCollision(constrictBlocksLeft[i], constrictBlocksRight[i]); } if (numMoving < numToConstrict) { StartMoving(numToConstrict - numMoving); } } private void HandleCollision(ConstrictBlock block1, ConstrictBlock block2) { if(block1.boundedBox.Intersects(block2.boundedBox)) { block1.movingOut = false; block2.movingOut = false; } } private void StartMoving(int numToStartConstrict) { for (var i = 0; i < numToStartConstrict; i++) { int index = MainGame.rand.Next(constrictBlocksLeft.Count - 1); float speed1 = MainGame.rand.Next(minConstrictSpeed, maxConstrictSpeed); float speed2 = MainGame.rand.Next(minConstrictSpeed, maxConstrictSpeed); MoveBlock(constrictBlocksLeft[index], speed1); MoveBlock(constrictBlocksRight[index], speed2); } } private void MoveBlock(ConstrictBlock block, float speed) { if (!block.isMoving) { block.isMoving = true; block.movingOut = true; block.constrictSpeed = speed; } } public void Draw(SpriteBatch batch) { for (var i = 0; i < constrictBlocksLeft.Count; i++) { constrictBlocksLeft[i].Draw(batch); constrictBlocksRight[i].Draw(batch); } } public bool DoesContactPlayer(Rectangle box) { for (var i = 0; i < constrictBlocksLeft.Count; i++) { if (box.Intersects(constrictBlocksLeft[i].boundedBox) || box.Intersects(constrictBlocksRight[i].boundedBox)) { return true; } } return false; } } }
02-february-1gam-smoke-rush
branches/DPSFParticle/Constriction/Constriction/Constrict/ConstrictionManager.cs
C#
gpl3
3,910
using Constriction.Walls; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Constriction.Constrict; using System; using Constriction.Particle; namespace Constriction { /// <summary> /// This is the main type for your game /// </summary> public class MainGame : Microsoft.Xna.Framework.Game { public const int SCREEN_WIDTH = 800; public const int SCREEN_HEIGHT = 600; public const int WALL_SIZE = 16; GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public static Texture2D emptyTex; public static SpriteFont hudFont; public static Random rand; FogParticleSystem fogParticleSystem; WallManager wallManager; ConstrictionManager constrictionManager; Player player; Goal goal; ScoreHUD hud; public MainGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = SCREEN_WIDTH; graphics.PreferredBackBufferHeight = SCREEN_HEIGHT; } protected override void Initialize() { rand = new Random(); player = new Player(); goal = new Goal(); wallManager = new WallManager(); constrictionManager = new ConstrictionManager(); player.wallManager = wallManager; hud = new ScoreHUD(); fogParticleSystem = new FogParticleSystem(this); base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); emptyTex = Content.Load<Texture2D>("Sprite/Empty"); hudFont = Content.Load<SpriteFont>("Font/HUDFont"); player.tex = Content.Load<Texture2D>("Sprite/Player"); goal.tex = Content.Load<Texture2D>("Sprite/Goal"); fogParticleSystem.Initialize(GraphicsDevice, Content, spriteBatch, constrictionManager); } protected override void Update(GameTime gameTime) { // Allows the game to exit if (Keyboard.GetState().IsKeyDown(Keys.Escape) || GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { this.Exit(); } HandleInput(); player.Update(gameTime); constrictionManager.Update(gameTime); fogParticleSystem.Update(gameTime, constrictionManager); if (player.boundedBox.Intersects(goal.boundedBox)) { HandleGoalCollision(); } if (constrictionManager.DoesContactPlayer(player.boundedBox)) { //TODO Hurt Player } base.Update(gameTime); } private void HandleInput() { var state = Keyboard.GetState(); player.upPressed = state.IsKeyDown(Keys.Up); player.downPressed = state.IsKeyDown(Keys.Down); player.leftPressed = state.IsKeyDown(Keys.Left); player.rightPressed = state.IsKeyDown(Keys.Right); player.runPressed = state.IsKeyDown(Keys.LeftShift); player.walkPressed = state.IsKeyDown(Keys.LeftControl); } private void HandleGoalCollision() { hud.curScore += 1; goal.ChangePosition(); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.White); spriteBatch.Begin(); constrictionManager.Draw(spriteBatch); player.Draw(spriteBatch); goal.Draw(spriteBatch); wallManager.Draw(spriteBatch); hud.Draw(spriteBatch); fogParticleSystem.Draw(); spriteBatch.End(); base.Draw(gameTime); } } }
02-february-1gam-smoke-rush
branches/DPSFParticle/Constriction/Constriction/MainGame.cs
C#
gpl3
4,122
using System; using Constriction.Walls; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction { public class Player { public const int PLAYER_WIDTH = 32; public const int PLAYER_HEIGHT = 32; public const int PLAYER_RUN_SPEED = 300; public const int PLAYER_JOG_SPEED = 170; public const int PLAYER_WALK_SPEED = 100; public Rectangle boundedBox; public Texture2D tex; public WallManager wallManager; public bool upPressed, downPressed; public bool leftPressed, rightPressed; public bool runPressed, walkPressed; private Vector2 position; private Vector2 velocity; private float rotation; public Player() { position = new Vector2(400, 300); boundedBox = new Rectangle((int)position.X, (int)position.Y, PLAYER_WIDTH, PLAYER_HEIGHT); } public void Update(GameTime time) { HandleInput(time); UpdatePosition(); UpdateBox(); } private void HandleInput(GameTime time) { velocity = Vector2.Zero; int speed; if (runPressed) { speed = PLAYER_RUN_SPEED; } else if (walkPressed) { speed = PLAYER_WALK_SPEED; } else { speed = PLAYER_JOG_SPEED; } if (upPressed) { velocity.Y -= speed; } if (downPressed) { velocity.Y += speed; } if (leftPressed) { velocity.X -= speed; } if (rightPressed) { velocity.X += speed; } if (velocity != Vector2.Zero) { rotation = (float)Math.Atan2(velocity.Y, velocity.X); velocity.Normalize(); velocity *= speed * (float)time.ElapsedGameTime.TotalSeconds; } } private void UpdatePosition() { position.X += velocity.X; UpdateBox(); var solidObstacle = wallManager.IsSpaceFree(this.boundedBox); if (solidObstacle.HasValue) { if (velocity.X > 0)//Right { position.X = solidObstacle.Value.Left - PLAYER_WIDTH; } else if (velocity.X < 0)//Left { position.X = solidObstacle.Value.Right; } } position.Y += velocity.Y; UpdateBox(); solidObstacle = wallManager.IsSpaceFree(this.boundedBox); if (solidObstacle.HasValue) { if (velocity.Y > 0)//Down { position.Y = solidObstacle.Value.Top - PLAYER_HEIGHT; } else if (velocity.Y < 0)//Up { position.Y = solidObstacle.Value.Bottom; } } UpdateBox(); } private void UpdateBox() { boundedBox.Location = new Point((int)position.X, (int)position.Y); } public void Draw(SpriteBatch batch) { float xPos = position.X + PLAYER_WIDTH / 2; float yPos = position.Y + PLAYER_HEIGHT / 2; batch.Draw(tex, new Vector2(xPos, yPos), null, Color.White, rotation, new Vector2(PLAYER_WIDTH / 2, PLAYER_HEIGHT / 2), 1, SpriteEffects.None, 0); } } }
02-february-1gam-smoke-rush
branches/DPSFParticle/Constriction/Constriction/Player.cs
C#
gpl3
3,868
using System; using DPSF; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; using Constriction.Constrict; namespace Constriction.Particle { /// <summary> /// Create a new Particle System class that inherits from a Default DPSF Particle System. /// </summary> [Serializable] class FogParticleSystem : DefaultSpriteParticleSystem { /// <summary> /// Constructor /// </summary> /// <param name="cGame">Handle to the Game object being used. Pass in null for this /// parameter if not using a Game object.</param> public FogParticleSystem(Game cGame) : base(cGame) { } /// <summary> /// Function to Initialize the Particle System with default values. /// Particle system properties should not be set until after this is called, as /// they are likely to be reset to their default values. /// </summary> /// <param name="cGraphicsDevice">The Graphics Device the Particle System should use</param> /// <param name="cContentManager">The Content Manager the Particle System should use to load resources</param> /// <param name="cSpriteBatch">The Sprite Batch that the Sprite Particle System should use to draw its particles. /// If this is not initializing a Sprite particle system, or you want the particle system to use its own Sprite Batch, /// pass in null.</param> public void Initialize(GraphicsDevice cGraphicsDevice, ContentManager cContentManager, SpriteBatch cSpriteBatch, ConstrictionManager blockManager) { base.AutoInitialize(cGraphicsDevice, cContentManager, cSpriteBatch); base.InitializeSpriteParticleSystem(cGraphicsDevice, cContentManager, 1000, 50000, "Particle/FogParticle", cSpriteBatch); Name = "Fog Particle System"; // Finish loading the Particle System in a separate function call, so if // we want to reset the Particle System later we don't need to completely // re-initialize it, we can just call this function to reset it. LoadParticleSystem(); InitializeEmitters(blockManager); } /// <summary> /// Load the Particle System Events and any other settings /// </summary> public void LoadParticleSystem() { ParticleInitializationFunction = InitializeParticleUsingInitialProperties; // Setup the Initial Properties of the Particles. // These are only applied if using InitializeParticleUsingInitialProperties // as the Particle Initialization Function. InitialProperties.LifetimeMin = 2.0f; InitialProperties.LifetimeMax = 3.0f; InitialProperties.PositionMin = Vector3.Zero; InitialProperties.PositionMax = Vector3.Zero; InitialProperties.VelocityMin = new Vector3(10, 10, 0); InitialProperties.VelocityMax = new Vector3(-10, -10, 0); InitialProperties.StartSizeMin = 8; InitialProperties.StartSizeMax = 32; InitialProperties.StartColorMin = Color.Black; InitialProperties.StartColorMax = Color.Black; InitialProperties.EndColorMin = Color.Black; InitialProperties.EndColorMax = Color.Black; // Remove all Events first so that none are added twice if this function is called again ParticleEvents.RemoveAllEvents(); ParticleSystemEvents.RemoveAllEvents(); // Allow the Particle's Position, Rotation, Width and Height, Color, and Transparency to be updated each frame ParticleEvents.AddEveryTimeEvent(UpdateParticlePositionUsingVelocity); ParticleEvents.AddEveryTimeEvent(UpdateParticleTransparencyToFadeOutUsingLerp); } private void InitializeEmitters(ConstrictionManager blockManager) { foreach (var block in blockManager.constrictBlocksLeft) { var emitter = new ParticleEmitter(); emitter.ParticlesPerSecond = 100; emitter.PositionData.Position = new Vector3(block.boundedBox.Right, block.boundedBox.Center.Y, 0); this.Emitters.Add(emitter); } foreach (var block in blockManager.constrictBlocksRight) { var emitter = new ParticleEmitter(); emitter.ParticlesPerSecond = 100; emitter.PositionData.Position = new Vector3(block.boundedBox.Left, block.boundedBox.Center.Y, 0); this.Emitters.Add(emitter); } } public void Update(GameTime time, ConstrictionManager blockManager) { UpdateEmitters(blockManager); base.Update((float)time.ElapsedGameTime.TotalSeconds); } private void UpdateEmitters(ConstrictionManager blockManager) { var index = 0; foreach (var block in blockManager.constrictBlocksLeft) { var emitter = this.Emitters[index]; emitter.Enabled = block.isMoving; emitter.PositionData.Position = new Vector3(block.boundedBox.Right, block.boundedBox.Center.Y, 0); index++; } foreach (var block in blockManager.constrictBlocksRight) { var emitter = this.Emitters[index]; emitter.Enabled = block.isMoving; emitter.PositionData.Position = new Vector3(block.boundedBox.Left, block.boundedBox.Center.Y, 0); index++; } } } }
02-february-1gam-smoke-rush
branches/DPSFParticle/Constriction/Constriction/Particle/FogParticleSystem.cs
C#
gpl3
5,472
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Constriction")] [assembly: AssemblyProduct("Constriction")] [assembly: AssemblyDescription("")] [assembly: AssemblyCompany("Hewlett-Packard Company")] [assembly: AssemblyCopyright("Copyright © Hewlett-Packard Company 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. Only Windows // assemblies support COM. [assembly: ComVisible(false)] // On Windows, the following GUID is for the ID of the typelib if this // project is exposed to COM. On other platforms, it unique identifies the // title storage container when deploying this assembly to the device. [assembly: Guid("689a6417-13c2-4d19-9740-209ed5f83db1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")]
02-february-1gam-smoke-rush
branches/DPSFParticle/Constriction/Constriction/Properties/AssemblyInfo.cs
C#
gpl3
1,410
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction { public class ScoreHUD { private Vector2 position; public int curScore; public ScoreHUD() { position = new Vector2(16, 0); curScore = 0; } public void Draw(SpriteBatch batch) { batch.DrawString(MainGame.hudFont, string.Format("Score: {0}", curScore), position, Color.White); } } }
02-february-1gam-smoke-rush
branches/DPSFParticle/Constriction/Constriction/ScoreHUD.cs
C#
gpl3
516
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction { public class Goal { public const int GOAL_WIDTH = 16; public const int GOAL_HEIGHT = 16; public Texture2D tex; public Rectangle boundedBox; public Goal() { boundedBox = new Rectangle(0, 0, GOAL_WIDTH, GOAL_HEIGHT); ChangePosition(); } public void ChangePosition() { boundedBox.X = MainGame.rand.Next(MainGame.WALL_SIZE, MainGame.SCREEN_WIDTH - MainGame.WALL_SIZE - GOAL_WIDTH); boundedBox.Y = MainGame.rand.Next(MainGame.WALL_SIZE, MainGame.SCREEN_HEIGHT - MainGame.WALL_SIZE - GOAL_HEIGHT); } public void Draw(SpriteBatch batch) { batch.Draw(tex, boundedBox, Color.White); } } }
02-february-1gam-smoke-rush
branches/DPSFParticle/Constriction/Constriction/Goal.cs
C#
gpl3
891
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Walls { public class Wall { public Rectangle boundedBox; public Texture2D tex; public Wall(int x, int y, int width, int height) { boundedBox = new Rectangle(x, y, width, height); } public void Draw(SpriteBatch batch) { batch.Draw(MainGame.emptyTex, boundedBox, Color.Black); } } }
02-february-1gam-smoke-rush
branches/DPSFParticle/Constriction/Constriction/Walls/Wall.cs
C#
gpl3
502
using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Walls { public class WallManager { public List<Wall> walls; public WallManager() { walls = new List<Wall>(); walls.Add(new Wall(0, 0, MainGame.SCREEN_WIDTH, MainGame.WALL_SIZE));//Top walls.Add(new Wall(0, MainGame.SCREEN_HEIGHT - MainGame.WALL_SIZE, MainGame.SCREEN_WIDTH, MainGame.WALL_SIZE));//Bottom walls.Add(new Wall(0, 0, MainGame.WALL_SIZE, MainGame.SCREEN_HEIGHT));//Left walls.Add(new Wall(MainGame.SCREEN_WIDTH - MainGame.WALL_SIZE, 0, MainGame.WALL_SIZE, MainGame.SCREEN_HEIGHT));//Right } public Rectangle? IsSpaceFree(Rectangle box) { foreach (var wall in walls) { if (box.Intersects(wall.boundedBox)) { return wall.boundedBox; } } return null; } public void Draw(SpriteBatch batch) { foreach (var wall in walls) { wall.Draw(batch); } } } }
02-february-1gam-smoke-rush
branches/DPSFParticle/Constriction/Constriction/Walls/WallManager.cs
C#
gpl3
1,254
using System; namespace Constriction { #if WINDOWS || XBOX static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { using (MainGame game = new MainGame()) { game.Run(); } } } #endif }
02-february-1gam-smoke-rush
branches/DPSFParticle/Constriction/Constriction/Program.cs
C#
gpl3
394
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Constrict { public class ConstrictPoint { public static float MinDistanceToTarget; public static float ConstrictTime;//Num of seconds to reach target public static float WiggleTime; private Vector2 origPosition; private Vector2 curPosition; private Vector2 drawPosition; private Vector2 wiggleTarget; private Vector2 velocity; private Vector2 wiggleVelocity; public bool waitingAtOrigPosition; public bool isWiggling; private bool movingTowardsTarget; public ConstrictPoint(Vector2 position) { origPosition = position; curPosition = position; drawPosition = position; velocity = Vector2.Zero; waitingAtOrigPosition = true; isWiggling = false; movingTowardsTarget = true; } public void Update(GameTime time, Vector2 target) { if (!waitingAtOrigPosition) { if (movingTowardsTarget) { UpdateVelocity(target, MinDistanceToTarget); MoveTowardsTarget(time, target); CheckTarget(target); } else { UpdateVelocity(origPosition, 0); MoveTowardsTarget(time, origPosition); CheckOrigPosition(); } UpdateWiggle(time); } } private void UpdateVelocity(Vector2 target, float stopAt) { if (velocity == Vector2.Zero) { float distance = Vector2.Distance(curPosition, target); distance -= stopAt; float distancePerSecond = distance / ConstrictTime; velocity = target - curPosition; velocity.Normalize(); velocity *= distancePerSecond; } } private void MoveTowardsTarget(GameTime time, Vector2 target) { curPosition += velocity * (float)time.ElapsedGameTime.TotalSeconds; } private void CheckTarget(Vector2 target) { if (Vector2.Distance(curPosition, target) < MinDistanceToTarget) { movingTowardsTarget = !movingTowardsTarget; velocity = Vector2.Zero; } } private void CheckOrigPosition() { if (Vector2.Distance(curPosition, origPosition) < 1) { movingTowardsTarget = !movingTowardsTarget; velocity = Vector2.Zero; waitingAtOrigPosition = true; } } public void StartWiggling(Vector2 target, bool wiggleTowardsTarget) { drawPosition = curPosition; if (wiggleTowardsTarget) { wiggleTarget = target; } else { var newWiggleTarget = origPosition - curPosition; newWiggleTarget = new Vector2(newWiggleTarget.X * 0.8f, newWiggleTarget.Y * 0.8f); wiggleTarget = curPosition + newWiggleTarget; } wiggleVelocity = wiggleTarget - curPosition; wiggleVelocity.Normalize(); wiggleVelocity *= WiggleTime; isWiggling = true; } private void UpdateWiggle(GameTime time) { //TODO Smooth animation when retracting wiggle if (isWiggling) { if (Vector2.Distance(drawPosition, wiggleTarget) < 32) { isWiggling = false; drawPosition = curPosition; } else { drawPosition += wiggleVelocity * (float)time.ElapsedGameTime.TotalSeconds; } } else { drawPosition = curPosition; } } public void Draw(SpriteBatch batch) { batch.Draw(MainGame.emptyTex, curPosition, Color.Black); batch.Draw(MainGame.emptyTex, new Rectangle((int)wiggleTarget.X, (int)wiggleTarget.Y, 5, 5), Color.Red); batch.Draw(MainGame.emptyTex, new Rectangle((int)drawPosition.X, (int)drawPosition.Y, 5, 5), Color.Green); } public Vector2 DrawPosition { get { return drawPosition; } } public Vector2 OrigPosition { get { return origPosition; } } } }
02-february-1gam-smoke-rush
branches/AllWallsConstrict/Constriction/Constriction/Constrict/ConstrictPoint.cs
C#
gpl3
4,809
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; namespace Constriction.Constrict { public class ConstrictionManager { public const int CONSTRICT_POINT_SPACING = 32; public static int numToWiggle = 3; public static float wiggleSpeed = 400; private List<ConstrictPoint> constrictPoints; private Vector2 target; private bool readyToWiggle; public ConstrictionManager() { target = new Vector2(400, 300); constrictPoints = new List<ConstrictPoint>(); FillConstrictPoints(); readyToWiggle = true; } private void FillConstrictPoints() { //Top for (var x = 16; x < MainGame.SCREEN_WIDTH; x += CONSTRICT_POINT_SPACING) { constrictPoints.Add(new ConstrictPoint(new Vector2(x, 16))); } //Right for (var y = 16; y < MainGame.SCREEN_HEIGHT; y += CONSTRICT_POINT_SPACING) { constrictPoints.Add(new ConstrictPoint(new Vector2(MainGame.SCREEN_WIDTH - 16, y))); //Right } //Bottom Reverse for (var x = MainGame.SCREEN_WIDTH - 16; x >= 32; x -= CONSTRICT_POINT_SPACING) { constrictPoints.Add(new ConstrictPoint(new Vector2(x, MainGame.SCREEN_HEIGHT - 16))); //Bottom } //Left Reverse for (var y = MainGame.SCREEN_HEIGHT - 16; y >= 32; y -= CONSTRICT_POINT_SPACING) { constrictPoints.Add(new ConstrictPoint(new Vector2(16, y))); //Left } } public void Update(GameTime gameTime) { bool waitingAtOrigPosition = true; bool wiggling = false; foreach (var point in constrictPoints) { point.Update(gameTime, target); if (!point.waitingAtOrigPosition) { waitingAtOrigPosition = false; } if (point.isWiggling) { wiggling = true; } } if (waitingAtOrigPosition) { UpdateTarget(); foreach (var point in constrictPoints) { point.waitingAtOrigPosition = false; } } if (!wiggling) { for (var i = 0; i < numToWiggle; i++) { bool wiggleIn = MainGame.rand.Next(100) < 50; var middle = MainGame.rand.Next(1, constrictPoints.Count - 2); constrictPoints[middle - 1].StartWiggling(target, wiggleIn); constrictPoints[middle].StartWiggling(target, wiggleIn); constrictPoints[middle + 1].StartWiggling(target, wiggleIn); } } } private void UpdateTarget() { target.X = MainGame.rand.Next(MainGame.WALL_SIZE, MainGame.SCREEN_WIDTH - MainGame.WALL_SIZE); target.Y = MainGame.rand.Next(MainGame.WALL_SIZE, MainGame.SCREEN_HEIGHT - MainGame.WALL_SIZE); } public void Draw(SpriteBatch batch) { foreach (var point in constrictPoints) { point.Draw(batch); } } public bool DoesContactPlayer(Rectangle box) { return false; } public Vector2[] GetAllPointVectors() { var vectors = new List<Vector2>(); foreach (var point in constrictPoints) { vectors.Add(point.DrawPosition); } return vectors.ToArray(); } public VertexPositionColor[] GetAllPointLocations() { var locations = new List<VertexPositionColor>(); foreach (var point in constrictPoints) { locations.Add(new VertexPositionColor(new Vector3(point.DrawPosition.X, point.DrawPosition.Y, 0), Color.Black)); locations.Add(new VertexPositionColor(new Vector3(point.OrigPosition.X, point.OrigPosition.Y, 0), Color.Black)); } locations.Add(new VertexPositionColor(new Vector3(constrictPoints[0].DrawPosition.X, constrictPoints[0].DrawPosition.Y, 0), Color.Black)); locations.Add(new VertexPositionColor(new Vector3(constrictPoints[0].OrigPosition.X, constrictPoints[0].OrigPosition.Y, 0), Color.Black)); return locations.ToArray(); } } }
02-february-1gam-smoke-rush
branches/AllWallsConstrict/Constriction/Constriction/Constrict/ConstrictionManager.cs
C#
gpl3
4,819
using Constriction.Walls; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Constriction.Constrict; using System; namespace Constriction { /// <summary> /// This is the main type for your game /// </summary> public class MainGame : Microsoft.Xna.Framework.Game { public const int SCREEN_WIDTH = 800; public const int SCREEN_HEIGHT = 600; public const int WALL_SIZE = 16; GraphicsDeviceManager graphics; SpriteBatch spriteBatch; BasicEffect basicEffect; public static Texture2D emptyTex; public static SpriteFont hudFont; public static Random rand; WallManager wallManager; ConstrictionManager constrictionManager; Player player; Goal goal; ScoreHUD hud; public MainGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = SCREEN_WIDTH; graphics.PreferredBackBufferHeight = SCREEN_HEIGHT; } protected override void Initialize() { basicEffect = new BasicEffect(graphics.GraphicsDevice); basicEffect.VertexColorEnabled = true; basicEffect.Projection = Matrix.CreateOrthographicOffCenter (0, graphics.GraphicsDevice.Viewport.Width, // left, right graphics.GraphicsDevice.Viewport.Height, 0, // bottom, top 0, 1); // near, far plane rand = new Random(); player = new Player(); goal = new Goal(); wallManager = new WallManager(); constrictionManager = new ConstrictionManager(); player.wallManager = wallManager; hud = new ScoreHUD(); ConstrictPoint.MinDistanceToTarget = 50; ConstrictPoint.ConstrictTime = 2; ConstrictPoint.WiggleTime = 500; base.Initialize(); } protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); emptyTex = Content.Load<Texture2D>("Sprite/Empty"); hudFont = Content.Load<SpriteFont>("Font/HUDFont"); player.tex = Content.Load<Texture2D>("Sprite/Player"); goal.tex = Content.Load<Texture2D>("Sprite/Goal"); } protected override void Update(GameTime gameTime) { // Allows the game to exit if (Keyboard.GetState().IsKeyDown(Keys.Escape) || GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { this.Exit(); } HandleInput(); player.Update(gameTime); constrictionManager.Update(gameTime); if (player.boundedBox.Intersects(goal.boundedBox)) { HandleGoalCollision(); } if (constrictionManager.DoesContactPlayer(player.boundedBox)) { //TODO Hurt Player } base.Update(gameTime); } private void HandleInput() { var state = Keyboard.GetState(); player.upPressed = state.IsKeyDown(Keys.Up); player.downPressed = state.IsKeyDown(Keys.Down); player.leftPressed = state.IsKeyDown(Keys.Left); player.rightPressed = state.IsKeyDown(Keys.Right); player.runPressed = state.IsKeyDown(Keys.LeftShift); player.walkPressed = state.IsKeyDown(Keys.LeftControl); } private void HandleGoalCollision() { hud.curScore += 1; goal.ChangePosition(); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.White); spriteBatch.Begin(); DrawConstrictingBlackness(spriteBatch); player.Draw(spriteBatch); goal.Draw(spriteBatch); wallManager.Draw(spriteBatch); constrictionManager.Draw(spriteBatch); hud.Draw(spriteBatch); spriteBatch.End(); base.Draw(gameTime); } private void DrawConstrictingBlackness(SpriteBatch batch) { var constrictPoints = constrictionManager.GetAllPointLocations(); basicEffect.CurrentTechnique.Passes[0].Apply(); graphics.GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.TriangleStrip, constrictPoints, 0, constrictPoints.Length - 2); } } }
02-february-1gam-smoke-rush
branches/AllWallsConstrict/Constriction/Constriction/MainGame.cs
C#
gpl3
4,908
using System; using Constriction.Walls; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction { public class Player { public const int PLAYER_WIDTH = 32; public const int PLAYER_HEIGHT = 32; public const int PLAYER_RUN_SPEED = 300; public const int PLAYER_JOG_SPEED = 170; public const int PLAYER_WALK_SPEED = 100; public Rectangle boundedBox; public Texture2D tex; public WallManager wallManager; public bool upPressed, downPressed; public bool leftPressed, rightPressed; public bool runPressed, walkPressed; private Vector2 position; private Vector2 velocity; private float rotation; public Player() { position = new Vector2(400, 300); boundedBox = new Rectangle((int)position.X, (int)position.Y, PLAYER_WIDTH, PLAYER_HEIGHT); } public void Update(GameTime time) { HandleInput(time); UpdatePosition(); UpdateBox(); } private void HandleInput(GameTime time) { velocity = Vector2.Zero; int speed; if (runPressed) { speed = PLAYER_RUN_SPEED; } else if (walkPressed) { speed = PLAYER_WALK_SPEED; } else { speed = PLAYER_JOG_SPEED; } if (upPressed) { velocity.Y -= speed; } if (downPressed) { velocity.Y += speed; } if (leftPressed) { velocity.X -= speed; } if (rightPressed) { velocity.X += speed; } if (velocity != Vector2.Zero) { rotation = (float)Math.Atan2(velocity.Y, velocity.X); velocity.Normalize(); velocity *= speed * (float)time.ElapsedGameTime.TotalSeconds; } } private void UpdatePosition() { position.X += velocity.X; UpdateBox(); var solidObstacle = wallManager.IsSpaceFree(this.boundedBox); if (solidObstacle.HasValue) { if (velocity.X > 0)//Right { position.X = solidObstacle.Value.Left - PLAYER_WIDTH; } else if (velocity.X < 0)//Left { position.X = solidObstacle.Value.Right; } } position.Y += velocity.Y; UpdateBox(); solidObstacle = wallManager.IsSpaceFree(this.boundedBox); if (solidObstacle.HasValue) { if (velocity.Y > 0)//Down { position.Y = solidObstacle.Value.Top - PLAYER_HEIGHT; } else if (velocity.Y < 0)//Up { position.Y = solidObstacle.Value.Bottom; } } UpdateBox(); } private void UpdateBox() { boundedBox.Location = new Point((int)position.X, (int)position.Y); } public void Draw(SpriteBatch batch) { float xPos = position.X + PLAYER_WIDTH / 2; float yPos = position.Y + PLAYER_HEIGHT / 2; batch.Draw(tex, new Vector2(xPos, yPos), null, Color.White, rotation, new Vector2(PLAYER_WIDTH / 2, PLAYER_HEIGHT / 2), 1, SpriteEffects.None, 0); } } }
02-february-1gam-smoke-rush
branches/AllWallsConstrict/Constriction/Constriction/Player.cs
C#
gpl3
3,868
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Constriction")] [assembly: AssemblyProduct("Constriction")] [assembly: AssemblyDescription("")] [assembly: AssemblyCompany("Hewlett-Packard Company")] [assembly: AssemblyCopyright("Copyright © Hewlett-Packard Company 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. Only Windows // assemblies support COM. [assembly: ComVisible(false)] // On Windows, the following GUID is for the ID of the typelib if this // project is exposed to COM. On other platforms, it unique identifies the // title storage container when deploying this assembly to the device. [assembly: Guid("689a6417-13c2-4d19-9740-209ed5f83db1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")]
02-february-1gam-smoke-rush
branches/AllWallsConstrict/Constriction/Constriction/Properties/AssemblyInfo.cs
C#
gpl3
1,410
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction { public class ScoreHUD { private Vector2 position; public int curScore; public ScoreHUD() { position = new Vector2(16, 0); curScore = 0; } public void Draw(SpriteBatch batch) { batch.DrawString(MainGame.hudFont, string.Format("Score: {0}", curScore), position, Color.White); } } }
02-february-1gam-smoke-rush
branches/AllWallsConstrict/Constriction/Constriction/ScoreHUD.cs
C#
gpl3
516
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction { public class Goal { public const int GOAL_WIDTH = 16; public const int GOAL_HEIGHT = 16; public Texture2D tex; public Rectangle boundedBox; public Goal() { boundedBox = new Rectangle(0, 0, GOAL_WIDTH, GOAL_HEIGHT); ChangePosition(); } public void ChangePosition() { boundedBox.X = MainGame.rand.Next(MainGame.WALL_SIZE, MainGame.SCREEN_WIDTH - MainGame.WALL_SIZE - GOAL_WIDTH); boundedBox.Y = MainGame.rand.Next(MainGame.WALL_SIZE, MainGame.SCREEN_HEIGHT - MainGame.WALL_SIZE - GOAL_HEIGHT); } public void Draw(SpriteBatch batch) { batch.Draw(tex, boundedBox, Color.White); } } }
02-february-1gam-smoke-rush
branches/AllWallsConstrict/Constriction/Constriction/Goal.cs
C#
gpl3
891
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Walls { public class Wall { public Rectangle boundedBox; public Texture2D tex; public Wall(int x, int y, int width, int height) { boundedBox = new Rectangle(x, y, width, height); } public void Draw(SpriteBatch batch) { batch.Draw(MainGame.emptyTex, boundedBox, Color.Black); } } }
02-february-1gam-smoke-rush
branches/AllWallsConstrict/Constriction/Constriction/Walls/Wall.cs
C#
gpl3
502
using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Walls { public class WallManager { public List<Wall> walls; public WallManager() { walls = new List<Wall>(); walls.Add(new Wall(0, 0, MainGame.SCREEN_WIDTH, MainGame.WALL_SIZE));//Top walls.Add(new Wall(0, MainGame.SCREEN_HEIGHT - MainGame.WALL_SIZE, MainGame.SCREEN_WIDTH, MainGame.WALL_SIZE));//Bottom walls.Add(new Wall(0, 0, MainGame.WALL_SIZE, MainGame.SCREEN_HEIGHT));//Left walls.Add(new Wall(MainGame.SCREEN_WIDTH - MainGame.WALL_SIZE, 0, MainGame.WALL_SIZE, MainGame.SCREEN_HEIGHT));//Right } public Rectangle? IsSpaceFree(Rectangle box) { foreach (var wall in walls) { if (box.Intersects(wall.boundedBox)) { return wall.boundedBox; } } return null; } public void Draw(SpriteBatch batch) { foreach (var wall in walls) { wall.Draw(batch); } } } }
02-february-1gam-smoke-rush
branches/AllWallsConstrict/Constriction/Constriction/Walls/WallManager.cs
C#
gpl3
1,254
using System; namespace Constriction { #if WINDOWS || XBOX static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { using (MainGame game = new MainGame()) { game.Run(); } } } #endif }
02-february-1gam-smoke-rush
branches/AllWallsConstrict/Constriction/Constriction/Program.cs
C#
gpl3
394
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Constrict { public class ConstrictBlock { public const int CONSTRICT_BLOCK_LONG = 64; public const int CONSTRICT_BLOCK_SHORT = 16; public Rectangle boundedBox; private ConstrictBlockSideEnum side; private float pos; public float constrictSpeed; public bool isMoving; public ConstrictBlock(int x, int y, ConstrictBlockSideEnum side) { switch (side) { case ConstrictBlockSideEnum.Left: case ConstrictBlockSideEnum.Right: boundedBox = new Rectangle(x, y, CONSTRICT_BLOCK_LONG, CONSTRICT_BLOCK_SHORT); break; case ConstrictBlockSideEnum.Top: case ConstrictBlockSideEnum.Bottom: boundedBox = new Rectangle(x, y, CONSTRICT_BLOCK_SHORT, CONSTRICT_BLOCK_LONG); break; } this.side = side; pos = 0; constrictSpeed = 100; isMoving = false; } public void Update(GameTime time) { if (isMoving) { UpdatePosition(time); CheckState(); } } private void UpdatePosition(GameTime time) { pos += constrictSpeed * (float)time.ElapsedGameTime.TotalSeconds; switch (side) { case ConstrictBlockSideEnum.Left: boundedBox.X = (int)pos - CONSTRICT_BLOCK_LONG; break; case ConstrictBlockSideEnum.Right: boundedBox.X = MainGame.SCREEN_WIDTH - MainGame.WALL_SIZE - (int)pos; break; case ConstrictBlockSideEnum.Top: boundedBox.Y = (int)pos - CONSTRICT_BLOCK_LONG; break; case ConstrictBlockSideEnum.Bottom: boundedBox.Y = MainGame.SCREEN_HEIGHT - MainGame.WALL_SIZE - (int)pos; break; } } private void CheckState() { float targetPos = 0; switch (side) { case ConstrictBlockSideEnum.Left: case ConstrictBlockSideEnum.Right: targetPos = MainGame.SCREEN_WIDTH + CONSTRICT_BLOCK_LONG; break; case ConstrictBlockSideEnum.Top: case ConstrictBlockSideEnum.Bottom: targetPos = MainGame.SCREEN_HEIGHT + CONSTRICT_BLOCK_LONG;; break; } if (pos > targetPos) { isMoving = false; pos = 0; } } public void Draw(SpriteBatch batch) { batch.Draw(MainGame.emptyTex, boundedBox, Color.Black); } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Constrict/ConstrictBlock.cs
C#
gpl3
3,085
namespace Constriction.Constrict { public enum ConstrictBlockSideEnum { Left = 0, Right = 1, Top = 2, Bottom = 3 } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Constrict/ConstrictBlockSideEnum.cs
C#
gpl3
174
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; namespace Constriction.Constrict { public class ConstrictionManager { public const int BASE_NUM_TO_MOVE = 5; public const int BASE_MIN_BLOCK_SPEED = 50; public const int BASE_MAX_BLOCK_SPEED = 250; public List<ConstrictBlock> constrictBlocksLeft; public List<ConstrictBlock> constrictBlocksRight; public List<ConstrictBlock> constrictBlocksTop; public List<ConstrictBlock> constrictBlocksBottom; private int numToMove; private int minBlockSpeed, maxBlockSpeed; public ConstrictionManager() { constrictBlocksLeft = new List<ConstrictBlock>(); constrictBlocksRight = new List<ConstrictBlock>(); constrictBlocksTop = new List<ConstrictBlock>(); constrictBlocksBottom = new List<ConstrictBlock>(); Reset(); } public void Reset() { constrictBlocksLeft.Clear(); constrictBlocksRight.Clear(); constrictBlocksTop.Clear(); constrictBlocksBottom.Clear(); FillConstrictBlocks(); numToMove = BASE_NUM_TO_MOVE; minBlockSpeed = BASE_MIN_BLOCK_SPEED; maxBlockSpeed = BASE_MAX_BLOCK_SPEED; } private void FillConstrictBlocks() { //Left & Right for (var y = 16; y < MainGame.SCREEN_HEIGHT - 16; y += ConstrictBlock.CONSTRICT_BLOCK_SHORT) { constrictBlocksLeft.Add(new ConstrictBlock(-ConstrictBlock.CONSTRICT_BLOCK_LONG, y, ConstrictBlockSideEnum.Left)); constrictBlocksRight.Add(new ConstrictBlock(MainGame.SCREEN_WIDTH - MainGame.WALL_SIZE, y, ConstrictBlockSideEnum.Right)); } //Top & Bottom for (var x = 16; x < MainGame.SCREEN_WIDTH - 16; x += ConstrictBlock.CONSTRICT_BLOCK_SHORT) { constrictBlocksTop.Add(new ConstrictBlock(x, -ConstrictBlock.CONSTRICT_BLOCK_LONG, ConstrictBlockSideEnum.Top)); constrictBlocksBottom.Add(new ConstrictBlock(x, MainGame.SCREEN_HEIGHT - MainGame.WALL_SIZE, ConstrictBlockSideEnum.Bottom)); } } public void Update(GameTime gameTime) { int numMoving = 0; for (var i = 0; i < constrictBlocksLeft.Count; i++) { constrictBlocksLeft[i].Update(gameTime); constrictBlocksRight[i].Update(gameTime); if (constrictBlocksLeft[i].isMoving) { numMoving++; } if (constrictBlocksRight[i].isMoving) { numMoving++; } } for (var i = 0; i < constrictBlocksTop.Count; i++) { constrictBlocksTop[i].Update(gameTime); constrictBlocksBottom[i].Update(gameTime); if (constrictBlocksTop[i].isMoving) { numMoving++; } if (constrictBlocksBottom[i].isMoving) { numMoving++; } } if (numMoving < numToMove) { StartMoving(numToMove - numMoving); } } private void StartMoving(int numToStartMoving) { for (var i = 0; i < numToStartMoving; i++) { int which = MainGame.rand.Next(4); float speed = MainGame.rand.Next(minBlockSpeed, maxBlockSpeed); ConstrictBlock block; int index; switch (which) { case 0: index = MainGame.rand.Next(constrictBlocksLeft.Count - 1); block = constrictBlocksLeft[index]; break; case 1: index = MainGame.rand.Next(constrictBlocksRight.Count - 1); block = constrictBlocksRight[index]; break; case 2: index = MainGame.rand.Next(constrictBlocksTop.Count - 1); block = constrictBlocksTop[index]; break; default: index = MainGame.rand.Next(constrictBlocksBottom.Count - 1); block = constrictBlocksBottom[index]; break; } MoveBlock(block, speed); } } private void MoveBlock(ConstrictBlock block, float speed) { if (!block.isMoving) { block.isMoving = true; block.constrictSpeed = speed; } } public void Draw(SpriteBatch batch) { for (var i = 0; i < constrictBlocksLeft.Count; i++) { constrictBlocksLeft[i].Draw(batch); constrictBlocksRight[i].Draw(batch); } for (var i = 0; i < constrictBlocksTop.Count; i++) { constrictBlocksTop[i].Draw(batch); constrictBlocksBottom[i].Draw(batch); } } public bool DoesContactPlayer(Rectangle box) { for (var i = 0; i < constrictBlocksLeft.Count; i++) { if (box.Intersects(constrictBlocksLeft[i].boundedBox) || box.Intersects(constrictBlocksRight[i].boundedBox)) { return true; } } for (var i = 0; i < constrictBlocksTop.Count; i++) { if (box.Intersects(constrictBlocksTop[i].boundedBox) || box.Intersects(constrictBlocksBottom[i].boundedBox)) { return true; } } return false; } public void UpdateDifficulty(int curScore) { numToMove = BASE_NUM_TO_MOVE + curScore / 200; minBlockSpeed = BASE_MIN_BLOCK_SPEED + curScore / 250; maxBlockSpeed = BASE_MAX_BLOCK_SPEED + curScore / 150; } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Constrict/ConstrictionManager.cs
C#
gpl3
6,544
using System; using System.Collections.Generic; using Constriction.Constrict; using Constriction.GameState; using Constriction.Particle; using Constriction.Walls; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace Constriction { /// <summary> /// This is the main type for your game /// </summary> public class MainGame : Microsoft.Xna.Framework.Game { public const int SCREEN_WIDTH = 800; public const int SCREEN_HEIGHT = 600; public const int WALL_SIZE = 16; GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public static Texture2D emptyTex; public static SpriteFont hudFont; public static SpriteFont scoreFont; public static Random rand; Dictionary<GameStateEnum, IGameState> gameStates; GameStateEnum curState; public MainGame() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.PreferredBackBufferWidth = SCREEN_WIDTH; graphics.PreferredBackBufferHeight = SCREEN_HEIGHT; } protected override void Initialize() { rand = new Random(); gameStates = new Dictionary<GameStateEnum, IGameState>(); gameStates.Add(GameStateEnum.Title, new TitleState()); gameStates.Add(GameStateEnum.Help, new HelpState()); gameStates.Add(GameStateEnum.MainGame, new MainGameState()); gameStates.Add(GameStateEnum.GameOver, new GameOverState()); gameStates[GameStateEnum.Title].Initialize(this); gameStates[GameStateEnum.Help].Initialize(this); gameStates[GameStateEnum.MainGame].Initialize(this); gameStates[GameStateEnum.GameOver].Initialize(this); curState = GameStateEnum.Title; base.Initialize(); } protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); emptyTex = Content.Load<Texture2D>("Graphic/Empty"); hudFont = Content.Load<SpriteFont>("Font/HUDFont"); scoreFont = Content.Load<SpriteFont>("Font/ScoreEffectFont"); gameStates[GameStateEnum.Title].LoadContent(Content); gameStates[GameStateEnum.Help].LoadContent(Content); gameStates[GameStateEnum.MainGame].LoadContent(Content); gameStates[GameStateEnum.GameOver].LoadContent(Content); ((MainGameState)gameStates[GameStateEnum.MainGame]).LoadParticleContent(this, spriteBatch); } protected override void Update(GameTime gameTime) { // Allows the game to exit if (Keyboard.GetState().IsKeyDown(Keys.Escape) || GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { this.Exit(); } gameStates[curState].HandleInput(Keyboard.GetState()); gameStates[curState].Update(gameTime); var nextState = gameStates[curState].GetNextState(); if (nextState.HasValue) { gameStates[nextState.Value].Reset(); curState = nextState.Value; } base.Update(gameTime); } protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.White); spriteBatch.Begin(); gameStates[curState].Draw(spriteBatch); spriteBatch.End(); base.Draw(gameTime); } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/MainGame.cs
C#
gpl3
3,800
using System; using Constriction.Constrict; using DPSF; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Particle { /// <summary> /// Create a new Particle System class that inherits from a Default DPSF Particle System. /// </summary> [Serializable] class FogParticleSystem : DefaultSpriteParticleSystem { /// <summary> /// Constructor /// </summary> /// <param name="cGame">Handle to the Game object being used. Pass in null for this /// parameter if not using a Game object.</param> public FogParticleSystem(Game cGame) : base(cGame) { } /// <summary> /// Function to Initialize the Particle System with default values. /// Particle system properties should not be set until after this is called, as /// they are likely to be reset to their default values. /// </summary> /// <param name="cGraphicsDevice">The Graphics Device the Particle System should use</param> /// <param name="cContentManager">The Content Manager the Particle System should use to load resources</param> /// <param name="cSpriteBatch">The Sprite Batch that the Sprite Particle System should use to draw its particles. /// If this is not initializing a Sprite particle system, or you want the particle system to use its own Sprite Batch, /// pass in null.</param> public void Initialize(GraphicsDevice cGraphicsDevice, ContentManager cContentManager, SpriteBatch cSpriteBatch, ConstrictionManager blockManager) { base.AutoInitialize(cGraphicsDevice, cContentManager, cSpriteBatch); base.InitializeSpriteParticleSystem(cGraphicsDevice, cContentManager, 1000, 50000, "Particle/FogParticle", cSpriteBatch); Name = "Fog Particle System"; // Finish loading the Particle System in a separate function call, so if // we want to reset the Particle System later we don't need to completely // re-initialize it, we can just call this function to reset it. LoadParticleSystem(); InitializeEmitters(blockManager); } public void Reset() { this.RemoveAllParticles(); } /// <summary> /// Load the Particle System Events and any other settings /// </summary> public void LoadParticleSystem() { ParticleInitializationFunction = InitializeParticleUsingInitialProperties; // Setup the Initial Properties of the Particles. // These are only applied if using InitializeParticleUsingInitialProperties // as the Particle Initialization Function. InitialProperties.LifetimeMin = 1.0f; InitialProperties.LifetimeMax = 1.5f; InitialProperties.PositionMin = Vector3.Zero; InitialProperties.PositionMax = Vector3.Zero; InitialProperties.VelocityMin = new Vector3(10, 10, 0); InitialProperties.VelocityMax = new Vector3(-10, -10, 0); InitialProperties.StartSizeMin = 8; InitialProperties.StartSizeMax = 32; InitialProperties.StartColorMin = Color.Black; InitialProperties.StartColorMax = Color.Black; InitialProperties.EndColorMin = Color.Black; InitialProperties.EndColorMax = Color.Black; // Remove all Events first so that none are added twice if this function is called again ParticleEvents.RemoveAllEvents(); ParticleSystemEvents.RemoveAllEvents(); // Allow the Particle's Position, Rotation, Width and Height, Color, and Transparency to be updated each frame ParticleEvents.AddEveryTimeEvent(UpdateParticlePositionUsingVelocity); ParticleEvents.AddEveryTimeEvent(UpdateParticleTransparencyToFadeOutUsingLerp); } private void InitializeEmitters(ConstrictionManager blockManager) { foreach (var block in blockManager.constrictBlocksLeft) { var emitter = new ParticleEmitter(); emitter.ParticlesPerSecond = 100; emitter.PositionData.Position = new Vector3(block.boundedBox.Right, block.boundedBox.Center.Y, 0); this.Emitters.Add(emitter); } foreach (var block in blockManager.constrictBlocksRight) { var emitter = new ParticleEmitter(); emitter.ParticlesPerSecond = 100; emitter.PositionData.Position = new Vector3(block.boundedBox.Left, block.boundedBox.Center.Y, 0); this.Emitters.Add(emitter); } foreach (var block in blockManager.constrictBlocksTop) { var emitter = new ParticleEmitter(); emitter.ParticlesPerSecond = 100; emitter.PositionData.Position = new Vector3(block.boundedBox.Center.X, block.boundedBox.Bottom, 0); this.Emitters.Add(emitter); } foreach (var block in blockManager.constrictBlocksBottom) { var emitter = new ParticleEmitter(); emitter.ParticlesPerSecond = 100; emitter.PositionData.Position = new Vector3(block.boundedBox.Center.X, block.boundedBox.Top, 0); this.Emitters.Add(emitter); } } public void Update(GameTime time, ConstrictionManager blockManager) { UpdateEmitters(blockManager); base.Update((float)time.ElapsedGameTime.TotalSeconds); } private void UpdateEmitters(ConstrictionManager blockManager) { var index = 0; foreach (var block in blockManager.constrictBlocksLeft) { var emitter = this.Emitters[index]; emitter.Enabled = block.isMoving; emitter.PositionData.Position = new Vector3(block.boundedBox.Right, block.boundedBox.Center.Y, 0); index++; } foreach (var block in blockManager.constrictBlocksRight) { var emitter = this.Emitters[index]; emitter.Enabled = block.isMoving; emitter.PositionData.Position = new Vector3(block.boundedBox.Left, block.boundedBox.Center.Y, 0); index++; } foreach (var block in blockManager.constrictBlocksTop) { var emitter = this.Emitters[index]; emitter.Enabled = block.isMoving; emitter.PositionData.Position = new Vector3(block.boundedBox.Center.X, block.boundedBox.Bottom, 0); index++; } foreach (var block in blockManager.constrictBlocksBottom) { var emitter = this.Emitters[index]; emitter.Enabled = block.isMoving; emitter.PositionData.Position = new Vector3(block.boundedBox.Center.X, block.boundedBox.Top, 0); index++; } } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Particle/FogParticleSystem.cs
C#
gpl3
7,001
using System; using DPSF; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Content; namespace Constriction.Particle { [Serializable] public class CanisterParticleSystem : DefaultSpriteParticleSystem { public const int PICKUP_NUM_PARTICLES = 30; private Color canisterStartColor = new Color(0, 255, 228); private Color canisterEndColor = new Color(0, 255, 228, 0); public CanisterParticleSystem(Game cGame) : base(cGame) { } public void Initialize(GraphicsDevice cGraphicsDevice, ContentManager cContentManager, SpriteBatch cSpriteBatch) { base.AutoInitialize(cGraphicsDevice, cContentManager, cSpriteBatch); base.InitializeSpriteParticleSystem(cGraphicsDevice, cContentManager, 30, 30, "Particle/CanisterPickupParticle", cSpriteBatch); Name = "Canister Particle System"; // Finish loading the Particle System in a separate function call, so if // we want to reset the Particle System later we don't need to completely // re-initialize it, we can just call this function to reset it. LoadParticleSystem(); } public void Reset() { this.RemoveAllParticles(); } public void LoadParticleSystem() { ParticleInitializationFunction = InitializeParticleUsingInitialProperties; InitialProperties.LifetimeMin = 0.1f; InitialProperties.LifetimeMax = 0.4f; InitialProperties.PositionMin = Vector3.Zero; InitialProperties.PositionMax = Vector3.Zero; InitialProperties.VelocityMin = new Vector3(100, 100, 0); InitialProperties.VelocityMax = new Vector3(-100, -100, 0); InitialProperties.StartSizeMin = 4; InitialProperties.StartSizeMax = 8; InitialProperties.StartColorMin = canisterStartColor; InitialProperties.StartColorMax = canisterStartColor; InitialProperties.EndColorMin = canisterEndColor; InitialProperties.EndColorMax = canisterEndColor; ParticleEvents.RemoveAllEvents(); ParticleSystemEvents.RemoveAllEvents(); ParticleEvents.AddEveryTimeEvent(UpdateParticlePositionUsingVelocity); ParticleEvents.AddEveryTimeEvent(UpdateParticleTransparencyToFadeOutUsingLerp); Emitter.EmitParticlesAutomatically = false; Emitter.Enabled = true; } public void Explode(Point location) { Emitter.PositionData.Position = new Vector3(location.X, location.Y, 0); this.AddParticles(PICKUP_NUM_PARTICLES); } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Particle/CanisterParticleSystem.cs
C#
gpl3
2,817
using System; using DPSF; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Particle { [Serializable] public class DamageParticleSystem : DefaultSpriteParticleSystem { public const int DAMAGE_NUM_PARTICLES = 100; public DamageParticleSystem(Game cGame) : base(cGame) { } public void Initialize(GraphicsDevice cGraphicsDevice, ContentManager cContentManager, SpriteBatch cSpriteBatch) { base.AutoInitialize(cGraphicsDevice, cContentManager, cSpriteBatch); base.InitializeSpriteParticleSystem(cGraphicsDevice, cContentManager, 100, 100, "Graphic/Empty", cSpriteBatch); Name = "Damage Particle System"; LoadParticleSystem(); } public void Reset() { this.RemoveAllParticles(); } public void LoadParticleSystem() { ParticleInitializationFunction = InitializeParticleUsingInitialProperties; InitialProperties.LifetimeMin = 0.1f; InitialProperties.LifetimeMax = 0.4f; InitialProperties.PositionMin = Vector3.Zero; InitialProperties.PositionMax = Vector3.Zero; InitialProperties.VelocityMin = new Vector3(250, 250, 0); InitialProperties.VelocityMax = new Vector3(-250, -250, 0); InitialProperties.StartSizeMin = 1; InitialProperties.StartSizeMax = 3; InitialProperties.EndSizeMin = 1; InitialProperties.EndSizeMax = 3; InitialProperties.StartColorMin = Color.Yellow; InitialProperties.StartColorMax = Color.Red; InitialProperties.EndColorMin = Color.White; InitialProperties.EndColorMax = Color.White; ParticleEvents.RemoveAllEvents(); ParticleSystemEvents.RemoveAllEvents(); ParticleEvents.AddEveryTimeEvent(UpdateParticlePositionUsingVelocity); ParticleEvents.AddEveryTimeEvent(UpdateParticleTransparencyToFadeOutUsingLerp); Emitter.EmitParticlesAutomatically = false; Emitter.Enabled = true; } public void Explode(Point location) { Emitter.PositionData.Position = new Vector3(location.X, location.Y, 0); this.AddParticles(DAMAGE_NUM_PARTICLES); } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Particle/DamageParticleSystem.cs
C#
gpl3
2,474
using System; using DPSF; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Particle { [Serializable] public class DeathParticleSystem : DefaultSpriteParticleSystem { public const int DEATH_NUM_PARTICLES = 100; public DeathParticleSystem(Game cGame) : base(cGame) { } public void Initialize(GraphicsDevice cGraphicsDevice, ContentManager cContentManager, SpriteBatch cSpriteBatch) { base.AutoInitialize(cGraphicsDevice, cContentManager, cSpriteBatch); base.InitializeSpriteParticleSystem(cGraphicsDevice, cContentManager, 1000, 50000, "Graphic/Empty", cSpriteBatch); Name = "Death Particle System"; LoadParticleSystem(); } public void Reset() { this.RemoveAllParticles(); } public void LoadParticleSystem() { ParticleInitializationFunction = InitializeParticleUsingInitialProperties; InitialProperties.LifetimeMin = 0.5f; InitialProperties.LifetimeMax = 1.0f; InitialProperties.PositionMin = Vector3.Zero; InitialProperties.PositionMax = Vector3.Zero; InitialProperties.VelocityMin = new Vector3(150, 150, 0); InitialProperties.VelocityMax = new Vector3(-150, -150, 0); InitialProperties.StartSizeMin = 2; InitialProperties.StartSizeMax = 4; InitialProperties.EndSizeMin = 2; InitialProperties.EndSizeMax = 4; InitialProperties.StartColorMin = Color.Red; InitialProperties.StartColorMax = Color.Yellow; InitialProperties.EndColorMin = Color.Gray; InitialProperties.EndColorMax = Color.Gray; ParticleEvents.RemoveAllEvents(); ParticleSystemEvents.RemoveAllEvents(); ParticleEvents.AddEveryTimeEvent(UpdateParticlePositionUsingVelocity); ParticleEvents.AddEveryTimeEvent(UpdateParticleTransparencyToFadeOutUsingLerp); Emitter.EmitParticlesAutomatically = true; Emitter.ParticlesPerSecond = DEATH_NUM_PARTICLES; Emitter.Enabled = true; } public void Explode(Point location) { Emitter.PositionData.Position = new Vector3(location.X, location.Y, 0); this.AddParticles(DEATH_NUM_PARTICLES); } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Particle/DeathParticleSystem.cs
C#
gpl3
2,532
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction.ScoreEffect { public class ScoreEffect { public const float EFFECT_TIMER = 1; public const float MOVE_SPEED = 50; private Vector2 position; public float effectTimer; private int displayNumber; public ScoreEffect(float x, float y, int displayNumber) { position = new Vector2(x - 12, y - 14); effectTimer = EFFECT_TIMER; this.displayNumber = displayNumber; } public void Update(GameTime time) { if (effectTimer > 0) { effectTimer -= (float)time.ElapsedGameTime.TotalSeconds; position.Y -= MOVE_SPEED * (float)time.ElapsedGameTime.TotalSeconds; } } public void Draw(SpriteBatch batch) { if (effectTimer > 0) { batch.DrawString(MainGame.scoreFont, displayNumber.ToString(), position, Color.White); } } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/ScoreEffect/ScoreEffect.cs
C#
gpl3
1,127
using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; using Microsoft.Xna.Framework; namespace Constriction.ScoreEffect { public class ScoreEffectManager { private List<ScoreEffect> scoreEffects; public ScoreEffectManager() { scoreEffects = new List<ScoreEffect>(); } public void Reset() { scoreEffects.Clear(); } public void AddScoreEffect(Point startPosition, float displayNumber) { scoreEffects.Add(new ScoreEffect(startPosition.X, startPosition.Y, (int)displayNumber)); } public void Update(GameTime time) { var removeScoreEffects = new List<ScoreEffect>(); foreach (var scoreEffect in scoreEffects) { scoreEffect.Update(time); if (scoreEffect.effectTimer <= 0) { removeScoreEffects.Add(scoreEffect); } } foreach (var removeScoreEffect in removeScoreEffects) { scoreEffects.Remove(removeScoreEffect); } } public void Draw(SpriteBatch batch) { foreach (var scoreEffect in scoreEffects) { scoreEffect.Draw(batch); } } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/ScoreEffect/ScoreEffectManager.cs
C#
gpl3
1,422
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Canister { public class Canister { public const int WIDTH = 16; public const int HEIGHT = 16; public static Color fillColor = new Color(0, 255, 228); public static Vector2 fillOffset = new Vector2(1, 6); public const int FILL_WIDTH = 14; public const int FILL_HEIGHT = 7; public const float FILLED_AMOUNT = 100; public const float DRAIN_RATE = 10; public Rectangle boundedBox; public float fillAmount; public Canister(int x, int y) { boundedBox = new Rectangle(x, y, WIDTH, HEIGHT); fillAmount = FILLED_AMOUNT; } public void Update(GameTime time) { if (fillAmount > 0) { fillAmount -= DRAIN_RATE * (float)time.ElapsedGameTime.TotalSeconds; if (fillAmount < 0) { fillAmount = 0; } } } public void Draw(SpriteBatch batch) { float fillHeight = FILL_HEIGHT * fillAmount / FILLED_AMOUNT; float fillWidth = FILL_WIDTH; float fillX = boundedBox.X + fillOffset.X; float fillY = boundedBox.Y + fillOffset.Y + (FILL_HEIGHT - fillHeight); batch.Draw(MainGame.emptyTex, new Rectangle((int)(boundedBox.X + fillOffset.X), (int)(boundedBox.Y + fillOffset.Y), (int)FILL_WIDTH, (int)FILL_HEIGHT), Color.Black); batch.Draw(MainGame.emptyTex, new Rectangle((int)fillX, (int)fillY, (int)fillWidth, (int)fillHeight), fillColor); batch.Draw(CanisterManager.tex, boundedBox, Color.White); } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Canister/Canister.cs
C#
gpl3
1,827
using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace Constriction.Canister { public class CanisterManager { public const int MAX_NUM_CANISTERS = 5; public const float MIN_DISTANCE = 70; public const float CANISTER_SPAWN_TIMER = 1.5f; public const int MIN_X = 128; public const int MAX_X = MainGame.SCREEN_WIDTH - MainGame.WALL_SIZE - Canister.WIDTH - 128; public const int MIN_Y = 128; public const int MAX_Y = MainGame.SCREEN_HEIGHT - MainGame.WALL_SIZE - Canister.HEIGHT - 128; public static Texture2D tex; public List<Canister> canisters; private float canisterSpawnTimer; public CanisterManager() { canisters = new List<Canister>(); } public void Reset() { canisters.Clear(); canisterSpawnTimer = 0; } public Canister DoesCollide(Rectangle playerBox) { foreach (var canister in canisters) { if (playerBox.Intersects(canister.boundedBox)) { canisters.Remove(canister); return canister; } } return null; } public void Update(GameTime time) { var removeCanisters = new List<Canister>(); UpdateTimers(time); foreach (var canister in canisters) { canister.Update(time); if (canister.fillAmount <= 0) { removeCanisters.Add(canister); } } foreach (var removeCanister in removeCanisters) { canisters.Remove(removeCanister); } } private void UpdateTimers(GameTime time) { canisterSpawnTimer -= (float)time.ElapsedGameTime.TotalSeconds; if (canisterSpawnTimer < 0) { if (canisters.Count < MAX_NUM_CANISTERS) { SpawnCanister(); } canisterSpawnTimer = CANISTER_SPAWN_TIMER; } } private void SpawnCanister() { var position = new Vector2(MainGame.rand.Next(MIN_X, MAX_X), MainGame.rand.Next(MIN_Y, MAX_Y)); if (IsTooClose(position)) { position = new Vector2(MainGame.rand.Next(MIN_X, MAX_X), MainGame.rand.Next(MIN_Y, MAX_Y)); // Try Again. Only try twice so we don't get stuck here forever, at the mercy of the random number generator if (IsTooClose(position)) { return; } } canisters.Add(new Canister((int)position.X, (int)position.Y)); } private bool IsTooClose(Vector2 position) { bool tooClose = false; foreach (var canister in canisters) { if (Vector2.Distance(position, new Vector2(canister.boundedBox.X, canister.boundedBox.Y)) < MIN_DISTANCE) { tooClose = true; } } return tooClose; } public void Draw(SpriteBatch batch) { foreach (var canister in canisters) { canister.Draw(batch); } } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Canister/CanisterManager.cs
C#
gpl3
3,645
using Constriction.Particle; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Player { public class DyingPlayer { public const int SPRITE_WIDTH = 32; public const int SPRITE_HEIGHT = 32; public const float DYING_TIMER = 5f; public Texture2D tex; private Rectangle boundedBox; private DeathParticleSystem deathParticleSystem; public bool isDead; private float dyingTimer; private float rotation; public DyingPlayer() { boundedBox = new Rectangle(0, 0, SPRITE_WIDTH, SPRITE_HEIGHT); isDead = false; dyingTimer = 0; } public void Initialize(MainGame game, SpriteBatch spriteBatch) { deathParticleSystem = new DeathParticleSystem(game); deathParticleSystem.Initialize(game.GraphicsDevice, game.Content, spriteBatch); } public void Activate(Point newLocation, float rotation) { dyingTimer = DYING_TIMER; boundedBox.Location = newLocation; this.rotation = rotation; deathParticleSystem.Emitter.PositionData.Position = new Vector3(newLocation.X, newLocation.Y, 0); deathParticleSystem.Emitter.Enabled = true; } public void Reset() { isDead = false; dyingTimer = 0; deathParticleSystem.Reset(); } public void Update(GameTime time) { if (!isDead) { var elapsedTime = (float)time.ElapsedGameTime.TotalSeconds; deathParticleSystem.Update(elapsedTime); dyingTimer -= elapsedTime; if (dyingTimer <= 0) { isDead = true; } } } public void Draw(SpriteBatch batch) { batch.Draw(tex, boundedBox, null, Color.White, rotation, new Vector2(SPRITE_WIDTH / 2, SPRITE_HEIGHT / 2), SpriteEffects.None, 0); deathParticleSystem.Draw(); } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Player/DyingPlayer.cs
C#
gpl3
2,210
using System; using Constriction.Walls; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Player { public class AlivePlayer { public const int SPRITE_WIDTH = 32; public const int SPRITE_HEIGHT = 32; public const int PLAYER_WIDTH = 16; public const int PLAYER_HEIGHT = 16; public const int PLAYER_RUN_SPEED = 300; public const int PLAYER_JOG_SPEED = 170; public const int PLAYER_WALK_SPEED = 100; public const float INVULN_TIMER = 1.5f; public Rectangle boundedBox; public Texture2D tex; public WallManager wallManager; public bool upPressed, downPressed; public bool leftPressed, rightPressed; public bool runPressed, walkPressed; private Vector2 position; private Vector2 velocity; public float rotation; public bool canBeHurt; private float invulnTimer; public AlivePlayer() { Reset(); } public void Reset() { position = new Vector2(400, 300); boundedBox = new Rectangle((int)position.X, (int)position.Y, PLAYER_WIDTH, PLAYER_HEIGHT); canBeHurt = true; invulnTimer = 0; } public void Hurt() { canBeHurt = false; invulnTimer = INVULN_TIMER; } public void Update(GameTime time) { UpdateInvulnerability(time); HandleInput(time); UpdatePosition(); UpdateBox(); } private void UpdateInvulnerability(GameTime time) { if (invulnTimer > 0) { invulnTimer -= (float)time.ElapsedGameTime.TotalSeconds; if (invulnTimer < 0) { invulnTimer = 0; canBeHurt = true; } } } private void HandleInput(GameTime time) { velocity = Vector2.Zero; int speed; if (runPressed) { speed = PLAYER_RUN_SPEED; } else if (walkPressed) { speed = PLAYER_WALK_SPEED; } else { speed = PLAYER_JOG_SPEED; } if (upPressed) { velocity.Y -= speed; } if (downPressed) { velocity.Y += speed; } if (leftPressed) { velocity.X -= speed; } if (rightPressed) { velocity.X += speed; } if (velocity != Vector2.Zero) { rotation = (float)Math.Atan2(velocity.Y, velocity.X); velocity.Normalize(); velocity *= speed * (float)time.ElapsedGameTime.TotalSeconds; } } private void UpdatePosition() { position.X += velocity.X; UpdateBox(); var solidObstacle = wallManager.IsSpaceFree(this.boundedBox); if (solidObstacle.HasValue) { if (velocity.X > 0)//Right { position.X = solidObstacle.Value.Left - PLAYER_WIDTH; } else if (velocity.X < 0)//Left { position.X = solidObstacle.Value.Right; } } position.Y += velocity.Y; UpdateBox(); solidObstacle = wallManager.IsSpaceFree(this.boundedBox); if (solidObstacle.HasValue) { if (velocity.Y > 0)//Down { position.Y = solidObstacle.Value.Top - PLAYER_HEIGHT; } else if (velocity.Y < 0)//Up { position.Y = solidObstacle.Value.Bottom; } } UpdateBox(); } private void UpdateBox() { boundedBox.Location = new Point((int)position.X, (int)position.Y); } public void Draw(SpriteBatch batch) { float xPos = position.X + SPRITE_WIDTH / 2 - PLAYER_WIDTH / 2; float yPos = position.Y + SPRITE_HEIGHT / 2 - PLAYER_HEIGHT / 2; float alpha = 1 - (invulnTimer / INVULN_TIMER * 0.8f); var color = Color.White * alpha; batch.Draw(tex, new Vector2(xPos, yPos), null, color, rotation, new Vector2(SPRITE_WIDTH / 2, SPRITE_HEIGHT / 2), 1, SpriteEffects.None, 0); } public Point GetLocation() { float xPos = position.X + SPRITE_WIDTH / 2 - PLAYER_WIDTH / 2; float yPos = position.Y + SPRITE_HEIGHT / 2 - PLAYER_HEIGHT / 2; return new Point((int)xPos, (int)yPos); } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Player/AlivePlayer.cs
C#
gpl3
5,197
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Smoke Rush")] [assembly: AssemblyProduct("Constriction")] [assembly: AssemblyDescription("")] [assembly: AssemblyCompany("Hewlett-Packard Company")] [assembly: AssemblyCopyright("Copyright © Hewlett-Packard Company 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. Only Windows // assemblies support COM. [assembly: ComVisible(false)] // On Windows, the following GUID is for the ID of the typelib if this // project is exposed to COM. On other platforms, it unique identifies the // title storage container when deploying this assembly to the device. [assembly: Guid("689a6417-13c2-4d19-9740-209ed5f83db1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")]
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Properties/AssemblyInfo.cs
C#
gpl3
1,408
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction { public class HUD { public const int PLAYER_HEALTH_MAX = 100; public const int PLAYER_DAMAGE_DECREMENT = 10; private Vector2 position; public int curScore; public int playerHealth; public HUD() { position = new Vector2(16, 0); Reset(); } public void Reset() { curScore = 0; playerHealth = PLAYER_HEALTH_MAX; } public void HurtPlayerHealth() { playerHealth -= PLAYER_DAMAGE_DECREMENT; } public void Draw(SpriteBatch batch) { batch.DrawString(MainGame.hudFont, string.Format("Score: {0}", curScore), position, Color.White); batch.Draw(MainGame.emptyTex, new Rectangle(100, 4, PLAYER_HEALTH_MAX, 8), Color.Red); batch.Draw(MainGame.emptyTex, new Rectangle(100, 4, playerHealth, 8), Color.GreenYellow); } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/HUD.cs
C#
gpl3
1,098
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Audio; using Constriction.Particle; using Constriction.Walls; using Constriction.Constrict; using Constriction.Player; using Constriction.Canister; using Constriction.ScoreEffect; namespace Constriction.GameState { public class MainGameState : IGameState { private Texture2D texFloor, texSmoke; private SoundEffect sndGoalPickup; private SoundEffect sndPlayerHurt; private SoundEffectInstance sndPlayerDying; private FogParticleSystem fogParticleSystem; private DamageParticleSystem damageParticleSystem; private CanisterParticleSystem canisterParticleSystem; private ScoreEffectManager scoreEffectManager; private WallManager wallManager; private ConstrictionManager constrictionManager; private CanisterManager canisterManager; private HUD hud; private AlivePlayer player; private DyingPlayer dyingPlayer; private bool playerIsDying; private bool playerIsDead; public void Initialize(Game game) { player = new AlivePlayer(); dyingPlayer = new DyingPlayer(); wallManager = new WallManager(); constrictionManager = new ConstrictionManager(); canisterManager = new CanisterManager(); scoreEffectManager = new ScoreEffectManager(); player.wallManager = wallManager; hud = new HUD(); fogParticleSystem = new FogParticleSystem(game); damageParticleSystem = new DamageParticleSystem(game); canisterParticleSystem = new CanisterParticleSystem(game); playerIsDying = false; playerIsDead = false; } public void LoadContent(ContentManager content) { texFloor = content.Load<Texture2D>("Graphic/Screen/MainGameScreenFloor"); texSmoke = content.Load<Texture2D>("Graphic/Screen/MainGameScreenSmoke"); player.tex = content.Load<Texture2D>("Graphic/Player"); dyingPlayer.tex = content.Load<Texture2D>("Graphic/DeadPlayer"); CanisterManager.tex = content.Load<Texture2D>("Graphic/Goal"); sndGoalPickup = content.Load<SoundEffect>("Sound/GoalPickup"); sndPlayerHurt = content.Load<SoundEffect>("Sound/PlayerHurt"); sndPlayerDying = content.Load<SoundEffect>("Sound/PlayerDying").CreateInstance(); sndPlayerDying.IsLooped = true; } public void LoadParticleContent(MainGame game, SpriteBatch spriteBatch) { fogParticleSystem.Initialize(game.GraphicsDevice, game.Content, spriteBatch, constrictionManager); damageParticleSystem.Initialize(game.GraphicsDevice, game.Content, spriteBatch); canisterParticleSystem.Initialize(game.GraphicsDevice, game.Content, spriteBatch); dyingPlayer.Initialize(game, spriteBatch); } public void HandleInput(KeyboardState state) { player.upPressed = state.IsKeyDown(Keys.Up); player.downPressed = state.IsKeyDown(Keys.Down); player.leftPressed = state.IsKeyDown(Keys.Left); player.rightPressed = state.IsKeyDown(Keys.Right); player.runPressed = state.IsKeyDown(Keys.LeftShift); player.walkPressed = state.IsKeyDown(Keys.LeftControl); } public void Update(GameTime time) { if (playerIsDying) { dyingPlayer.Update(time); if (dyingPlayer.isDead) { playerIsDead = true; sndPlayerDying.Stop(); } } else { player.Update(time); } canisterManager.Update(time); scoreEffectManager.Update(time); constrictionManager.Update(time); UpdateParticles(time); //Collisions if (player.canBeHurt) { var canister = canisterManager.DoesCollide(player.boundedBox); if (canister != null) { sndGoalPickup.Play(0.5f, 0.0f, 0.0f); canisterParticleSystem.Explode(canister.boundedBox.Center); hud.curScore += (int)canister.fillAmount; constrictionManager.UpdateDifficulty(hud.curScore); scoreEffectManager.AddScoreEffect(canister.boundedBox.Center, canister.fillAmount); } } if (player.canBeHurt && constrictionManager.DoesContactPlayer(player.boundedBox)) { sndPlayerHurt.Play(0.5f, 0.0f, 0.0f); player.Hurt(); hud.HurtPlayerHealth(); if (hud.playerHealth > 0) { damageParticleSystem.Explode(player.boundedBox.Center); } } //Check end state if (hud.playerHealth <= 0 && !playerIsDying) { KillPlayer(); } } private void UpdateParticles(GameTime time) { fogParticleSystem.Update(time, constrictionManager); damageParticleSystem.Update((float)time.ElapsedGameTime.TotalSeconds); canisterParticleSystem.Update((float)time.ElapsedGameTime.TotalSeconds); } private void KillPlayer() { playerIsDying = true; dyingPlayer.Activate(player.GetLocation(), player.rotation); sndPlayerDying.Play(); } public void Draw(SpriteBatch batch) { batch.Draw(texFloor, Vector2.Zero, Color.White); //constrictionManager.Draw(batch); if (playerIsDying) { dyingPlayer.Draw(batch); } else { player.Draw(batch); } wallManager.Draw(batch); fogParticleSystem.Draw(); canisterParticleSystem.Draw(); damageParticleSystem.Draw(); canisterManager.Draw(batch); batch.Draw(texSmoke, Vector2.Zero, Color.White); scoreEffectManager.Draw(batch); hud.Draw(batch); } public void Reset() { fogParticleSystem.Reset(); damageParticleSystem.Reset(); canisterParticleSystem.Reset(); constrictionManager.Reset(); scoreEffectManager.Reset(); player.Reset(); dyingPlayer.Reset(); canisterManager.Reset(); hud.Reset(); playerIsDying = false; playerIsDead = false; } public GameStateEnum? GetNextState() { GameStateEnum? nextState = null; if (playerIsDead) { nextState = GameStateEnum.GameOver; } return nextState; } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/GameState/MainGameState.cs
C#
gpl3
7,466
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace Constriction.GameState { public class GameOverState : IGameState { private Texture2D texGameOverScreen; private bool keysPressed; private bool goToNextState; public void Initialize(Game game) { Reset(); } public void LoadContent(ContentManager content) { texGameOverScreen = content.Load<Texture2D>("Graphic/Screen/GameOverScreen"); } public void HandleInput(KeyboardState state) { var keysDown = state.GetPressedKeys().Length; if (keysDown > 0 && !keysPressed) { goToNextState = true; } else if (keysDown == 0) { keysPressed = false; } } public void Update(GameTime time) { //TODO Something cool and animation-y } public void Draw(SpriteBatch batch) { batch.Draw(texGameOverScreen, Vector2.Zero, Color.White); } public void Reset() { keysPressed = true; goToNextState = false; } public GameStateEnum? GetNextState() { GameStateEnum? nextState = null; if (goToNextState) { nextState = GameStateEnum.Title; } return nextState; } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/GameState/GameOverState.cs
C#
gpl3
1,654
namespace Constriction.GameState { public enum GameStateEnum { Title = 0, Help = 1, MainGame = 2, GameOver = 3 } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/GameState/GameStateEnum.cs
C#
gpl3
172
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace Constriction.GameState { public class TitleState : IGameState { private Texture2D texTitleScreen; private bool acceptingKeyPresses; private bool keysPressed; private bool goToNextState; public void Initialize(Game game) { Reset(); } public void LoadContent(ContentManager content) { texTitleScreen = content.Load<Texture2D>("Graphic/Screen/TitleScreen"); } public void HandleInput(KeyboardState state) { var keysDown = state.GetPressedKeys().Length; if (keysDown > 0 && !keysPressed && acceptingKeyPresses) { goToNextState = true; } else if (keysDown == 0) { keysPressed = false; } } public void Update(GameTime time) { //TODO Something cool and animation-y } public void Draw(SpriteBatch batch) { batch.Draw(texTitleScreen, Vector2.Zero, Color.White); } public void Reset() { keysPressed = true; goToNextState = false; acceptingKeyPresses = true; } public GameStateEnum? GetNextState() { GameStateEnum? nextState = null; if (goToNextState) { nextState = GameStateEnum.Help; } return nextState; } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/GameState/TitleState.cs
C#
gpl3
1,743
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Graphics; namespace Constriction.GameState { public interface IGameState { void Initialize(Game game); void LoadContent(ContentManager content); void HandleInput(KeyboardState state); void Update(GameTime time); void Draw(SpriteBatch batch); void Reset(); GameStateEnum? GetNextState(); } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/GameState/IGameState.cs
C#
gpl3
530
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace Constriction.GameState { public class HelpState : IGameState { private Texture2D texHelpScreen; private bool keysPressed; private bool goToNextState; public void Initialize(Game game) { Reset(); } public void LoadContent(ContentManager content) { texHelpScreen = content.Load<Texture2D>("Graphic/Screen/HelpScreen"); } public void HandleInput(KeyboardState state) { var keysDown = state.GetPressedKeys().Length; if (keysDown > 0 && !keysPressed) { goToNextState = true; } else if (keysDown == 0) { keysPressed = false; } } public void Update(GameTime time) { //TODO Something cool and animation-y } public void Draw(SpriteBatch batch) { batch.Draw(texHelpScreen, Vector2.Zero, Color.White); } public void Reset() { keysPressed = true; goToNextState = false; } public GameStateEnum? GetNextState() { GameStateEnum? nextState = null; if (goToNextState) { nextState = GameStateEnum.MainGame; } return nextState; } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/GameState/HelpState.cs
C#
gpl3
1,637
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Walls { public class Wall { public Rectangle boundedBox; public Texture2D tex; public Wall(int x, int y, int width, int height) { boundedBox = new Rectangle(x, y, width, height); } public void Draw(SpriteBatch batch) { batch.Draw(MainGame.emptyTex, boundedBox, Color.Black); } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Walls/Wall.cs
C#
gpl3
502
using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Constriction.Walls { public class WallManager { public List<Wall> walls; public WallManager() { walls = new List<Wall>(); walls.Add(new Wall(0, 0, MainGame.SCREEN_WIDTH, MainGame.WALL_SIZE));//Top walls.Add(new Wall(0, MainGame.SCREEN_HEIGHT - MainGame.WALL_SIZE, MainGame.SCREEN_WIDTH, MainGame.WALL_SIZE));//Bottom walls.Add(new Wall(0, 0, MainGame.WALL_SIZE, MainGame.SCREEN_HEIGHT));//Left walls.Add(new Wall(MainGame.SCREEN_WIDTH - MainGame.WALL_SIZE, 0, MainGame.WALL_SIZE, MainGame.SCREEN_HEIGHT));//Right } public Rectangle? IsSpaceFree(Rectangle box) { foreach (var wall in walls) { if (box.Intersects(wall.boundedBox)) { return wall.boundedBox; } } return null; } public void Draw(SpriteBatch batch) { foreach (var wall in walls) { wall.Draw(batch); } } } }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Walls/WallManager.cs
C#
gpl3
1,254
using System; namespace Constriction { #if WINDOWS || XBOX static class Program { /// <summary> /// The main entry point for the application. /// </summary> static void Main(string[] args) { using (MainGame game = new MainGame()) { game.Run(); } } } #endif }
02-february-1gam-smoke-rush
trunk/Constriction/Constriction/Program.cs
C#
gpl3
394
using System; using System.Drawing; using System.Drawing.Printing; using System.Collections; using System.Windows.Forms; namespace ClaseTicket { public class Ticket2 { ArrayList headerLines = new ArrayList(); ArrayList subHeaderLines = new ArrayList(); ArrayList items = new ArrayList(); ArrayList totales = new ArrayList(); ArrayList footerLines = new ArrayList(); private Image headerImage = null; int count = 0; int maxChar = 35; int maxCharDescription = 20; int imageHeight = 0; float leftMargin = 0; float topMargin = 3; string fontName = "Lucida Console"; int fontSize = 9; Font printFont = null; SolidBrush myBrush = new SolidBrush(Color.Black); Graphics gfx = null; string line = null; public Ticket2() { } public Image HeaderImage { get { return headerImage; } set { if (headerImage != value) headerImage = value; } } public int MaxChar { get { return maxChar; } set { if (value != maxChar) maxChar = value; } } public int MaxCharDescription { get { return maxCharDescription; } set { if (value != maxCharDescription) maxCharDescription = value; } } public int FontSize { get { return fontSize; } set { if (value != fontSize) fontSize = value; } } public string FontName { get { return fontName; } set { if (value != fontName) fontName = value; } } public void AddHeaderLine(string line) { headerLines.Add(line); } public void AddSubHeaderLine(string line) { subHeaderLines.Add(line); } public void AddItem(string cantidad, string item, string price) { OrderItem newItem = new OrderItem('?'); items.Add(newItem.GenerateItem(cantidad, item, price)); } public void AddTotal(string name, string price) { OrderTotal newTotal = new OrderTotal('?'); totales.Add(newTotal.GenerateTotal(name, price)); } public void AddFooterLine(string line) { footerLines.Add(line); } private string AlignRightText(int lenght) { string espacios = ""; int spaces = maxChar - lenght; for (int x = 0; x < spaces; x++) espacios += " "; return espacios; } private string DottedLine() { string dotted = ""; for (int x = 0; x < maxChar; x++) dotted += "="; return dotted; } public bool PrinterExists(string impresora) { foreach (String strPrinter in PrinterSettings.InstalledPrinters) { if (impresora == strPrinter) return true; } return false; } public void PrintTicket(string impresora) { try { printFont = new Font(fontName, fontSize, FontStyle.Regular); PrintDocument pr = new PrintDocument(); //pr.PrinterSettings.PrinterName = impresora; pr.PrintPage += new PrintPageEventHandler(pr_PrintPage); pr.Print(); String pkInstalledPrinters; for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++) { pkInstalledPrinters = PrinterSettings.InstalledPrinters[i]; String[] a = new String[15]; a[i] = (pkInstalledPrinters); } } catch (Exception e) { MessageBox.Show(e.Message); } } private void pr_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) { e.Graphics.PageUnit = GraphicsUnit.Millimeter; gfx = e.Graphics; DrawImage(); DrawHeader(); DrawSubHeader(); DrawItems(); DrawTotales(); DrawFooter(); if (headerImage != null) { HeaderImage.Dispose(); headerImage.Dispose(); } } private float YPosition() { return topMargin + (count * printFont.GetHeight(gfx) + imageHeight); } private void DrawImage() { if (headerImage != null) { try { gfx.DrawImage(headerImage, new Point((int)leftMargin, (int)YPosition())); double height = ((double)headerImage.Height / 58) * 15; imageHeight = (int)Math.Round(height) + 3; } catch (Exception) { } } } private void DrawHeader() { foreach (string header in headerLines) { if (header.Length > maxChar) { int currentChar = 0; int headerLenght = header.Length; while (headerLenght > maxChar) { line = header.Substring(currentChar, maxChar); gfx.DrawString(line, printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; currentChar += maxChar; headerLenght -= maxChar; } line = header; gfx.DrawString(line.Substring(currentChar, line.Length - currentChar), printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; } else { line = header; gfx.DrawString(line, printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; } } DrawEspacio(); } private void DrawSubHeader() { foreach (string subHeader in subHeaderLines) { if (subHeader.Length > maxChar) { int currentChar = 0; int subHeaderLenght = subHeader.Length; while (subHeaderLenght > maxChar) { line = subHeader; gfx.DrawString(line.Substring(currentChar, maxChar), printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; currentChar += maxChar; subHeaderLenght -= maxChar; } line = subHeader; gfx.DrawString(line.Substring(currentChar, line.Length - currentChar), printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; } else { line = subHeader; gfx.DrawString(line, printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; line = DottedLine(); gfx.DrawString(line, printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; } } DrawEspacio(); } private void DrawItems() { OrderItem ordIt = new OrderItem('?'); gfx.DrawString("CANT DESCRIPCION IMPORTE", printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; DrawEspacio(); foreach (string item in items) { line = ordIt.GetItemCantidad(item); gfx.DrawString(line, printFont, myBrush, leftMargin, YPosition(), new StringFormat()); line = ordIt.GetItemPrice(item); line = AlignRightText(line.Length) + line; gfx.DrawString(line, printFont, myBrush, leftMargin, YPosition(), new StringFormat()); string name = ordIt.GetItemName(item); leftMargin = 0; if (name.Length > maxCharDescription) { int currentChar = 0; int itemLenght = name.Length; while (itemLenght > maxCharDescription) { line = ordIt.GetItemName(item); gfx.DrawString(" " + line.Substring(currentChar, maxCharDescription), printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; currentChar += maxCharDescription; itemLenght -= maxCharDescription; } line = ordIt.GetItemName(item); gfx.DrawString(" " + line.Substring(currentChar, line.Length - currentChar), printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; } else { gfx.DrawString(" " + ordIt.GetItemName(item), printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; } } leftMargin = 0; DrawEspacio(); line = DottedLine(); gfx.DrawString(line, printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; DrawEspacio(); } private void DrawTotales() { OrderTotal ordTot = new OrderTotal('?'); foreach (string total in totales) { line = ordTot.GetTotalCantidad(total); line = AlignRightText(line.Length) + line; gfx.DrawString(line, printFont, myBrush, leftMargin, YPosition(), new StringFormat()); leftMargin = 0; line = " " + ordTot.GetTotalName(total); gfx.DrawString(line, printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; } leftMargin = 0; DrawEspacio(); DrawEspacio(); } private void DrawFooter() { foreach (string footer in footerLines) { if (footer.Length > maxChar) { int currentChar = 0; int footerLenght = footer.Length; while (footerLenght > maxChar) { line = footer; gfx.DrawString(line.Substring(currentChar, maxChar), printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; currentChar += maxChar; footerLenght -= maxChar; } line = footer; gfx.DrawString(line.Substring(currentChar, line.Length - currentChar), printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; } else { line = footer; gfx.DrawString(line, printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; } } leftMargin = 0; DrawEspacio(); } private void DrawEspacio() { line = ""; gfx.DrawString(line, printFont, myBrush, leftMargin, YPosition(), new StringFormat()); count++; } } public class OrderItem { char[] delimitador = new char[] { '?' }; public OrderItem(char delimit) { delimitador = new char[] { delimit }; } public string GetItemCantidad(string orderItem) { string[] delimitado = orderItem.Split(delimitador); return delimitado[0]; } public string GetItemName(string orderItem) { string[] delimitado = orderItem.Split(delimitador); return delimitado[1]; } public string GetItemPrice(string orderItem) { string[] delimitado = orderItem.Split(delimitador); return delimitado[2]; } public string GenerateItem(string cantidad, string itemName, string price) { return cantidad + delimitador[0] + itemName + delimitador[0] + price; } } public class OrderTotal { char[] delimitador = new char[] { '?' }; public OrderTotal(char delimit) { delimitador = new char[] { delimit }; } public string GetTotalName(string totalItem) { string[] delimitado = totalItem.Split(delimitador); return delimitado[0]; } public string GetTotalCantidad(string totalItem) { string[] delimitado = totalItem.Split(delimitador); return delimitado[1]; } public string GenerateTotal(string totalName, string price) { return totalName + delimitador[0] + price; } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Ticket.cs
C#
oos
14,098
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class ProductosForm : Plantilla { Productos miProducto; public ProductosForm() { InitializeComponent(); } private void ProductosForm_Load(object sender, EventArgs e) { this.miProducto = new Productos(); this.miProducto.extraerTodosProductos(); this.enlaceFomulario = BindingContext[miProducto.Datos.DataSet, "PRODUCTOS"]; this.dgvClientes.DataSource = miProducto.Datos.DataSet; this.dgvClientes.DataMember = "PRODUCTOS"; this.enlazarCajas(); } private void btnNuevo_Click(object sender, EventArgs e) { this.desenlazarCajas(); this.borrarCajas(); this.estadoCajasNuevo(false); this.estadoBotones(false); } public void desenlazarCajas() { this.txtId.DataBindings.Clear(); this.txtDescripcion.DataBindings.Clear(); this.txtPrecio.DataBindings.Clear(); this.txtStock.DataBindings.Clear(); } public void borrarCajas() { this.txtId.Clear(); this.txtDescripcion.Clear(); this.txtPrecio.Clear(); this.txtStock.Clear(); this.txtId.Focus(); } public void estadoCajasNuevo(bool soloLectura) { this.txtId.ReadOnly = soloLectura; this.estadoCajasActualizar(soloLectura); } public void estadoCajasActualizar(bool soloLectura) { this.txtDescripcion.ReadOnly = soloLectura; this.txtPrecio.ReadOnly = soloLectura; this.txtStock.ReadOnly = soloLectura; } public void estadoBotones(bool estado) { btnNuevo.Enabled = estado; btnActualizar.Enabled = estado; btnEliminar.Enabled = estado; btnGuardar.Enabled = !estado; btnCancelar.Enabled = !estado; btnBuscar.Enabled = estado; } private void btnActualizar_Click(object sender, EventArgs e) { this.desenlazarCajas(); this.estadoCajasActualizar(false); this.estadoBotones(false); } private void btnEliminar_Click(object sender, EventArgs e) { DialogResult dr = MessageBox.Show("Realmente desea elminar el registro?", "Eliminar Registro", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == DialogResult.Yes) { this.eliminar(); } } public void eliminar() { this.enlaceFomulario.RemoveAt(enlaceFomulario.Position); this.miProducto.guardarProducto(); } private void btnGuardar_Click(object sender, EventArgs e) { if (!txtId.ReadOnly) { this.miProducto.nuevoProducto (Convert.ToInt32(txtId.Text),txtDescripcion.Text, Convert.ToInt32(txtPrecio.Text), Convert.ToInt32(txtStock.Text)); } else { this.eliminar(); this.miProducto.nuevoProducto(Convert.ToInt32(txtId.Text), txtDescripcion.Text, Convert.ToInt32(txtPrecio.Text), Convert.ToInt32(txtStock.Text)); } this.miProducto.guardarProducto(); this.borrarCajas(); this.enlazarCajas(); this.estadoBotones(true); this.estadoCajasNuevo(true); } public void enlazarCajas() { Binding enlace; enlace = new Binding("text", this.miProducto.Datos.DataSet, "PRODUCTOS.ID_PROD"); this.txtId.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miProducto.Datos.DataSet, "PRODUCTOS.DESCRIPCION"); this.txtDescripcion.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miProducto.Datos.DataSet, "PRODUCTOS.PRECIO"); this.txtPrecio.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miProducto.Datos.DataSet, "PRODUCTOS.STOCK"); this.txtStock.DataBindings.Add(enlace); enlace = null; } private void btnCancelar_Click(object sender, EventArgs e) { this.borrarCajas(); this.enlazarCajas(); this.estadoCajasNuevo(true); this.estadoBotones(true); } private void btnBuscar_Click(object sender, EventArgs e) { BuscarProducto buscar = new BuscarProducto(); buscar.ShowDialog(); } private void btnSalir_Click(object sender, EventArgs e) { // this.Close(); } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/ProductosForm.cs
C#
oos
5,347
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class BuscarProducto : Plantilla2 { public BuscarProducto() { InitializeComponent(); } private void BuscarProducto_Load(object sender, EventArgs e) { } private void bntBuscar_Click(object sender, EventArgs e) { Productos misClientes = new Productos(); misClientes.extraerDatosBusqueda("Descripcion", txtBuscar.Text); dgvClientes.DataSource = misClientes.Datos.DataSet; dgvClientes.DataMember = "PRODUCTOS"; } private void btnCancelar_Click(object sender, EventArgs e) { this.Close(); } private void txtBuscar_TextChanged(object sender, EventArgs e) { } private void btnSeleccionar_Click(object sender, EventArgs e) { } private void dgvClientes_Click(object sender, EventArgs e) { } private void dgvClientes_SelectionChanged(object sender, EventArgs e) { } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/BuscarProducto.cs
C#
oos
1,352
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class Historial : UserControl { public Historial() { InitializeComponent(); } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Historial.cs
C#
oos
384
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using FacturaControl; using System.Configuration; using LibPrintTicket; using ClaseTicket; namespace pryecto_taller_sist { public partial class FacturaD : Plantilla { private DateTime fecha=DateTime.Now; public FacturaD() { InitializeComponent(); } private void FacturaD_Load(object sender, EventArgs e) { txtFecha.Text = Convert.ToString(fecha); } private void btnAgregar_Click(object sender, EventArgs e) { Buscar_Productos buscar = new Buscar_Productos(); buscar.ShowDialog(); this.dgvFactura.Rows.Add(); this.dgvFactura["colCant",dgvFactura.Rows.Count-1].Value=buscar.Cantidad; this.dgvFactura["colDesc", dgvFactura.Rows.Count - 1].Value = buscar.Descripcion; this.dgvFactura["colPrecio", dgvFactura.Rows.Count - 1].Value = buscar.Precio; this.dgvFactura["colTotal", dgvFactura.Rows.Count - 1].Value = (buscar.Cantidad * buscar.Precio); this.calcularTotal(); } private void calcularTotal() { double suma = 0; for (int i = 0; i < dgvFactura.Rows.Count; i++) { suma = suma + Convert.ToDouble(this.dgvFactura["colTotal", i].Value); } this.txtTotal.Text = Convert.ToString(suma); } private void dgvFactura_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) { this.calcularTotal(); } private void btnImprimir_Click(object sender, EventArgs e) { if (txtApellido.TextLength > 0 && dgvFactura.RowCount > 0) { DialogResult dialog = MessageBox.Show("¿Desear imprimir el Ticket?", "Confirmar Impresión", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dialog == DialogResult.Yes) { Ticket2 ticket = new Ticket2(); // ticket.HeaderImage = System.Drawing.Image.FromFile(@"C:\imagen.jpg"); //esta propiedad no es obligatoria ticket.AddHeaderLine("TIENDA 'EL NOMBRE QUE SEA'"); ticket.AddHeaderLine("M. PLAZA DE MAYO 3020"); ticket.AddHeaderLine("ARG, CORONEL GRANADA"); ticket.AddHeaderLine("CUIL: 123456789-0"); //El metodo AddSubHeaderLine es lo mismo al de AddHeaderLine con la diferencia //de que al final de cada linea agrega una linea punteada "==========" ticket.AddSubHeaderLine("Caja # 1 - Ticket # 1"); ticket.AddSubHeaderLine("Fecha - Hora:" + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString()); //El metodo AddItem requeire 3 parametros, el primero es cantidad, el segundo es la descripcion //del producto y el tercero es el precio ticket.AddItem("1", "Articulo Prueba", "15.00"); ticket.AddItem("2", "Articulo Prueba", "25.00"); //El metodo AddTotal requiere 2 parametros, la descripcion del total, y el precio ticket.AddTotal("SUBTOTAL", "29.75"); ticket.AddTotal("IVA", "5.25"); ticket.AddTotal("TOTAL", "35.00"); ticket.AddTotal("", ""); //Ponemos un total en blanco que sirve de espacio ticket.AddTotal("RECIBIDO", "50.00"); ticket.AddTotal("CAMBIO", "15.00"); ticket.AddTotal("", "");//Ponemos un total en blanco que sirve de espacio //ticket.AddTotal("USTED AHORRO", "0.00"); //El metodo AddFooterLine funciona igual que la cabecera ticket.AddFooterLine("No olvide controlar su vuelto"); ticket.AddFooterLine("Ticket no valido como factura"); ticket.AddFooterLine("GRACIAS POR TU VISITA"); //Y por ultimo llamamos al metodo PrintTicket para imprimir el ticket, este metodo necesita un //parametro de tipo string que debe de ser el nombre de la impresora. ticket.PrintTicket("a"); } } else { MessageBox.Show("No es posible imprimir un ticket sin completar los datos del Cliente y la lista de Productos"); } } private void button2_Click(object sender, EventArgs e) { //this.Close(); } private void button1_Click(object sender, EventArgs e) { BuscarCliente buscar = new BuscarCliente(); buscar.ShowDialog(); if (buscar.Apellido1 !=null ) { this.txtCliente.Text = buscar.Estado1; this.txtApellido.Text = buscar.Apellido1; } } private void btnCancelar_Click(object sender, EventArgs e) { } private void btnNuevo_Click(object sender, EventArgs e) { LimpiarDatos(); } public void LimpiarDatos() { this.txtApellido.Text = null; this.txtCliente.Text = null; this.txtEstado.Text = null; dgvFactura.Rows.Clear(); } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/FacturaD.cs
C#
oos
5,785
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general sobre un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos atributos para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("pryecto taller sist")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("pryecto taller sist")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible como true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM [assembly: Guid("a1812bdc-56e1-4b99-bb8c-4c879b75da0f")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o establecer como predeterminados los números de versión de compilación y de revisión // mediante el asterisco ('*'), como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Properties/AssemblyInfo.cs
C#
oos
1,605
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class Buscar_Productos : BuscarProducto { Productos misProductos; private int cantidad; public int Cantidad { get { return this.cantidad; } set { this.cantidad = value; } } private int idProducto; public int IdProducto { get { return this.idProducto; } set { this.idProducto = value; } } private string descripcion; public string Descripcion { get { return this.descripcion; } set { this.descripcion = value; } } private int precio; public int Precio { get { return this.precio; } set { this.precio = value; } } public string txtProduct= ""; public Buscar_Productos() { InitializeComponent(); } private void btnCancelar_Click_1(object sender, EventArgs e) { this.Close(); } private void Buscar_ProductoFactura_Load(object sender, EventArgs e) { } public void btnSeleccionar_Click(object sender, EventArgs e) { if (txtIdProducto.Text.Length != 0) { this.idProducto = Convert.ToInt32(this.txtIdProducto.Text); this.descripcion = this.txtDescripcion.Text; this.precio = Convert.ToInt32(this.txtPrecio.Text); this.cantidad = Convert.ToInt32(this.txtCantidadd.Text); this.Close(); } else { MessageBox.Show("Debe seleccionar un Producto"); } } public void enlazarCaja() { Binding enlace; enlace = new Binding("Text", this.misProductos.Datos.DataSet, "PRODUCTOS.Id_Prod"); this.txtIdProducto.DataBindings.Add(enlace); enlace = null; enlace = new Binding("Text", this.misProductos.Datos.DataSet, "PRODUCTOS.Descripcion"); this.txtDescripcion.DataBindings.Add(enlace); enlace = null; enlace = new Binding("Text", this.misProductos.Datos.DataSet, "PRODUCTOS.PRECIO"); this.txtPrecio.DataBindings.Add(enlace); enlace = null; } public void desenlazarCajas() { this.txtIdProducto.DataBindings.Clear(); this.txtDescripcion.DataBindings.Clear(); this.txtPrecio.DataBindings.Clear(); } private void txtIdProducto_TextChanged(object sender, EventArgs e) { } private void bntBuscar_Click_1(object sender, EventArgs e) { desenlazarCajas(); this.misProductos = new Productos(); this.misProductos.extraerDatosBusqueda("DESCRIPCION", txtBuscar.Text); this.enlaceFomulario = BindingContext[this.misProductos.Datos.DataSet, "PRODUCTOS"]; this.dgvClientes.DataSource = this.misProductos.Datos.DataSet; this.dgvClientes.DataMember = "PRODUCTOS"; enlazarCaja(); this.txtProduct = txtIdProducto.Text; } private void dgvClientes_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void txtCantidad_TextChanged(object sender, EventArgs e) { } private void dgvClientes_CellContentClick_1(object sender, DataGridViewCellEventArgs e) { } } } //enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTE.Apellido_P"); // this.txtApPaterno.DataBindings.Add(enlace); // enlace = null;
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Buscar ProductoFactura.cs
C#
oos
4,144
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class ProductosForm : Plantilla { Productos miProducto; public ProductosForm() { InitializeComponent(); } private void ProductosForm_Load(object sender, EventArgs e) { this.miProducto = new Productos(); this.miProducto.extraerTodosProductos(); this.enlaceFomulario = BindingContext[miProducto.Datos.DataSet, "PRODUCTOS"]; this.dgvClientes.DataSource = miProducto.Datos.DataSet; this.dgvClientes.DataMember = "PRODUCTOS"; this.enlazarCajas(); } private void btnNuevo_Click(object sender, EventArgs e) { this.desenlazarCajas(); this.borrarCajas(); this.estadoCajasNuevo(false); this.estadoBotones(false); } public void desenlazarCajas() { this.txtId.DataBindings.Clear(); this.txtDescripcion.DataBindings.Clear(); this.txtPrecio.DataBindings.Clear(); this.txtStock.DataBindings.Clear(); } public void borrarCajas() { this.txtId.Clear(); this.txtDescripcion.Clear(); this.txtPrecio.Clear(); this.txtStock.Clear(); this.txtId.Focus(); } public void estadoCajasNuevo(bool soloLectura) { this.txtId.ReadOnly = soloLectura; this.estadoCajasActualizar(soloLectura); } public void estadoCajasActualizar(bool soloLectura) { this.txtDescripcion.ReadOnly = soloLectura; this.txtPrecio.ReadOnly = soloLectura; this.txtStock.ReadOnly = soloLectura; } public void estadoBotones(bool estado) { btnNuevo.Enabled = estado; btnActualizar.Enabled = estado; btnEliminar.Enabled = estado; btnGuardar.Enabled = !estado; btnCancelar.Enabled = !estado; btnBuscar.Enabled = estado; } private void btnActualizar_Click(object sender, EventArgs e) { this.desenlazarCajas(); this.estadoCajasActualizar(false); this.estadoBotones(false); } private void btnEliminar_Click(object sender, EventArgs e) { this.eliminar(); } public void eliminar() { this.enlaceFomulario.RemoveAt(enlaceFomulario.Position); this.miProducto.guardarProducto(); } private void btnGuardar_Click(object sender, EventArgs e) { if (!txtId.ReadOnly) { this.miProducto.nuevoProducto (Convert.ToInt32(txtId.Text),txtDescripcion.Text, Convert.ToInt32(txtPrecio.Text), Convert.ToInt32(txtStock.Text)); } else { this.eliminar(); this.miProducto.nuevoProducto(Convert.ToInt32(txtId.Text), txtDescripcion.Text, Convert.ToInt32(txtPrecio.Text), Convert.ToInt32(txtStock.Text)); } this.miProducto.guardarProducto(); this.borrarCajas(); this.enlazarCajas(); this.estadoBotones(true); this.estadoCajasNuevo(true); } public void enlazarCajas() { Binding enlace; enlace = new Binding("text", this.miProducto.Datos.DataSet, "PRODUCTOS.ID_PROD"); this.txtId.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miProducto.Datos.DataSet, "PRODUCTOS.DESCRIPCION"); this.txtDescripcion.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miProducto.Datos.DataSet, "PRODUCTOS.PRECIO"); this.txtPrecio.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miProducto.Datos.DataSet, "PRODUCTOS.STOCK"); this.txtStock.DataBindings.Add(enlace); enlace = null; } private void btnCancelar_Click(object sender, EventArgs e) { this.borrarCajas(); this.enlazarCajas(); this.estadoCajasNuevo(true); this.estadoBotones(true); } private void btnBuscar_Click(object sender, EventArgs e) { BuscarProducto buscar = new BuscarProducto(); buscar.ShowDialog(); } private void btnSalir_Click(object sender, EventArgs e) { this.Close(); } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Repo/pryecto taller sist/ProductosForm.cs
C#
oos
5,099
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class BuscarProducto : Plantilla { public BuscarProducto() { InitializeComponent(); } private void BuscarProducto_Load(object sender, EventArgs e) { } private void bntBuscar_Click(object sender, EventArgs e) { Productos misClientes = new Productos(); misClientes.extraerDatosBusqueda("Descripcion", txtBuscar.Text); dgvClientes.DataSource = misClientes.Datos.DataSet; dgvClientes.DataMember = "PRODUCTOS"; } private void btnCancelar_Click(object sender, EventArgs e) { this.Close(); } private void txtBuscar_TextChanged(object sender, EventArgs e) { } private void btnSeleccionar_Click(object sender, EventArgs e) { } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Repo/pryecto taller sist/BuscarProducto.cs
C#
oos
1,139
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class FacturaD : Plantilla { private DateTime fecha=DateTime.Now; public FacturaD() { InitializeComponent(); } private void FacturaD_Load(object sender, EventArgs e) { txtFecha.Text = Convert.ToString(fecha); } private void btnAgregar_Click(object sender, EventArgs e) { Buscar_ProductoFactura buscar = new Buscar_ProductoFactura(); buscar.ShowDialog(); this.dgvFactura.Rows.Add(); this.dgvFactura["colCant",dgvFactura.Rows.Count-1].Value=buscar.Cantidad; this.dgvFactura["colDesc", dgvFactura.Rows.Count - 1].Value = buscar.Descripcion; this.dgvFactura["colPrecio", dgvFactura.Rows.Count - 1].Value = buscar.Precio; this.dgvFactura["colTotal", dgvFactura.Rows.Count - 1].Value = (buscar.Cantidad * buscar.Precio); this.calcularTotal(); } private void calcularTotal() { double suma = 0; for (int i = 0; i < dgvFactura.Rows.Count; i++) { suma = suma + Convert.ToDouble(this.dgvFactura["colTotal", i].Value); } this.txtTotal.Text = Convert.ToString(suma); } private void dgvFactura_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) { this.calcularTotal(); } private void btnImprimir_Click(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { this.Close(); } private void button1_Click(object sender, EventArgs e) { BuscarCliente buscar = new BuscarCliente(); buscar.ShowDialog(); } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Repo/pryecto taller sist/FacturaD.cs
C#
oos
2,124
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general sobre un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos atributos para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("pryecto taller sist")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("pryecto taller sist")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible como true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM [assembly: Guid("a1812bdc-56e1-4b99-bb8c-4c879b75da0f")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o establecer como predeterminados los números de versión de compilación y de revisión // mediante el asterisco ('*'), como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Repo/pryecto taller sist/Properties/AssemblyInfo.cs
C#
oos
1,605
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class Buscar_ProductoFactura : BuscarProducto { Productos misProductos; private int cantidad; public int Cantidad { get { return this.cantidad; } set { this.cantidad = value; } } private int idProducto; public int IdProducto { get { return this.idProducto; } set { this.idProducto = value; } } private string descripcion; public string Descripcion { get { return this.descripcion; } set { this.descripcion = value; } } private int precio; public int Precio { get { return this.precio; } set { this.precio = value; } } public Buscar_ProductoFactura() { InitializeComponent(); } private void btnCancelar_Click_1(object sender, EventArgs e) { this.Close(); } private void Buscar_ProductoFactura_Load(object sender, EventArgs e) { } private void btnSeleccionar_Click(object sender, EventArgs e) { if (txtIdProducto.Text.Length != 0) { this.idProducto = Convert.ToInt32(this.txtIdProducto.Text); this.descripcion = this.txtDescripcion.Text; this.precio = Convert.ToInt32(this.txtPrecio.Text); this.cantidad = Convert.ToInt32(this.txtCantidadd.Text); this.Close(); } else { MessageBox.Show("Error, debe seleccionar un Producto"); } } public void enlazarCaja() { Binding enlace; enlace = new Binding("Text", this.misProductos.Datos.DataSet, "PRODUCTOS.Id_Prod"); this.txtIdProducto.DataBindings.Add(enlace); enlace = null; enlace = new Binding("Text", this.misProductos.Datos.DataSet, "PRODUCTOS.Descripcion"); this.txtDescripcion.DataBindings.Add(enlace); enlace = null; enlace = new Binding("Text", this.misProductos.Datos.DataSet, "PRODUCTOS.PRECIO"); this.txtPrecio.DataBindings.Add(enlace); enlace = null; } public void desenlazarCajas() { this.txtIdProducto.DataBindings.Clear(); this.txtDescripcion.DataBindings.Clear(); this.txtPrecio.DataBindings.Clear(); } private void txtIdProducto_TextChanged(object sender, EventArgs e) { } private void bntBuscar_Click_1(object sender, EventArgs e) { desenlazarCajas(); this.misProductos = new Productos(); this.misProductos.extraerDatosBusqueda("DESCRIPCION", txtBuscar.Text); this.enlaceFomulario = BindingContext[this.misProductos.Datos.DataSet, "PRODUCTOS"]; this.dgvClientes.DataSource = this.misProductos.Datos.DataSet; this.dgvClientes.DataMember = "PRODUCTOS"; enlazarCaja(); } } } //enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTE.Apellido_P"); // this.txtApPaterno.DataBindings.Add(enlace); // enlace = null;
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Repo/pryecto taller sist/Buscar ProductoFactura.cs
C#
oos
3,716
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class FacturacionMDI : Form { public FacturacionMDI() { InitializeComponent(); } private void clienteToolStripMenuItem_Click(object sender, EventArgs e) { ClientesForm clientes = new ClientesForm(); clientes.ShowDialog(); } private void productosToolStripMenuItem_Click(object sender, EventArgs e) { ProductosForm producto = new ProductosForm(); producto.ShowDialog(); } private void facturaToolStripMenuItem_Click(object sender, EventArgs e) { FacturaD fact = new FacturaD(); fact.ShowDialog(); } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Repo/pryecto taller sist/FacturacionMDI.cs
C#
oos
969
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class Plantilla : Form { protected BindingManagerBase enlaceFomulario; public BindingManagerBase EnlaceFormulario { get { return this.enlaceFomulario; } set { this.enlaceFomulario = value; } } public Plantilla() { InitializeComponent(); } private void Plantilla_Load(object sender, EventArgs e) { } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Repo/pryecto taller sist/Plantilla.cs
C#
oos
714
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class BuscarCliente : Plantilla { private int idCliente; public int IDCliente { get { return this.idCliente; } set { this.idCliente = value; } } public BuscarCliente() { InitializeComponent(); } private void BuscarCliente_Load(object sender, EventArgs e) { } private void bntBuscar_Click(object sender, EventArgs e) { Clientes misClientes = new Clientes(); misClientes.extraerDatosBusqueda("NOMBRE", txtBuscar.Text); dgvClientes.DataSource = misClientes.Datos.DataSet; dgvClientes.DataMember = "CLIENTES"; } private void btnCancelar_Click(object sender, EventArgs e) { Close(); } private void btnSeleccionar_Click(object sender, EventArgs e) { } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Repo/pryecto taller sist/BuscarCliente.cs
C#
oos
1,203
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Windows.Forms; namespace pryecto_taller_sist { public class BaseDatos { private string connectionString; private string nombreTabla; private string consultaSql; private SqlConnection connection; private SqlDataAdapter dataAdapter; private SqlCommand command; private SqlCommandBuilder commandBuilder; private DataSet dataSet; public DataSet DataSet { get { return this.dataSet; } set { this.dataSet = value; } } public string ConsultaSql { get { return this.consultaSql; } set { this.consultaSql = value; } } public string NombreTabla { get { return this.nombreTabla; } set { this.nombreTabla = value; } } public BaseDatos(string consultaSql, string nombreTabla) { this.consultaSql = consultaSql; this.nombreTabla = nombreTabla; this.extraerDatos(); } public void extraerDatos() { try { // this.connectionString = ConfigurationManager.ConnectionStrings[@"Data Source=localhost\SQLExpress;Initial Catalog=FACT;Integrated Security=true;"].ToString(); this.connection = new SqlConnection(@"Data Source=localhost\SQLExpress;Initial Catalog=FACT;Integrated Security=true;"); //this.connectionString); this.command = new SqlCommand(this.consultaSql, this.connection); this.dataAdapter = new SqlDataAdapter(this.command); this.commandBuilder = new SqlCommandBuilder(this.dataAdapter); this.dataSet = new DataSet(); this.dataAdapter.Fill(this.dataSet, nombreTabla); } catch (Exception error) { MessageBox.Show(error.Message.ToString()); } } public void agregarFila(DataRow fila) { try { this.dataSet.Tables[this.nombreTabla].Rows.Add(fila); } catch (Exception error) { MessageBox.Show(error.Message.ToString()); } } public void guardar() { try { if (dataSet.HasChanges()) { this.dataAdapter.Update(this.dataSet, this.nombreTabla); } } catch (Exception error) { MessageBox.Show(error.Message.ToString()); } } } public class Clientes { private BaseDatos datos; string tabla="CLIENTES"; public Clientes() { } public BaseDatos Datos { get { return this.datos; } set { this.datos = value; } } public void extraerClienteTodosClientes() { datos = new BaseDatos("select * from CLIENTES", this.tabla); } public void extraerDatosBusqueda(string nombreCampo,string valor) { datos = new BaseDatos("select * from CLIENTES where "+nombreCampo+" like '%"+valor+"%'", this.tabla); //"select * from CLIENTE where CI likes '2345'"; } public void nuevoCliente(string id,string nombr,string apellido, string edad,string documento,string estado,string dir,string tel) { DataRow fila = datos.DataSet.Tables[this.tabla].NewRow(); fila["Id_Cliente"]=id; fila["Nombre"]=nombr; fila["Apellido"]=apellido; fila["Edad"] = edad; fila["Documento"]=documento; fila["Estado"]=estado; fila["Direccion"]=dir; fila["Telefono"]=tel; datos.agregarFila(fila); } public void guardarClientes() { datos.guardar(); } } public class Productos { private BaseDatos datos; string tabla = "PRODUCTOS"; public Productos() { } public BaseDatos Datos { get { return this.datos; } set { this.datos = value; } } public void extraerTodosProductos() { datos = new BaseDatos("select * from PRODUCTOS", this.tabla); } public void extraerDatosBusqueda(string nombreCampo, string valor) { datos = new BaseDatos("select * from PRODUCTOS where " + nombreCampo + " like '%" + valor + "%'", this.tabla); //"select * from CLIENTE where CI likes '2345'"; } public void nuevoProducto(int id, string descripcion, int precio, int stock) { DataRow fila = datos.DataSet.Tables[this.tabla].NewRow(); fila["Id_Prod"] = id; fila["Descripcion"] = descripcion; fila["Precio"] = precio; fila["Stock"] = stock; datos.agregarFila(fila); } public void guardarProducto() { datos.guardar(); } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Repo/pryecto taller sist/BaseDatos.cs
C#
oos
5,569
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class ClientesForm : Plantilla { Clientes miClientes; public ClientesForm() { InitializeComponent(); } private void ClientesForm_Load(object sender, EventArgs e) { this.miClientes = new Clientes(); this.miClientes.extraerClienteTodosClientes(); this.enlaceFomulario= BindingContext[miClientes.Datos.DataSet,"CLIENTES"]; this.dgvClientes.DataSource = miClientes.Datos.DataSet; this.dgvClientes.DataMember = "CLIENTES"; this.enlazarCajas(); } public void enlazarCajas() { Binding enlace; enlace = new Binding("text",this.miClientes.Datos.DataSet, "CLIENTES.Id_Cliente"); this.txtId.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Nombre"); this.txtNombre.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Apellido"); this.txtApellido.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Edad"); this.txtDocumento.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Telefono"); this.txtEstado.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Direccion"); this.txtDireccion.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.TMP1_CL"); this.txtTelefono.DataBindings.Add(enlace); enlace = null; } public void desenlazarCajas() { this.txtId.DataBindings.Clear(); this.txtNombre.DataBindings.Clear(); this.txtApellido.DataBindings.Clear(); this.txtDocumento.DataBindings.Clear(); this.txtEstado.DataBindings.Clear(); this.txtDireccion.DataBindings.Clear(); this.txtTelefono.DataBindings.Clear(); } private void btnNuevo_Click(object sender, EventArgs e) { this.desenlazarCajas(); this.borrarCajas(); this.estadoCajasNuevo(false); this.estadoBotones(false); } public void borrarCajas() { this.txtId.Clear(); this.txtNombre.Clear(); this.txtApellido.Clear(); this.txtDocumento.Clear(); this.txtEstado.Clear(); this.txtDireccion.Clear(); this.txtTelefono.Clear(); this.txtId.Focus(); } public void estadoCajasNuevo(bool soloLectura) { this.txtId.ReadOnly = soloLectura; this.estadoCajasActualizar(soloLectura); } public void estadoCajasActualizar(bool soloLectura) { this.txtNombre.ReadOnly = soloLectura; this.txtApellido.ReadOnly = soloLectura; this.txtDocumento.ReadOnly = soloLectura; this.txtEstado.ReadOnly = soloLectura; this.txtDireccion.ReadOnly = soloLectura; this.txtTelefono.ReadOnly = soloLectura; } public void estadoBotones(bool estado) { btnNuevo.Enabled = estado; btnActualizar.Enabled = estado; btnEliminar.Enabled = estado; btnGuardar.Enabled = !estado; btnCancelar.Enabled = !estado; btnBuscar.Enabled = estado; } private void btnCancelar_Click(object sender, EventArgs e) { this.borrarCajas(); this.enlazarCajas(); this.estadoCajasNuevo(true); this.estadoBotones(true); } private void btnActualizar_Click(object sender, EventArgs e) { this.desenlazarCajas(); this.estadoCajasActualizar(false); this.estadoBotones(false); } private void btnSalir_Click(object sender, EventArgs e) { this.Close(); } private void btnGuardar_Click(object sender, EventArgs e) { if (!txtId.ReadOnly) { this.miClientes.nuevoCliente(txtId.Text, txtNombre.Text, txtApellido.Text, txtEdad.Text,txtDocumento.Text,txtEstado.Text, txtDireccion.Text, txtTelefono.Text); } else { this.eliminar(); this.miClientes.nuevoCliente(txtId.Text, txtNombre.Text, txtApellido.Text, txtEdad.Text ,txtDocumento.Text, txtEstado.Text, txtDireccion.Text, txtTelefono.Text); } this.miClientes.guardarClientes(); this.borrarCajas(); this.enlazarCajas(); this.estadoBotones(true); this.estadoCajasNuevo(true); } private void btnEliminar_Click(object sender, EventArgs e) { this.eliminar(); } public void eliminar() { this.enlaceFomulario.RemoveAt(enlaceFomulario.Position); this.miClientes.guardarClientes(); } private void btnBuscar_Click(object sender, EventArgs e) { BuscarCliente buscar = new BuscarCliente(); buscar.ShowDialog(); } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Repo/pryecto taller sist/ClientesForm.cs
C#
oos
6,002
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace pryecto_taller_sist { static class Program { /// <summary> /// Punto de entrada principal para la aplicación. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FacturacionMDI()); } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Repo/pryecto taller sist/Program.cs
C#
oos
526
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class Plantilla2 : Form { protected BindingManagerBase enlaceFomulario; public BindingManagerBase EnlaceFormulario { get { return this.enlaceFomulario; } set { this.enlaceFomulario = value; } } public Plantilla2() { InitializeComponent(); } private void Plantilla_Load(object sender, EventArgs e) { } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Plantilla2.cs
C#
oos
716
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class FacturacionMDI : Form { public FacturacionMDI() { InitializeComponent(); } private void clienteToolStripMenuItem_Click(object sender, EventArgs e) { ClientesForm clientes = new ClientesForm(); // clientes.ShowDialog(); } private void productosToolStripMenuItem_Click(object sender, EventArgs e) { ProductosForm producto = new ProductosForm(); // producto.ShowDialog(); } private void facturaToolStripMenuItem_Click(object sender, EventArgs e) { FacturaD fact = new FacturaD(); //fact.ShowDialog(); } private void salirToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void FacturacionMDI_FormClosing(object sender, FormClosingEventArgs e) { DialogResult dr = MessageBox.Show("Desea cerrar la aplicacion?", "Cerrar Aplicación", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dr == DialogResult.No) { e.Cancel = true; } } private void facturaD1_Load(object sender, EventArgs e) { } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/FacturacionMDI.cs
C#
oos
1,565
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class Plantilla : UserControl { protected BindingManagerBase enlaceFomulario; public BindingManagerBase EnlaceFormulario { get { return this.enlaceFomulario; } set { this.enlaceFomulario = value; } } public Plantilla() { InitializeComponent(); } private void Plantilla_Load(object sender, EventArgs e) { } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Plantilla.cs
C#
oos
721
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Threading; namespace pryecto_taller_sist { public partial class BuscarCliente : Plantilla2 { private String Cliente; public String Cliente1 { get { return Cliente1; } set { Cliente1 = value; } } private String Apellido; public String Apellido1 { get { return Apellido; } set { Apellido = value; } } private String Estado; public String Estado1 { get { return Estado; } set { Estado = value; } } public BuscarCliente() { InitializeComponent(); } private void BuscarCliente_Load(object sender, EventArgs e) { } private void bntBuscar_Click(object sender, EventArgs e) { Clientes misClientes = new Clientes(); misClientes.extraerDatosBusqueda("NOMBRE", txtBuscar.Text); dgvClientes.DataSource = misClientes.Datos.DataSet; dgvClientes.DataMember = "CLIENTES"; while (dgvClientes.RowCount <= 0) { Thread.Sleep(2000); } enlazarCajas(); } private void btnCancelar_Click(object sender, EventArgs e) { this.Close(); } private void btnSeleccionar_Click(object sender, EventArgs e) { if (txtEstado.Text.Length != 0) { this.Cliente = txtNombre.Text; this.Apellido = txtApellido.Text; this.Estado = txtEstado.Text; this.Close(); } else { MessageBox.Show("Debe seleccionar un Cliente"); } } public void enlazarCajas() { Binding enlace; enlace = new Binding("text", dgvClientes.DataSource, "CLIENTES.Id_Cliente"); this.txtId.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", dgvClientes.DataSource, "CLIENTES.Nombre"); this.txtNombre.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", dgvClientes.DataSource, "CLIENTES.Apellido"); this.txtApellido.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", dgvClientes.DataSource, "CLIENTES.Estado"); this.txtEstado.DataBindings.Add(enlace); enlace = null; } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/BuscarCliente.cs
C#
oos
2,857
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Windows.Forms; namespace pryecto_taller_sist { public class BaseDatos { private string connectionString; private string nombreTabla; private string consultaSql; private SqlConnection connection; private SqlDataAdapter dataAdapter; private SqlCommand command; private SqlCommandBuilder commandBuilder; private DataSet dataSet; public DataSet DataSet { get { return this.dataSet; } set { this.dataSet = value; } } public string ConsultaSql { get { return this.consultaSql; } set { this.consultaSql = value; } } public string NombreTabla { get { return this.nombreTabla; } set { this.nombreTabla = value; } } public BaseDatos(string consultaSql, string nombreTabla) { this.consultaSql = consultaSql; this.nombreTabla = nombreTabla; this.extraerDatos(); } public void extraerDatos() { try { // this.connectionString = ConfigurationManager.ConnectionStrings[@"Data Source=localhost\SQLExpress;Initial Catalog=FACT;Integrated Security=true;"].ToString(); this.connection = new SqlConnection(@"Data Source=localhost\SQLExpress;Initial Catalog=FACT;Integrated Security=true;"); //this.connectionString); this.command = new SqlCommand(this.consultaSql, this.connection); this.dataAdapter = new SqlDataAdapter(this.command); this.commandBuilder = new SqlCommandBuilder(this.dataAdapter); this.dataSet = new DataSet(); this.dataAdapter.Fill(this.dataSet, nombreTabla); } catch (Exception error) { MessageBox.Show(error.Message.ToString()); } } public void agregarFila(DataRow fila) { try { this.dataSet.Tables[this.nombreTabla].Rows.Add(fila); } catch (Exception error) { MessageBox.Show(error.Message.ToString()); } } public void guardar() { try { if (dataSet.HasChanges()) { this.dataAdapter.Update(this.dataSet, this.nombreTabla); //this.connection = new SqlConnection(@"Data Source=localhost\SQLExpress;Initial Catalog=FACT;Integrated Security=true;"); //string a = ("delete from productos where id_prod ='2'"); //command = new SqlCommand(a, connection); //connection.Open(); //command.ExecuteNonQuery(); } } catch (Exception error) { MessageBox.Show(error.Message.ToString()); } } } public class Clientes { private BaseDatos datos; string tabla="CLIENTES"; public Clientes() { } public BaseDatos Datos { get { return this.datos; } set { this.datos = value; } } public void extraerClienteTodosClientes() { datos = new BaseDatos("select * from CLIENTES", this.tabla); } public void extraerDatosBusqueda(string nombreCampo,string valor) { datos = new BaseDatos("select * from CLIENTES where "+nombreCampo+" like '%"+valor+"%'", this.tabla); //"select * from CLIENTE where CI likes '2345'"; } public void nuevoCliente(string id,string nombr,string apellido, string edad,string documento,string estado,string dir,string tel) { DataRow fila = datos.DataSet.Tables[this.tabla].NewRow(); fila["Id_Cliente"]=id; fila["Nombre"]=nombr; fila["Apellido"]=apellido; fila["Edad"] = edad; fila["Documento"]=documento; fila["Estado"]=estado; fila["Direccion"]=dir; fila["Telefono"]=tel; datos.agregarFila(fila); } public void guardarClientes() { datos.guardar(); } } public class Productos { private BaseDatos datos; string tabla = "PRODUCTOS"; public Productos() { } public BaseDatos Datos { get { return this.datos; } set { this.datos = value; } } public void extraerTodosProductos() { datos = new BaseDatos("select * from PRODUCTOS", this.tabla); } public void extraerDatosBusqueda(string nombreCampo, string valor) { datos = new BaseDatos("select * from PRODUCTOS where " + nombreCampo + " like '%" + valor + "%'", this.tabla); //"select * from CLIENTE where CI likes '2345'"; } public void nuevoProducto(int id, string descripcion, int precio, int stock) { DataRow fila = datos.DataSet.Tables[this.tabla].NewRow(); fila["Id_Prod"] = id; fila["Descripcion"] = descripcion; fila["Precio"] = precio; fila["Stock"] = stock; datos.agregarFila(fila); } public void guardarProducto() { datos.guardar(); } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/BaseDatos.cs
C#
oos
5,950
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class ClienteHistorial : Plantilla { Clientes miClientes; public ClienteHistorial() { InitializeComponent(); } private void ClientesForm_Load(object sender, EventArgs e) { this.miClientes = new Clientes(); this.miClientes.extraerClienteTodosClientes(); this.enlaceFomulario= BindingContext[miClientes.Datos.DataSet,"CLIENTES"]; this.dgvClientes.DataSource = miClientes.Datos.DataSet; this.dgvClientes.DataMember = "CLIENTES"; this.enlazarCajas(); } public void enlazarCajas() { Binding enlace; enlace = new Binding("text",this.miClientes.Datos.DataSet, "CLIENTES.Id_Cliente"); this.txtId.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Nombre"); this.txtNombre.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Apellido"); this.txtApellido.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Edad"); this.txtDocumento.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Telefono"); this.txtEstado.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Direccion"); this.txtDireccion.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.TMP1_CL"); this.txtTelefono.DataBindings.Add(enlace); enlace = null; } public void desenlazarCajas() { this.txtId.DataBindings.Clear(); this.txtNombre.DataBindings.Clear(); this.txtApellido.DataBindings.Clear(); this.txtDocumento.DataBindings.Clear(); this.txtEstado.DataBindings.Clear(); this.txtDireccion.DataBindings.Clear(); this.txtTelefono.DataBindings.Clear(); } private void btnNuevo_Click(object sender, EventArgs e) { this.desenlazarCajas(); this.borrarCajas(); this.estadoCajasNuevo(false); this.estadoBotones(false); } public void borrarCajas() { this.txtId.Clear(); this.txtNombre.Clear(); this.txtApellido.Clear(); this.txtDocumento.Clear(); this.txtEstado.Clear(); this.txtDireccion.Clear(); this.txtTelefono.Clear(); this.txtId.Focus(); } public void estadoCajasNuevo(bool soloLectura) { this.txtId.ReadOnly = soloLectura; this.estadoCajasActualizar(soloLectura); } public void estadoCajasActualizar(bool soloLectura) { this.txtNombre.ReadOnly = soloLectura; this.txtApellido.ReadOnly = soloLectura; this.txtDocumento.ReadOnly = soloLectura; this.txtEstado.ReadOnly = soloLectura; this.txtDireccion.ReadOnly = soloLectura; this.txtTelefono.ReadOnly = soloLectura; } public void estadoBotones(bool estado) { btnNuevo.Enabled = estado; btnActualizar.Enabled = estado; btnEliminar.Enabled = estado; btnGuardar.Enabled = !estado; btnCancelar.Enabled = !estado; btnBuscar.Enabled = estado; } private void btnCancelar_Click(object sender, EventArgs e) { this.borrarCajas(); this.enlazarCajas(); this.estadoCajasNuevo(true); this.estadoBotones(true); } private void btnActualizar_Click(object sender, EventArgs e) { this.desenlazarCajas(); this.estadoCajasActualizar(false); this.estadoBotones(false); } private void btnSalir_Click(object sender, EventArgs e) { // this.Close(); } private void btnGuardar_Click(object sender, EventArgs e) { if (!txtId.ReadOnly) { this.miClientes.nuevoCliente(txtId.Text, txtNombre.Text, txtApellido.Text, txtEdad.Text,txtDocumento.Text,txtEstado.Text, txtDireccion.Text, txtTelefono.Text); } else { this.eliminar(); this.miClientes.nuevoCliente(txtId.Text, txtNombre.Text, txtApellido.Text, txtEdad.Text ,txtDocumento.Text, txtEstado.Text, txtDireccion.Text, txtTelefono.Text); } this.miClientes.guardarClientes(); this.borrarCajas(); this.enlazarCajas(); this.estadoBotones(true); this.estadoCajasNuevo(true); } private void btnEliminar_Click(object sender, EventArgs e) { this.eliminar(); } public void eliminar() { this.enlaceFomulario.RemoveAt(enlaceFomulario.Position); this.miClientes.guardarClientes(); } private void btnBuscar_Click(object sender, EventArgs e) { BuscarCliente buscar = new BuscarCliente(); buscar.ShowDialog(); if (buscar.Apellido1 != null) { this.txtId.Text = buscar.Estado1; this.txtApellido.Text = buscar.Apellido1; } } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/ClienteHistorial.cs
C#
oos
6,170
using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Drawing; using System.Drawing.Printing; using System.Runtime.InteropServices; namespace FacturaControl { class Factura { String[,] datos = new String[100, 3]; String[,] items = new String[1000, 6]; int contador_datos = 0; int contador_items = 0; int contador = 1; int posItemsY = 0; Font printFont = null; SolidBrush myBrush = new SolidBrush(Color.Black); string fontName = "Lucida Console"; int fontSize = 8; Graphics gfx = null; public Factura() { } public bool PrinterExists(string impresora) { foreach (String strPrinter in PrinterSettings.InstalledPrinters) { if (impresora == strPrinter) return true; } return false; } public void PrintFactura(string impresora) { printFont = new Font(fontName, fontSize, FontStyle.Regular); PrintDocument pr = new PrintDocument(); pr.PrinterSettings.PrinterName = impresora; pr.DocumentName = "Impresion de Factura"; pr.PrintPage += new PrintPageEventHandler(pr_PrintPage); pr.Print(); } private void pr_PrintPage(Object sender, PrintPageEventArgs e) { e.Graphics.PageUnit = GraphicsUnit.Millimeter; gfx = e.Graphics; DrawDatos(); DrawItems(); } private void DrawDatos() { for (int i = 0; i < contador_datos; i++) { int PosX = int.Parse(datos[i, 1].ToString()); int PosY = int.Parse(datos[i, 2].ToString()); gfx.DrawString(datos[i, 0], printFont, myBrush, PosX, PosY, new StringFormat()); } } private void DrawItems() { for (int i = 0; i < contador_items; i++) { int PosX = int.Parse(items[i, 1]); int PosY = int.Parse(items[i, 2]); gfx.DrawString(items[i, 0], printFont, myBrush, PosX, PosY + posItemsY, new StringFormat()); if (contador == 6) { posItemsY += 4; //incremento en 4 milimitros para la proxima linea contador = 0; } contador++; } } public void AddDatos(string datoTexto, string PosX, string PosY) { datos[contador_datos, 0] = datoTexto; datos[contador_datos, 1] = PosX; datos[contador_datos, 2] = PosY; contador_datos++; } public void AddItems(string AdditemTexto) { string[] itemsDatos = AdditemTexto.Split(','); string a = itemsDatos[0]; items[contador_items, 0] = AlignRightText(itemsDatos[0].Length, int.Parse(itemsDatos[0])); items[contador_items, 1] = ConfigurationSettings.AppSettings["textBox_ImpCanX"]; items[contador_items, 2] = ConfigurationSettings.AppSettings["textBox_ImpCanY"]; contador_items++; items[contador_items, 0] = AlignRightText(itemsDatos[2].Length, int.Parse(ConfigurationSettings.AppSettings["textBox_ImpPreMC"])) + itemsDatos[2]; items[contador_items, 1] = ConfigurationSettings.AppSettings["textBox_ImpPreX"]; items[contador_items, 2] = ConfigurationSettings.AppSettings["textBox_ImpPreY"]; contador_items++; items[contador_items, 0] = AlignRightText(itemsDatos[3].Length, int.Parse(ConfigurationSettings.AppSettings["textBox_ImpAliMC"])) + itemsDatos[3]; items[contador_items, 1] = ConfigurationSettings.AppSettings["textBox_ImpAliX"]; items[contador_items, 2] = ConfigurationSettings.AppSettings["textBox_ImpAliY"]; contador_items++; items[contador_items, 0] = AlignRightText(itemsDatos[4].Length, int.Parse(ConfigurationSettings.AppSettings["textBox_ImpBivMC"])) + itemsDatos[4]; items[contador_items, 1] = ConfigurationSettings.AppSettings["textBox_ImpBivX"]; items[contador_items, 2] = ConfigurationSettings.AppSettings["textBox_ImpBivY"]; contador_items++; items[contador_items, 0] = AlignRightText(itemsDatos[5].Length, int.Parse(ConfigurationSettings.AppSettings["textBox_ImpImpMC"])) + itemsDatos[5]; items[contador_items, 1] = ConfigurationSettings.AppSettings["textBox_ImpImpX"]; items[contador_items, 2] = ConfigurationSettings.AppSettings["textBox_ImpImpY"]; // Al detalle lo mando a comprobar y dividir en dos o mas lineas si es necesario DivideItemDet(itemsDatos[1].Length, int.Parse(ConfigurationSettings.AppSettings["textBox_ImpDetMC"]), itemsDatos[1]); // Continuo almacenando contador_items++; } private string AlignRightText(int lenght, int maxChar) { string espacios = ""; int spaces = maxChar - lenght; for (int x = 0; x < spaces; x++) espacios += " "; return espacios; } private void DivideItemDet(int lenghtDet, int maxCharDet, string detalleText) { if (lenghtDet > maxCharDet) { string[] splitDetalle = detalleText.Split(' '); string linea = ""; int i = 0; int contador_lineas = 0; while (i < splitDetalle.Length) { while ((linea.Length < maxCharDet) && (i < splitDetalle.Length)) { linea += splitDetalle[i] + " "; i++; } if (contador_lineas < 1) { contador_items++; items[contador_items, 0] = linea; items[contador_items, 1] = ConfigurationSettings.AppSettings["textBox_ImpDetX"]; items[contador_items, 2] = ConfigurationSettings.AppSettings["textBox_ImpDetY"]; contador_lineas++; linea = ""; } else { contador_items++; items[contador_items, 0] = ""; items[contador_items, 1] = ConfigurationSettings.AppSettings["textBox_ImpCanX"]; items[contador_items, 2] = ConfigurationSettings.AppSettings["textBox_ImpCanY"]; contador_items++; items[contador_items, 0] = linea; items[contador_items, 1] = ConfigurationSettings.AppSettings["textBox_ImpDetX"]; items[contador_items, 2] = ConfigurationSettings.AppSettings["textBox_ImpDetY"]; contador_items++; items[contador_items, 0] = ""; items[contador_items, 1] = ConfigurationSettings.AppSettings["textBox_ImpPreX"]; items[contador_items, 2] = ConfigurationSettings.AppSettings["textBox_ImpPreY"]; contador_items++; items[contador_items, 0] = ""; items[contador_items, 1] = ConfigurationSettings.AppSettings["textBox_ImpAliX"]; items[contador_items, 2] = ConfigurationSettings.AppSettings["textBox_ImpAliY"]; contador_items++; items[contador_items, 0] = ""; items[contador_items, 1] = ConfigurationSettings.AppSettings["textBox_ImpBivX"]; items[contador_items, 2] = ConfigurationSettings.AppSettings["textBox_ImpBivY"]; contador_items++; items[contador_items, 0] = ""; items[contador_items, 1] = ConfigurationSettings.AppSettings["textBox_ImpImpX"]; items[contador_items, 2] = ConfigurationSettings.AppSettings["textBox_ImpImpY"]; linea = ""; } } } else { contador_items++; items[contador_items, 0] = detalleText; items[contador_items, 1] = ConfigurationSettings.AppSettings["textBox_ImpDetX"]; items[contador_items, 2] = ConfigurationSettings.AppSettings["textBox_ImpDetY"]; } } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Factura.cs
C#
oos
8,950
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class ClientesForm : Plantilla { Clientes miClientes; public ClientesForm() { InitializeComponent(); } private void ClientesForm_Load(object sender, EventArgs e) { this.miClientes = new Clientes(); this.miClientes.extraerClienteTodosClientes(); this.enlaceFomulario= BindingContext[miClientes.Datos.DataSet,"CLIENTES"]; this.dgvClientes.DataSource = miClientes.Datos.DataSet; this.dgvClientes.DataMember = "CLIENTES"; this.enlazarCajas(); } public void enlazarCajas() { Binding enlace; enlace = new Binding("text",this.miClientes.Datos.DataSet, "CLIENTES.Id_Cliente"); this.txtId.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Nombre"); this.txtNombre.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Apellido"); this.txtApellido.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Edad"); this.txtDocumento.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Telefono"); this.txtEstado.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.Direccion"); this.txtDireccion.DataBindings.Add(enlace); enlace = null; enlace = new Binding("text", this.miClientes.Datos.DataSet, "CLIENTES.TMP1_CL"); this.txtTelefono.DataBindings.Add(enlace); enlace = null; } public void desenlazarCajas() { this.txtId.DataBindings.Clear(); this.txtNombre.DataBindings.Clear(); this.txtApellido.DataBindings.Clear(); this.txtDocumento.DataBindings.Clear(); this.txtEstado.DataBindings.Clear(); this.txtDireccion.DataBindings.Clear(); this.txtTelefono.DataBindings.Clear(); } private void btnNuevo_Click(object sender, EventArgs e) { this.desenlazarCajas(); this.borrarCajas(); this.estadoCajasNuevo(false); this.estadoBotones(false); } public void borrarCajas() { this.txtId.Clear(); this.txtNombre.Clear(); this.txtApellido.Clear(); this.txtDocumento.Clear(); this.txtEstado.Clear(); this.txtDireccion.Clear(); this.txtTelefono.Clear(); this.txtId.Focus(); } public void estadoCajasNuevo(bool soloLectura) { this.txtId.ReadOnly = soloLectura; this.estadoCajasActualizar(soloLectura); } public void estadoCajasActualizar(bool soloLectura) { this.txtNombre.ReadOnly = soloLectura; this.txtApellido.ReadOnly = soloLectura; this.txtDocumento.ReadOnly = soloLectura; this.txtEstado.ReadOnly = soloLectura; this.txtDireccion.ReadOnly = soloLectura; this.txtTelefono.ReadOnly = soloLectura; } public void estadoBotones(bool estado) { btnNuevo.Enabled = estado; btnActualizar.Enabled = estado; btnEliminar.Enabled = estado; btnGuardar.Enabled = !estado; btnCancelar.Enabled = !estado; btnBuscar.Enabled = estado; } private void btnCancelar_Click(object sender, EventArgs e) { this.borrarCajas(); this.enlazarCajas(); this.estadoCajasNuevo(true); this.estadoBotones(true); } private void btnActualizar_Click(object sender, EventArgs e) { this.desenlazarCajas(); this.estadoCajasActualizar(false); this.estadoBotones(false); } private void btnSalir_Click(object sender, EventArgs e) { // this.Close(); } private void btnGuardar_Click(object sender, EventArgs e) { if (!txtId.ReadOnly) { this.miClientes.nuevoCliente(txtId.Text, txtNombre.Text, txtApellido.Text, txtEdad.Text,txtDocumento.Text,txtEstado.Text, txtDireccion.Text, txtTelefono.Text); } else { this.eliminar(); this.miClientes.nuevoCliente(txtId.Text, txtNombre.Text, txtApellido.Text, txtEdad.Text ,txtDocumento.Text, txtEstado.Text, txtDireccion.Text, txtTelefono.Text); } this.miClientes.guardarClientes(); this.borrarCajas(); this.enlazarCajas(); this.estadoBotones(true); this.estadoCajasNuevo(true); } private void btnEliminar_Click(object sender, EventArgs e) { this.eliminar(); } public void eliminar() { this.enlaceFomulario.RemoveAt(enlaceFomulario.Position); this.miClientes.guardarClientes(); } private void btnBuscar_Click(object sender, EventArgs e) { BuscarCliente buscar = new BuscarCliente(); buscar.ShowDialog(); if (buscar.Apellido1 != null) { this.txtId.Text = buscar.Estado1; this.txtApellido.Text = buscar.Apellido1; } } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/ClientesForm.cs
C#
oos
6,162
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace pryecto_taller_sist { static class Program { /// <summary> /// Punto de entrada principal para la aplicación. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FacturacionMDI()); } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Program.cs
C#
oos
526
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace pryecto_taller_sist { public partial class Notas : UserControl { public Notas() { InitializeComponent(); } private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e) { } } }
0987654321zxcvbnmqaz
trunk/pryecto taller sist/Notas.cs
C#
oos
488
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** * */ package org.sagemath.android.views; import android.content.Context; import android.view.View; /** * @author Harald Schilly */ public class ScrollImageView extends View { /** * @param context */ public ScrollImageView(Context context) { super(context); } }
12085952-sageandroid
app-v1/src/org/sagemath/android/views/ScrollImageView.java
Java
gpl3
1,116
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android; import org.sagemath.android.fx.FunctionEditor; import org.json.JSONArray; import org.json.JSONException; import android.content.Context; import java.io.BufferedOutputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Static global Data. * * @author Harald Schilly */ final public class Global { private Global() { }; private static String FN_SETTINGS = "settings.json"; public static final String TAG = "SageAndroid"; /** * ID used for the Intent to identify a {@link FunctionEditor} */ public static final int FUNC_EDIT = 313245; // directional flags public static final int RIGHT = 1374, LEFT = 1375, FLIP = 1376; // cool number and used for zoom in and zoom out. public static double GOLDEN_RATIO = 1.61803399; private static CalculationAPI api; final static void setCalculationAPI(CalculationAPI api) { Global.api = api; } final public static CalculationAPI getCalculationAPI() { return api; } // Don't try to use localhost, because localhost is the Android // device itself. You always have to connect to some other machine. final static Set<Server> servers = new HashSet<Server>(3); // TODO remove initial list of servers static { servers.add(new Server("sagenb.org", "admin", "test")); } // private static SharedPreferences settings = null; private static Server server = null; private static SageAndroid context = null; static void setContext(SageAndroid context) { Global.context = context; try { loadSettings(); } catch (IOException ex) { // TODO handle this } catch (JSONException ex) { // TODO handle this } } final public static Context getContext() { return context; } /** * writes the list of servers to a json file. for more, read {@link * loadSettings()}. */ final static void saveSettings() { FileOutputStream fos = null; try { fos = context.openFileOutput(FN_SETTINGS, Context.MODE_PRIVATE); BufferedOutputStream bos = new BufferedOutputStream(fos); JSONArray json = new JSONArray(); for (Server s : servers) { JSONArray entry = new JSONArray(); entry.put(s.server); entry.put(s.username); entry.put(s.password); json.put(entry); } bos.write(json.toString().getBytes()); bos.close(); } catch (FileNotFoundException e) { // we just write to the fos, this should never fail, ... } catch (IOException ex) { // TODO handle this } finally { try { fos.close(); } catch (IOException ex) { } } } private final static StringBuilder loadSb = new StringBuilder(); /** * Reads the storead JSON data.<br> * Example: * * <pre> * [ * [ "http://server1", "franz", "99999" ], * [ "http://server2", "susi", "secret" ] * ] * </pre> * * @throws IOException * @throws JSONException */ final static void loadSettings() throws IOException, JSONException { // create "empty" settings file if it does not exist if (context.getFileStreamPath(FN_SETTINGS).exists()) { saveSettings(); return; } // first, read the file FileInputStream fis = context.openFileInput(FN_SETTINGS); try { BufferedReader br = new BufferedReader(new InputStreamReader(fis)); loadSb.setLength(0); for (int c; (c = br.read()) >= 0;) { loadSb.append(c); } } finally { fis.close(); } // then assume everything is readable from the json, otherwise an exception // is thrown List<Server> tmpServers = new ArrayList<Server>(); JSONArray json = new JSONArray(loadSb.toString()); for (int i = json.length() - 1; i >= 0; i--) { JSONArray entry = json.getJSONArray(i); tmpServers.add(new Server(entry.getString(0), entry.getString(1), entry.getString(2))); } // then replace the data (updating it would be better) servers.clear(); servers.addAll(tmpServers); } final static void setServer(Server selServer) { // we probably have to update an entry, remove it and ... for (Server s : servers) { if (selServer.server.equals(s.server)) { servers.remove(s); } } // ... add it servers.add(selServer); // point to the selected one server = selServer; } /** * @return password or if not set, "" */ final static String getPassword() { return (server == null) ? "" : server.password; } /** * @return username or if not set, "" */ final static String getUser() { return (server == null) ? "" : server.username; } /** * @return Server */ final public static Server getServer() { return server; } }
12085952-sageandroid
app-v1/src/org/sagemath/android/Global.java
Java
gpl3
5,916
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android; parcelable Server;
12085952-sageandroid
app-v1/src/org/sagemath/android/Server.aidl
AIDL
gpl3
881
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android; interface ConnectionListener { /** * Callback from background service to the actual App. */ void handleConnectionState(in int s); }
12085952-sageandroid
app-v1/src/org/sagemath/android/ConnectionListener.aidl
AIDL
gpl3
1,007
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** * */ package org.sagemath.android; import android.app.Activity; import android.content.res.Configuration; import android.util.DisplayMetrics; import android.view.Display; /** * @author Harald Schilly */ public class Utils { /** * @param activity * @return 1 is portrait and 2 is landscape */ final public static int screenOrientation(Activity activity) { int orientation = activity.getResources().getConfiguration().orientation; // if undefined if (orientation == Configuration.ORIENTATION_UNDEFINED) { final Display display = activity.getWindowManager().getDefaultDisplay(); if (display.getWidth() == display.getHeight()) { orientation = Configuration.ORIENTATION_SQUARE; } else { if (display.getWidth() < display.getHeight()) { orientation = Configuration.ORIENTATION_PORTRAIT; } else { orientation = Configuration.ORIENTATION_LANDSCAPE; } } } return orientation; } /** * @return */ final public static float getScaledWidth(Activity activity) { DisplayMetrics dm = activity.getResources().getDisplayMetrics(); int absWidth = dm.widthPixels; return absWidth / dm.scaledDensity; } }
12085952-sageandroid
app-v1/src/org/sagemath/android/Utils.java
Java
gpl3
2,064
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android; import android.os.Parcel; import android.os.Parcelable; import java.text.DecimalFormat; import java.util.concurrent.atomic.AtomicInteger; /** * Something to do for the Sage Server. * * @author Harald Schilly */ final public class Calculation { final public static int INIT = 0, STARTED = 1, FINISHED = 2; // for the unique id final private static AtomicInteger ID = new AtomicInteger(0); final private static DecimalFormat decimalSeconds = new DecimalFormat(); static { decimalSeconds.applyPattern("0.#### [s]"); } // id, starttime and code are defacto final and should be // treated as such, but they are not because of the aidl serialization. private int id; private int state = Calculation.INIT; private String result = ""; private long starttime = -1L; private String code = ""; // it's a convention that there has to be this field called CREATOR. final public static Parcelable.Creator<Calculation> CREATOR = new Parcelable.Creator<Calculation>() { @Override final public Calculation createFromParcel(Parcel in) { return new Calculation(in); } @Override final public Calculation[] newArray(int size) { return new Calculation[size]; } }; public Calculation(Parcel in) { readFromParcel(in); } /** * construct a new Calculation object. It is used to communicate between * Server/Client (Background Service) and holds the input, later the output * and a unique id. Additionally, it gives you the total time for the * calculation and it is planned to include a state. */ public Calculation() { id = ID.getAndIncrement(); } final void setCode(String code) { this.code = code; } final public String getCode() { return code; } final public void setResult(String result) { this.result = result; } final void setStartTime(long starttime) { this.starttime = starttime; } /** * AIDL serialization, must match with writeToParcel and used in * {@link CalculationListener} * * @param in */ final void readFromParcel(Parcel in) { id = in.readInt(); state = in.readInt(); result = in.readString(); code = in.readString(); starttime = in.readLong(); } /** * AIDL serialization, must match with readFromParcel and used in * {@link CalculationListener} * * @param reply * @param parcelableWriteReturnValue */ final void writeToParcel(Parcel reply, int parcelableWriteReturnValue) { reply.writeInt(id); reply.writeInt(state); reply.writeString(result); reply.writeString(code); reply.writeLong(starttime); } /** * the result of the calculation or "" * * @return */ final public String getResult() { return result; } /** * ID of the calculation * * @return unique int */ final public int getId() { return id; } /** * timespan between start of calculation and now in seconds. * * @return timespan in seconds */ final public String getElapsed() { double d = System.currentTimeMillis() - starttime; return decimalSeconds.format(d / 1000.0); } }
12085952-sageandroid
app-v1/src/org/sagemath/android/Calculation.java
Java
gpl3
4,055
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android; import org.sagemath.android.Calculation; import org.sagemath.android.Server; import org.sagemath.android.CalculationListener; import org.sagemath.android.ConnectionListener; interface CalculationAPI { void setServer(out Server server); /** * kill the current connection (if there is one) */ void killConnection(); int getStatus(); void stopService(); void addCalcListener(CalculationListener listener); void removeCalcListener(CalculationListener listener); void addConnListener(ConnectionListener listener); void removeConnListener(ConnectionListener listener); void setKeepAlive(boolean keepAlive); boolean getKeepAlive(); /** * This is the way to start a new calculation. The Service creates a * Calculation object and returns its unique ID. Later, the Calculation * object is sent back.<br> * TODO Maybe we should move the creation of the object to the client? */ int calculate(String code); /** * if true, a calculation is currently running. */ boolean isCalculationRunning(); /** * clears all unprocessed calculations from the working queue */ void clearQueue(); /** * returns the size of the queue */ int getQueueSize(); /** * if set to true, a notification in the notification bar * is shown when calculation has finished (only useful if * app is paused or closed) */ void setShowNotification(boolean b); }
12085952-sageandroid
app-v1/src/org/sagemath/android/CalculationAPI.aidl
AIDL
gpl3
2,321
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android; import org.sagemath.android.Calculation; interface CalculationListener { /** * Callback from background service to the actual App. * * @return if <code>true</code> the calculation was consumed and we do not need * to ask more listeners to handle the result. */ boolean handleCalculationResult(in Calculation c); }
12085952-sageandroid
app-v1/src/org/sagemath/android/CalculationListener.aidl
AIDL
gpl3
1,199
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** * */ package org.sagemath.android; import android.os.Parcel; import android.os.Parcelable; /** * @author Harald Schilly */ class Server { String server, username, password; /** * it's a convention that there has to be a field called CREATOR. */ final public static Parcelable.Creator<Server> CREATOR = new Parcelable.Creator<Server>() { @Override final public Server createFromParcel(Parcel in) { return new Server(in); } @Override final public Server[] newArray(int size) { return new Server[size]; } }; public Server(Parcel in) { readFromParcel(in); } public Server(String server, String username, String password) { this.server = server; this.username = username; this.password = password; } /** * */ public Server() { // TODO Auto-generated constructor stub } /** * AIDL serialization, must match with writeToParcel. * * @param in */ final void readFromParcel(Parcel in) { server = in.readString(); username = in.readString(); password = in.readString(); } /** * AIDL serialization, must match with readFromParcel * * @param reply * @param parcelableWriteReturnValue */ final void writeToParcel(Parcel out, int parcelableWriteReturnValue) { out.writeString(server); out.writeString(username); out.writeString(password); } /** * Determine if two probably distinct objects are equal. * * @return true, if they have the same field values. */ @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof Server) { Server so = (Server) other; if (this.server == so.server && this.username == so.username && this.password == so.password) { return true; } } return false; } /** * This class is used in a HashSet and has no final fields. We also have to * override {@link equals}. */ @Override public int hashCode() { return 0; // no immutable fields! } @Override public String toString() { return server; } }
12085952-sageandroid
app-v1/src/org/sagemath/android/Server.java
Java
gpl3
2,975
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** * */ package org.sagemath.android.interacts; import org.sagemath.android.Calculation; import org.sagemath.android.Global; import org.sagemath.android.R; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Message; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; import android.widget.ScrollView; import android.widget.TextView; import android.widget.ImageView.ScaleType; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.text.DecimalFormat; /** * @author Harald Schilly */ public class Plot extends AbstractInteract { /** * @param resource */ public Plot() { super(R.layout.plot); } private ImageView plot; private Button btnZoomIn, btnZoomOut; private float zoom = 1; private final String FILENAME = "plot.png"; private TextView status; private ScrollView scroll; final private static DecimalFormat decimalPercent = new DecimalFormat(); static { decimalPercent.applyPattern("0.## %"); } final private static BitmapFactory.Options bmOptions = new BitmapFactory.Options(); static { bmOptions.inScaled = false; } /* * (non-Javadoc) * @see org.sagemath.android.interacts.AbstractInteract#build() */ @Override protected void init() { plot = (ImageView) myView.findViewById(R.id.imgPlot); status = (TextView) myView.findViewById(R.id.txtPlotStatus); scroll = (ScrollView) myView.findViewById(R.id.plotScrollViewImage); // plot.setImageResource(R.drawable.example_plot); Bitmap bm = BitmapFactory.decodeResource(context.getResources(), R.drawable.example_plot, bmOptions); plot.setImageBitmap(bm); plot.setScaleType(ScaleType.CENTER); // TODO that does not work this way and we better not use scrolling at all scroll.setHorizontalScrollBarEnabled(true); btnZoomIn = (Button) myView.findViewById(R.id.btnPlotZoomIn); btnZoomOut = (Button) myView.findViewById(R.id.btnPlotZoomOut); OnClickListener nyi = new OnClickListener() { @Override public void onClick(View v) { if (v == btnZoomIn) { zoom *= Global.GOLDEN_RATIO; } else if (v == btnZoomOut) { zoom /= Global.GOLDEN_RATIO; } String width = Integer.toString(myView.getWidth()); calculate("plot(...zoom=" + decimalPercent.format(zoom) + ", width=" + width + ")"); } }; btnZoomIn.setOnClickListener(nyi); btnZoomOut.setOnClickListener(nyi); try { DownloadThread dt = new DownloadThread(downloadProgressHandler, new URI( "http://www.example.com/")); dt.start(); } catch (MalformedURLException ex) { } catch (URISyntaxException ex) { } } final private static int DOWNLOAD_PROGRESS = 239847; /** * Updates UI with download progress */ final private Handler downloadProgressHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case (DOWNLOAD_PROGRESS): int down = msg.arg1; int size = msg.arg2; if (size == 0) { // unknown } else { String percent = decimalPercent.format((double) down / (double) size); if (status != null) { status.setText("progress " + percent); } } break; default: super.handleMessage(msg); } } }; /** * Downloads the image */ private class DownloadThread extends Thread { private static final int MAX_BUFFER = 1024; private Handler handler; private int size = 0; private URL url; int downloaded = 0; DownloadThread(Handler h, URI uri) throws MalformedURLException { handler = h; this.url = uri.toURL(); } private void sendMessage() { Message msg = handler.obtainMessage(); msg.what = DOWNLOAD_PROGRESS; msg.arg1 = downloaded; msg.arg2 = size; handler.sendMessage(msg); } @Override public void run() { RandomAccessFile file = null; InputStream stream = null; try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); stream = connection.getInputStream(); size = connection.getContentLength(); if (connection.getResponseCode() != 200) { // TODO ERROR } if (size < 1) { // TODO ERROR } File f = new File(FILENAME); if (f.exists()) { f.delete(); } f.deleteOnExit(); file = new RandomAccessFile(FILENAME, "rw"); while (true) { byte buffer[] = new byte[(size - downloaded > MAX_BUFFER) ? MAX_BUFFER : size - downloaded]; // Read from server into buffer. int read = stream.read(buffer); if (read == -1) { break; } // Write buffer to file. file.write(buffer, 0, read); downloaded += read; sendMessage(); } } catch (IOException ex) { } } } // ~~~ end DownloadThread /* * (non-Javadoc) * @see * org.sagemath.android.interacts.AbstractInteract#onError(java.lang.String) */ @Override protected void onError(String msg) { status.setText(msg); } /* * (non-Javadoc) * @see * org.sagemath.android.interacts.AbstractInteract#onResult(java.lang.String) */ @Override protected void onResult(Calculation c) { status.setText(c.getCode() + "\n" + c.getResult()); } /* * (non-Javadoc) * @see org.sagemath.android.interacts.AbstractInteract#reset() */ @Override public void reset() { zoom = 1; status.setText("reset"); } }
12085952-sageandroid
app-v1/src/org/sagemath/android/interacts/Plot.java
Java
gpl3
7,038
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android.interacts; import org.sagemath.android.Calculation; import org.sagemath.android.R; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; /** * Calculate the solution to a system of linear equations, e.g. a 3 x 4 Matrix * of numerical value fields that are for a 3x3 matrix A and a 3x1 vector b and * then display the solution vector below. * * @author Harald Schilly */ public class System extends AbstractInteract { public System() { super(R.layout.system); } private Button solve; private TextView output; /* * (non-Javadoc) * @see org.sagemath.android.interacts.AbstractInteract#build() */ @Override protected void init() { solve = (Button) myView.findViewById(R.id.systemBtnSolve); output = (TextView) myView.findViewById(R.id.systemOutput); solve.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { output.setText("calculating ..."); calculate(Integer.toString((int) (42 * Math.random()))); } }); } /* * (non-Javadoc) * @see * org.sagemath.android.interacts.AbstractInteract#onError(java.lang.String) */ @Override protected void onError(String error) { output.setText("Error: " + error); } /* * (non-Javadoc) * @see * * org.sagemath.android.interacts.AbstractInteract#onResult(org.sagemath.android * .Calculation) */ @Override protected void onResult(Calculation c) { output.setText(c.getResult()); } /* * (non-Javadoc) * @see org.sagemath.android.interacts.AbstractInteract#reset() */ @Override public void reset() { // TODO Auto-generated method stub } }
12085952-sageandroid
app-v1/src/org/sagemath/android/interacts/System.java
Java
gpl3
2,610
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** * */ package org.sagemath.android.interacts; import org.sagemath.android.Calculation; import org.sagemath.android.CalculationAPI; import org.sagemath.android.CalculationListener; import org.sagemath.android.Global; import android.content.Context; import android.os.Handler; import android.os.Message; import android.os.RemoteException; import android.util.Log; import android.view.LayoutInflater; import android.view.View; /** * @author Harald Schilly */ public abstract class AbstractInteract { private static final int MSG_ID = 2; final protected LayoutInflater layoutInflater; final Handler handler; protected View myView; private CalculationAPI api; protected Context context; /** * callback to update on result. since it comes from another thread (the IPC * mechanism) we have to use the handler to get it on the UI thread. before * that, we check if it actually concerns us. */ private CalculationListener calcListener = new CalculationListener.Stub() { @Override public boolean handleCalculationResult(Calculation c) throws RemoteException { // only react to results that were initiated by me if (id == c.getId()) { handler.sendMessage(handler.obtainMessage(MSG_ID, c)); return true; } return false; } }; /** * This is set to the ID of the {@link Calculation}. When we are called back, * we expect that this ID matches with the one in the answer. */ private int id = -1; /** * This is the base for all interact like interfaces. * It does the basic wireing, adds some thin wrappers around the * API and provides two callbacks: {@link AbstractInteract.onResult} and * {@link AbstractInteract.onError}. * * @param R.layout.[identifyer] */ public AbstractInteract(final int resource) { this.api = Global.getCalculationAPI(); this.context = Global.getContext(); this.layoutInflater = LayoutInflater.from(context); // Handler are called from non-UI threads to update the UI on the UI thread. handler = new Handler() { @Override public void handleMessage(Message msg) { if (MSG_ID == msg.what) { onResult((Calculation) msg.obj); } else { super.handleMessage(msg); } } }; myView = layoutInflater.inflate(resource, null); init(); } public void addCalcListener() { try { api.addCalcListener(calcListener); } catch (RemoteException re) { Log.w(Global.TAG, "Failed to add CalcListener in AbstracInteract", re); } } public void removeCalcListener() { try { api.removeCalcListener(calcListener); } catch (RemoteException re) { Log.w(Global.TAG, "Failed to remove CalcListener in AbstracInteract", re); } } protected void calculate(String code) { try { id = api.calculate(code); } catch (RemoteException ex) { onError(ex.toString()); } } /** * Use this method to get the View of this Interact. * It basically calls {@link build} to wire up the application. * * @return interact view */ public View getView() { reset(); return myView; } /** * Called once when object is created. Get UI elements and bind methods to UI * events, etc. */ abstract protected void init(); /** * Called when {@link Calculation} has finished. * * @param c */ abstract protected void onResult(Calculation c); /** * Called when error happened. * * @param error */ protected abstract void onError(String error); /** * reset is called when it is shown again (view object stays the same * but we have a chance to clean up) */ public abstract void reset(); }
12085952-sageandroid
app-v1/src/org/sagemath/android/interacts/AbstractInteract.java
Java
gpl3
4,607
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android.interacts; import org.sagemath.android.Calculation; import org.sagemath.android.R; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; /** * A simple interact that executes the given lines of code. * * @author schilly */ public class ExecuteCommand extends AbstractInteract { private TextView output; public ExecuteCommand() { super(R.layout.execute_command); } /* * (non-Javadoc) * @see * org.sagemath.android.interacts.AbstractInteract#build() */ @Override protected void init() { final EditText input = (EditText) myView.findViewById(R.id.exInputText); output = (TextView) myView.findViewById(R.id.exOutput); final Button button = (Button) myView.findViewById(R.id.exSend); button.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { calculate(input.getText().toString()); } }); } @Override public void onResult(Calculation c) { // interpret output and update UI output.setText(c.getResult()); } /* * (non-Javadoc) * @see * org.sagemath.android.interacts.AbstractInteract#onError(java.lang.String) */ @Override protected void onError(String msg) { output.setText("Error: " + msg); } /* * (non-Javadoc) * @see org.sagemath.android.interacts.AbstractInteract#reset() */ @Override public void reset() { output.setText(""); } }
12085952-sageandroid
app-v1/src/org/sagemath/android/interacts/ExecuteCommand.java
Java
gpl3
2,385
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, schilly <email@email.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. /** * */ package org.sagemath.android.interacts; import org.sagemath.android.Calculation; import org.sagemath.android.R; import android.widget.SeekBar; import android.widget.TextView; import android.widget.SeekBar.OnSeekBarChangeListener; /** * @author Harald Schilly */ public class SliderTest2 extends AbstractInteract { private TextView sliderTV; private int a = 0; /** */ public SliderTest2() { super(R.layout.slider_test); } @Override protected void onResult(Calculation c) { sliderTV.setText("a: " + a + " and result: " + c.getResult()); } @Override protected void onError(String msg) { sliderTV.setText("ERROR: " + msg); } @Override protected void init() { sliderTV = (TextView) myView.findViewById(R.id.SliderTestText); SeekBar sliderSB = (SeekBar) myView.findViewById(R.id.SliderTestSeekBar); sliderSB.setOnSeekBarChangeListener(new OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { a = progress; calculate(Integer.toString(progress)); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } /* * (non-Javadoc) * @see org.sagemath.android.interacts.AbstractInteract#reset() */ @Override public void reset() { onResult(new Calculation()); a = 0; } }
12085952-sageandroid
app-v1/src/org/sagemath/android/interacts/SliderTest2.java
Java
gpl3
2,323
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android.fx; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; /** * @author Harald Schilly */ public class ActionView extends TextView { private Action action; /** * @param context */ public ActionView(Context context) { super(context); } public ActionView(Context context, AttributeSet attrs) { super(context, attrs); } void setAction(Action action) { this.action = action; } Action getAction() { return action; } }
12085952-sageandroid
app-v1/src/org/sagemath/android/fx/ActionView.java
Java
gpl3
1,366
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android.fx; import android.content.Context; import android.util.AttributeSet; import android.widget.TextView; /** * @author Harald Schilly */ public class KeyView extends TextView { private Key key; /** * @param context */ public KeyView(Context context) { super(context); } public KeyView(Context context, AttributeSet attrs) { super(context, attrs); } void setKey(Key key) { this.key = key; } Key getKey() { return key; } }
12085952-sageandroid
app-v1/src/org/sagemath/android/fx/KeyView.java
Java
gpl3
1,327
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android.fx; import org.sagemath.android.R; import org.sagemath.android.Utils; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TableLayout; import android.widget.TableRow; import android.widget.TextView; import android.widget.Toast; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Edit a String to build up a function, like "1 + sin(x * cos(x)) / (1-x)". * This is an {@link Activity} and might also be used from other applications. * * @author Harald Schilly */ final public class FunctionEditor extends Activity { private Button btnDone, btnCancel; private EditText formula; private TableLayout gridFunc, gridNavi, gridOps; final static Pattern wordBoundary = Pattern.compile("\\b"); /** * Operators */ final private static String[] staticOps = { "+", "-", "*", "/", "^", "x", "y", "z", "(", ")", "<", ">", ".", "[", "]", "<", ">" }; /** * Entry point for creating the {@link FunctionEditor} Activity class. * * @return intent with modified text, and the start and end position of the * selection. */ @Override final public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.function_editor); final LayoutInflater inflater = this.getLayoutInflater(); // UI fields formula = (EditText) findViewById(R.id.fx_formula); btnDone = (Button) findViewById(R.id.fx_button_done); btnCancel = (Button) findViewById(R.id.fx_button_cancel); gridOps = (TableLayout) findViewById(R.id.fx_grid_ops); gridFunc = (TableLayout) findViewById(R.id.fx_grid_func); gridNavi = (TableLayout) findViewById(R.id.fx_grid_navi); { // Copy the text and selection state from the intent that started me Bundle bIntent = getIntent().getExtras(); final String func = bIntent.getString("func"); final int start = bIntent.getInt("start"); final int end = bIntent.getInt("end"); formula.setText(func); formula.setSelection(start, end); } // when done return the constructed string with the current selection in a // bundle btnDone.setOnClickListener(new OnClickListener() { @Override final public void onClick(View v) { Intent intent = new Intent(); Bundle bundle = new Bundle(); bundle.putString("func", formula.getText().toString()); bundle.putInt("start", formula.getSelectionStart()); bundle.putInt("end", formula.getSelectionEnd()); intent.putExtra("data", bundle); setResult(RESULT_OK, intent); finish(); } }); // just signal that it was canceled btnCancel.setOnClickListener(new OnClickListener() { @Override final public void onClick(View v) { setResult(RESULT_CANCELED); finish(); } }); // The following sets the "keys" which insert something or additionally // deletes something if there is a selection { final int cols = (int) (Utils.getScaledWidth(this) / 60.0); int idx = 0; TableRow row = null; for (Key key : Key.values()) { if (idx % cols == 0) { row = new TableRow(this); gridFunc.addView(row); } idx++; KeyView cell = (KeyView) inflater.inflate(R.layout.function_editor_key, null); cell.setText(key.toString()); cell.setKey(key); cell.setOnClickListener(keyClickListener); row.addView(cell); } } // this part inserts operators like +, -, ... { final int cols = (int) (Utils.getScaledWidth(this) / 40.0); TableRow row = null; int idx = 0; for (String op : staticOps) { if (idx % cols == 0) { row = new TableRow(this); gridOps.addView(row); } idx++; TextView cell = (TextView) inflater.inflate(R.layout.function_editor_textview, null); cell.setText(op); cell.setOnClickListener(opClickListener); row.addView(cell); } } // this part is lengthy and does some actions like cursor move, selections // and deletions { final int cols = (int) (Utils.getScaledWidth(this) / 40.0); TableRow row = null; int idx = 0; for (Action act : Action.values()) { if (idx % cols == 0) { row = new TableRow(this); gridNavi.addView(row); } idx++; ActionView cell = (ActionView) inflater.inflate(R.layout.function_editor_action, null); cell.setText(act.toString()); cell.setAction(act); cell.setOnClickListener(actionClickListener); row.addView(cell); } } } final private OnClickListener opClickListener = new OnClickListener() { @Override public void onClick(View v) { final String op = (String) ((TextView) v).getText(); final int start = formula.getSelectionStart(); final int end = formula.getSelectionEnd(); Editable formulaEdit = formula.getEditableText(); formulaEdit.replace(start, end, " " + op + " "); formula.setText(formulaEdit.toString()); formula.setSelection(start + op.length() + 2); } }; /** * This is the action listener, avoiding to create one for each key. */ final private OnClickListener keyClickListener = new OnClickListener() { @Override public void onClick(View v) { final Key f = ((KeyView) v).getKey(); final int oldPos = formula.getSelectionStart(); String s = formula.getText().replace(oldPos, formula.getSelectionEnd(), f.getInsert()) .toString(); formula.setText(s); formula.setSelection(oldPos + f.getOffset()); } }; /** * This is the action listener, avoiding to create one for each action. */ final private OnClickListener actionClickListener = new OnClickListener() { @Override public void onClick(View v) { final Action curAct = ((ActionView) v).getAction(); final int len = formula.length(); final int selLeft = formula.getSelectionStart(); final int selRght = formula.getSelectionEnd(); final int oneLeft = (selLeft <= 0) ? selLeft : selLeft - 1; final int oneRght = (selRght >= len - 1) ? selRght : selRght + 1; // ~~~ one word left and right final int oneWordRight, oneWordLeft; { // TODO make this correct final CharSequence leftpart = formula.getText().subSequence(0, selLeft); final CharSequence rightpart = formula.getText().subSequence(selRght, len - 1); Matcher matcher = wordBoundary.matcher(rightpart); int onerightmatchtmp; try { onerightmatchtmp = matcher.end(); } catch (IllegalStateException ise) { onerightmatchtmp = oneRght; } final int onerightmatch = onerightmatchtmp; final Matcher leftmatch = wordBoundary.matcher(leftpart); oneWordRight = (onerightmatch >= len - 1) ? len - 1 : onerightmatch; int oneleftmatchtmp; try { oneleftmatchtmp = leftmatch.start(leftmatch.groupCount() - 1); } catch (IllegalStateException ise) { oneleftmatchtmp = oneLeft; } final int oneleftmatch = oneleftmatchtmp; oneWordLeft = (oneleftmatch >= 0) ? oneleftmatch : 0; } // ~~~ end of one word left and right final Editable formulaEdit = formula.getEditableText(); switch (curAct) { case Linebreak: // TODO get the system specific linebreak formulaEdit.insert(selRght, "\n"); break; case Del: if (selLeft == selRght) { formulaEdit.delete(selLeft, oneRght); } else { formulaEdit.delete(selLeft, selRght); } break; case DelLeftOneChar: formulaEdit.delete(oneLeft, selRght); break; case DelRightOneChar: formulaEdit.delete(selLeft, oneRght); break; case SelLeftOneChar: formula.setSelection(oneLeft, selRght); break; case SelRightOneChar: formula.setSelection(selLeft, oneRght); break; case SelLeftOneWord: formula.setSelection(oneWordLeft, selRght); break; case SelRightOneWord: formula.setSelection(selLeft, oneWordRight); break; default: String msg = "ERROR: undefined action " + curAct.toString(); Toast.makeText(FunctionEditor.this, msg, Toast.LENGTH_SHORT).show(); } formula.setText(formulaEdit.toString()); } }; } /** * utf8 arrows for navigation and actions like deleting. * <a href="http://en.wikipedia.org/wiki/Arrow_%28symbol%29">Arrows at * Wikipedia</a> */ enum Action { // "\u00b6" // pilcrow sign Linebreak("\u21b2"), // down left for linebreak Del("\u21af"), // flash light arrow LeftMoveWordBoundary("\u219e"), // left two heads RightMoveWordBoundary("\u21a0"), // right two heads ChangeCase("\u21c5"), // up down double DelLeftOneChar("\u21dc"), // left wriggle DelLeftRightWordBoundary("\u21ad"), // left right wriggle DelRightOneChar("\u21dd"), // right wriggle SelLeftOneChar("\u21e6"), // left thick SelRightOneChar("\u21e8"), // right thick SelLeftOneWord("\u21da"), // left triple SelRightOneWord("\u21db"); // right triple final private String sign; Action(String sign) { this.sign = sign; } @Override public String toString() { return sign; } } /** * Defines the special keys to insert functions. <br> * The argument <code>insert</code> might contain the special character "|" * (pipe symbol) which stands for the insert sign. Otherwise, just specify the * <code>offset</code> parameter. */ enum Key { // zero("0"), one("1"), two("2"), three("3"), four("4"), // // five("5"), six("6"), seven("7"), eight("8"), nine("9"), // sin("sin"), cos("cos"), Tan("tan"), // trig asin("asin"), acos("acos"), atan("atan"), // trig inv infinity("\u221e", "oo"), // special integrate("\u222b", "integrate(|, x)"), diff("dx", "diff(|, x)"), // calc limit("limit", "limit(|, x = 0)"); final private String display, insert; final private int offset; Key(String display, boolean append) { this(display, append ? display + "(|)" : display); } Key(String display) { this(display, true); } Key(String display, String insert) { this(display, insert, 0); } Key(String display, String insert, int offset) { this.display = display; this.insert = insert; this.offset = offset; } /** * @return the relative position where the cursor should be placed from the * current position. * i.e. if we have the string AB|CD with the cursor between B and C, * and we insert XY with an offset of 2, we should end up with * ABXY|CD. */ final int getOffset() { if (offset > 0) { return offset; } int idx = insert.indexOf("|"); if (idx >= 0) { return idx; } return insert.length(); } /** * @return the string that should actually be inserted */ final String getInsert() { return insert.replaceAll("\\|", ""); } @Override final public String toString() { return display; } }
12085952-sageandroid
app-v1/src/org/sagemath/android/fx/FunctionEditor.java
Java
gpl3
12,519
// Sage Android Client. // Connect to a Sage server, remotely execute commands and display results. // // Copyright (C) 2010, Harald Schilly <harald.schilly@gmail.com> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package org.sagemath.android; parcelable Calculation;
12085952-sageandroid
app-v1/src/org/sagemath/android/Calculation.aidl
AIDL
gpl3
886