I found this example of exactly what I want to do except with .svg files. It appears to work as I have to click the right arrow 6 times to show the first image again. Is there a reason why the other svg images aren't showing?
Here is the code I adapted:
int maxImages = 6; // Total # of images
int imageIndex = 0; // Initial image to be displayed is the first
boolean isPlaying = false;
// Declaring an array of images.
PShape[] images = new PShape[maxImages];
void setup() {
size(1080,1920);
// Loading the images into the array
// Don't forget to put the JPG files in the data folder!
for (int i = 0; i < images.length; i ++ ) {
images[i] = loadShape( "HairStyles" + i + ".svg" );
}
frameRate(5);
}
void draw() {
background(100);
shape(images[imageIndex],500,500);
}
// Only happens when you release key
void keyReleased() {
if (keyCode == RIGHT) {
// Cycle
if (imageIndex >= 5) {
imageIndex = 0;
}
else {
imageIndex += 1;
}
}
else if (keyCode == LEFT) {
// Cycle backwards
if (imageIndex <= 0) {
imageIndex = 5;
}
else {
imageIndex -= 1;
}
}
}
It's pretty much the same as the example, could my problem be something to do with the exported files?
Related
I am a noob playing around with actionscript but i feel this question is a basic coding questionMy project is similar to this picture.
I have four quadrant areas (Red, blue, yellow, and green) that I am adding text buttons to each area with a single word in each button. There are 16 words in each section that are added from 4 arrays that have the preset words (redWordArray, greenWordArray, yellowWordArray, blueWordArray). When clicked, the text button glows using a glow filter and the word gets added to another array for data collecting. For instance, a red word when clicked gets added to a red array (redChosenArray). When the word is clicked again, it removes the glow filter and is removed from the chosen array.
I am finding that my performance is slow and I am wondering if I am adding and deleting words correctly and efficiently. These are my functions for adding the glow filters and the selected word to the array. I would love your insights for best coding practices as I am sure it is a mess!
Thank you!
function selectWord(event:MouseEvent):void
{
var tempWord:String = event.currentTarget.mood.text;
var tempArray:Array;
if (event.currentTarget.clicked == false)
{
event.currentTarget.filters = filterArray;
event.currentTarget.clicked = true;
tempArray = addToArray(tempWord)
tempArray.push(tempWord);
trace(redChosen);
trace(blueChosen);
trace(yellowChosen);
trace(greenChosen);
trace("");
}else if(event.currentTarget.clicked == true)
{
event.currentTarget.filters = emptyFilterArray;
event.currentTarget.clicked = false;
removeMoodWord(tempWord);
trace(redChosen);
trace(blueChosen);
trace(yellowChosen);
trace(greenChosen);
trace("");
}
}
function addToArray(moodWord:String):Array
{
var wordFound:Boolean = false;
var allWords:int = 16;
var chosenArray:Array;
while (!wordFound)
{
for (var h:int = 0; h < allWords; h++)
{
if (moodWord == redWords[h])
{
chosenArray = redChosen;
wordFound = true;
}else if (moodWord == yellowWords[h])
{
chosenArray = yellowChosen
wordFound = true;
}else if (moodWord == greenWords[h])
{
chosenArray = greenChosen
wordFound = true;
}else if (moodWord == blueWords[h])
{
chosenArray = blueChosen
wordFound = true;
}
}
}
return chosenArray;
}
function removeMoodWord(moodWord:String):void
{
if (redChosen.indexOf(moodWord) >= 0)
{
redChosen.splice(redChosen.indexOf(moodWord), 1);
}else if (blueChosen.indexOf(moodWord) >= 0)
{
blueChosen.splice(blueChosen.indexOf(moodWord), 1);
}else if (yellowChosen.indexOf(moodWord) >= 0)
{
yellowChosen.splice(yellowChosen.indexOf(moodWord), 1);
}else if (greenChosen.indexOf(moodWord) >= 0)
{
greenChosen.splice(greenChosen.indexOf(moodWord), 1);
}
i fee}
I should be beyond this, but I can't get to the bottom of this error. I'm trying to write a sketch that records the feed of my Mac camera and stores each recording "session" into a PImage array, then adds that to a list of sessions (a PImage[] ArrayList). I'm using a 'Replay' class to access the images stored in memory to and replay them at a random position. The code below should be ready to be copied straight into the IDE.
Any help would be greatly appreciated. I have no idea why the replay objects are always displaying the live image. Thanks!
import processing.video.*;
Capture cam;
ArrayList<PImage[]> allImages;
ArrayList<PImage> currentImages;
ArrayList<Replay> replays;
boolean recording = false;
boolean finishedSaving = true;
int currentIndex = 0;
void setup() {
size(1056, 704, P2D);
frameRate(30);
allImages = new ArrayList<PImage[]>();
currentImages = new ArrayList<PImage>();
replays = new ArrayList<Replay>();
String[] cams = Capture.list();
if (cams.length == 0) {
println("No cams!");
exit();
} else {
cam = new Capture(this, 1056, 704, cams[0], 30);
cam.start();
}
}
void draw() {
background(0);
if (cam.available() == true) {
cam.read();
}
for (Replay r : replays) {
r.display();
}
if (recording) {
currentImages.add(cam);
noFill();
stroke(255, 0, 0);
strokeWeight(5);
rect(0, 0, cam.width/3, cam.height/3);
} else {
saveToArray();
}
image(cam, 0, 0, cam.width/3, cam.height/3);
}
void saveToArray() {
if (!finishedSaving) {
PImage[] tempImages = currentImages.toArray(new PImage[currentImages.size()]);
allImages.add(tempImages);
currentImages.clear();
println("Finished saving to allImages array");
println("allImages array size now = " + allImages.size());
replays.add(new Replay(currentIndex));
println("Added new Replay (index: " + currentIndex + ")");
currentIndex++;
finishedSaving = true;
println();
}
}
void keyPressed() {
if (key == 'r' || key == 'R') {
recording = !recording;
println("Recording: " + recording);
finishedSaving = false;
}
}
class Replay {
PVector position;
float w, h;
PImage[] images;
int count;
Replay(int allImagesIndex) {
w = cam.width/3;
h = cam.height/3;
position = new PVector(random(width-w), random(height-h));
count = 1;
images = allImages.get(allImagesIndex);
}
void display() {
image(images[count], position.x, position.y, w, h);
count++;
if (count > images.length-1) count = 1;
}
}
Looks like this was due to the camera feed always being assignment to each individual image. To get a "copy" of the "current" video stream frame, I just added .get() to the feed so it fetches the pixels and stores them in a PImage variable.
currentImages.add(cam.get());
I have to make a navigable map
the starting point is in the center
there are three worlds + the final stage
pressing up I have to navigate from the base to the first level of the first world and go next level in second and third
pressing down I have do go from the third to the second and from the second to the first level and from the first level of the world to the base
pressing left and right I have to change the world
now:
I already made a lot of menus using different methods, but alway using a 1d array
obj_menu:
create event:
///menu
menu[0] = "new";
menu[1] = "load";
menu[2] = "exit";
space = 55;
mpos = 0;
step event:
///move
if(inputs) {
var move = 0;
move -= max(keyboard_check_pressed(vk_up),0);
move += max(keyboard_check_pressed(vk_down),0);
if(move != 0) {
mpos += move;
if(mpos < 0) {
mpos = array_length_1d(saveload) -1;
}
if(mpos > array_length_1d(saveload) -1) {
mpos = 0;
}
}
//push
if(keyboard_check_pressed(vk_enter)) {
scr_menu();
}
}
scr_menu();
switch(mpos) {
case 0: { scr_new_game(); break; } //new
case 1: { scr_load_game(); break; } //load
case 2: { game_end(); break; } //exit
default: { break; }
}
This time I have to navigate in a 2d array
I did this:
obj_map:
create event:
///navigation setup
if(crash_to_base) { lvl[0,0] = true }
if(base_to_ruins_1) { lvl[1,0] = true }
if(ruins_1_to_ruins_2) { lvl[1,1] = true }
if(ruins_2_to_ruins_3) { lvl[1,2] = true }
if(base_to_city_1) { lvl[2,0] = true }
if(city_1_to_city_2) { lvl[2,1] = true }
if(city_2_to_city_3) { lvl[2,2] = true }
if(base_to_lab_1) { lvl[3,0] = true }
if(lab_1_to_lab_2) { lvl[3,1] = true }
if(lab_2_to_lab_3) { lvl[3,2] = true }
if(base_to_castle) { lvl[4,0] = true }
//posizione del menu
mposh = 0;
mposv = 0;
mpos[mposv,mposh] = 0;
step event:
///map navigation
if(inputs) {
moveh -= max(keyboard_check_pressed(vk_left),0);
moveh += max(keyboard_check_pressed(vk_right),0);
movev -= max(keyboard_check_pressed(vk_up),0);
movev += max(keyboard_check_pressed(vk_down),0);
if(moveh != 0) {
//mposh += move;
}
if(movev != 0) {
//mposv += move;
}
push = keyboard_check_pressed(vk_enter);
if(push) {
scr_map();
}
}
how to translate the first method to de sencond need??
Not quite sure what your having difficulty with, perhaps you could elaborate on what exactly the problem is? On a side note however your 1D menu navigation code can be greatly simplified to:
mpos += keyboard_check_pressed(vk_up) - keyboard_check_pressed(vk_down);
var len = array_length_1d(saveload);
if (mpos < 0) { mpos = len - 1; }
if (mpos > len - 1) { mpos = 0; }
and in terms of a 2d map navigation system, it might not be beneficial to use 2d arrays and instead you could use a ds_map which allows you to store all information on each location in one data structure. For instance
var lvlMap = ds_map_create()
lvlMap[?"base-title"] = "Base"
lvlMap[?"base-travel-right"] = "crash"
lvlMap[?"base-travel-left"] = "fortress"
then when you try to move right/left:
var next_location = lvlMap[?current_location+"-travel-"+direction]
current_location = next_location
I need a text editor control for column edit in my application.
Like notepad++ alt+mouse drag to select a text block , or pull down a long vertical cursor and press a key to insert a char to every lines over cursor.
I tried ScintillaNET but it not suppor the column-modet for insert, just can remove selected text block
I need below effect(notepad++), But ScintillaNET got:
I found a way to solve. Still using ScintillaNET.
But coding not enough beauty :)
class SelWrap
{
public int Begin { get; set; }
public int Length { get; set; }
}
//...
editor.KeyDown += (s, e) =>
{
// filter alt we will hold down alt to make vertical selection
if (e.Alt) return;
var tb = editor;
if (tb.Selections.Count < 2) return; // no in column mode
e.SuppressKeyPress = true; //block input, handle by below code
//refered from post #5825820
var input = Utility.GetCharFromKey(e.KeyCode).ToString();
if (input == "\0")
{
//SystemSounds.Beep.Play();
return;
}
var array = tb.Selections
.OrderBy(p => p.Start)
.Select(p => new SelWrap{Begin=p.Start, Length=p.End - p.Start })
.ToArray();
//do process every caret(or selection)
for (var i = 0; i < array.Length; i++)
{
var item = array[i];
if (item.Length > 0)
{
//if has selected text, just clean
tb.DeleteRange(item.Begin, item.Length);
for (var j = i + 1; j < array.Length; j++)
{
array[j].Begin -= item.Length;
}
}
if (input == "\b") //backspace
{
if (item.Length != 0) continue;
//delete a char before caret
tb.DeleteRange(item.Begin - 1, 1);
for (var j = i; j < array.Length; j++)
{
array[j].Begin--;
}
}
else //just insert that
{
tb.InsertText(item.Begin, input);
for (var j = i; j < array.Length; j++)
{
array[j].Begin++;
}
}
}
//restore caret status to keep column mode
tb.ClearSelections();
tb.SetSelection(array[0].Begin, array[0].Begin);
for (var i = 1; i < array.Length; i++)
{
var item = array[i];
tb.AddSelection(item.Begin, item.Begin);
}
};
//...
You need to turn on Scintilla rectangular selection by sending required messages to initialize rectangular selection. Example,
CallScintilla(SCI_SETSELECTIONMODE, SC_SEL_STREAM);
CallScintilla(SCI_SETMOUSESELECTIONRECTANGULARSWITCH, true);
CallScintilla(SCI_SETADDITIONALSELECTIONTYPING, true); // so you can type in the selection
CallScintilla(SCI_SETMULTIPLESELECTION, false);
// on paste, paste into rectangular selection
CallScintilla(SCI_SETMULTIPASTE, SC_MULTIPASTE_EACH);
After that, it works like Visual Studio, you hold down the Alt key and drag with the mouse to start a rectangular selection.
I'm building a word search game using the following AS3 code. My problem is I need to have spaces in my array of words, so that I can have things like states names, but I need the spaces removed before the words go into the puzzle.
The other concern is also that when a person selects a word from the puzzle will it still match the word in the list even though the word in the list still has a space.
I've struggled with this for a few days now and could use some help.
I've pasted all appropriate code below, I believe. Thanks.
Rich
// words and grid
private var wordList:Array;
private var usedWords:Array;
private var grid:Array;
// sprites
private var letterSprites:Sprite;
private var wordsSprite:Sprite;
wordList = ("New York,New Jersey,South Carolina,North Carolina").split(",");
// set up the sprites
gameSprite = new Sprite();
addChild(gameSprite);
letterSprites = new Sprite();
gameSprite.addChild(letterSprites);
wordsSprite = new Sprite();
gameSprite.addChild(wordsSprite);
// array of letters
var letters:Array = placeLetters();
// create word list fields and sprites
for(var i:int=0;i<usedWords.length;i++) {
var newWord:TextField = new TextField();
newWord.defaultTextFormat = letterFormatForList;
if(i < 20){ // first list
newWord.x = listXposition;
newWord.y = i*spacingForList+listYposition;
} else { // second list
newWord.x = listXposition + 130;
newWord.y = i*spacingForList+listYposition - (20 * 19);
}
newWord.width = 135;
newWord.height = spacingForList;
newWord.text = usedWords[i];
newWord.selectable = false;
wordsSprite.addChild(newWord);
}
// set game state
dragMode = "none";
numFound = 0;
}
// place the words in a grid of letters
public function placeLetters():Array {
// create empty grid
var letters:Array = new Array();
for(var x:int=0;x<puzzleSize;x++) {
letters[x] = new Array();
for(var y:int=0;y<puzzleSize;y++) {
letters[x][y] = "*";
}
}
// make copy of word list
var wordListCopy:Array = wordList.concat();
usedWords = new Array();
// make 1000 attempts to add words
var repeatTimes:int = 1000;
repeatLoop:while (wordListCopy.length > wordsLeft) {
if (repeatTimes-- <= 0) break;
// pick a random word, location and direction
var wordNum:int = Math.floor(Math.random()*wordListCopy.length);
var word:String = wordListCopy[wordNum].toUpperCase();
x = Math.floor(Math.random()*puzzleSize);
y = Math.floor(Math.random()*puzzleSize);
var dx:int = Math.floor(Math.random()*3)-1;
var dy:int = Math.floor(Math.random()*3)-1;
if ((dx == 0) && (dy == 0)) continue repeatLoop;
// check each spot in grid to see if word fits
letterLoop:for (var j:int=0;j<word.length;j++) {
if ((x+dx*j < 0) || (y+dy*j < 0) || (x+dx*j >= puzzleSize) || (y+dy*j >= puzzleSize)) continue repeatLoop;
var thisLetter:String = letters[x+dx*j][y+dy*j];
if ((thisLetter != "*") && (thisLetter != word.charAt(j))) continue repeatLoop;
}
// insert word into grid
insertLoop:for (j=0;j<word.length;j++) {
letters[x+dx*j][y+dy*j] = word.charAt(j);
}
// remove word from list
wordListCopy.splice(wordNum,1);
usedWords.push(word);
}
// fill rest of grid with random letters
for(x=0;x<puzzleSize;x++) {
for(y=0;y<puzzleSize;y++) {
if (letters[x][y] == "*") {
letters[x][y] = String.fromCharCode(65+Math.floor(Math.random()*26));
}
}
}
return letters;
}
// player clicks down on a letter to start
public function clickLetter(event:MouseEvent) {
var letter:String = event.currentTarget.getChildAt(0).text;
startPoint = findGridPoint(event.currentTarget);
dragMode = "drag";
}
// player dragging over letters
public function overLetter(event:MouseEvent) {
if (dragMode == "drag") {
endPoint = findGridPoint(event.currentTarget);
// if valid range, show outline
outlineSprite.graphics.clear();
if (isValidRange(startPoint,endPoint)) {
drawOutline(outlineSprite,startPoint,endPoint,0xCCCCCC);
}
}
}
// mouse released
public function mouseRelease(event:MouseEvent) {
if (dragMode == "drag") {
dragMode = "none";
outlineSprite.graphics.clear();
// get word and check it
if (isValidRange(startPoint,endPoint)) {
var word = getSelectedWord();
checkWord(word);
}
}
}
// when a letter is clicked, find and return the x and y location
public function findGridPoint(letterSprite:Object):Point {
// loop through all sprites and find this one
for(var x:int=0;x<puzzleSize;x++) {
for(var y:int=0;y<puzzleSize;y++) {
if (grid[x][y] == letterSprite) {
return new Point(x,y);
}
}
}
return null;
}
// determine if range is in the same row, column, or a 45 degree diagonal
public function isValidRange(p1,p2:Point):Boolean {
if (p1.x == p2.x) return true;
if (p1.y == p2.y) return true;
if (Math.abs(p2.x-p1.x) == Math.abs(p2.y-p1.y)) return true;
return false;
}
// draw a thick line from one location to another
public function drawOutline(s:Sprite,p1,p2:Point,c:Number) {
var off:Point = new Point(offset.x+spacing/2, offset.y+spacing/2);
s.graphics.lineStyle(outlineSize,c);
s.graphics.moveTo(p1.x*spacing+off.x ,p1.y*spacing+off.y-3);
s.graphics.lineTo(p2.x*spacing+off.x ,p2.y*spacing+off.y-3);
}
// find selected letters based on start and end points
public function getSelectedWord():String {
// determine dx and dy of selection, and word length
var dx = endPoint.x-startPoint.x;
var dy = endPoint.y-startPoint.y;
var wordLength:Number = Math.max(Math.abs(dx),Math.abs(dy))+1;
// get each character of selection
var word:String = "";
for(var i:int=0;i<wordLength;i++) {
var x = startPoint.x;
if (dx < 0) x -= i;
if (dx > 0) x += i;
var y = startPoint.y;
if (dy < 0) y -= i;
if (dy > 0) y += i;
word += grid[x][y].getChildAt(0).text;
}
return word;
}
// check word against word list
public function checkWord(word:String) {
// loop through words
for(var i:int=0;i<usedWords.length;i++) {
// compare word
if (word == usedWords[i].toUpperCase()) {
foundWord(word);
}
// compare word reversed
var reverseWord:String = word.split("").reverse().join("");
if (reverseWord == usedWords[i].toUpperCase()) {
foundWord(reverseWord);
}
}
}
// word found, remove from list, make outline permanent
public function foundWord(word:String) {
sndSuccess=new success_sound();
sndSuccessChannel=sndSuccess.play(200);
so.data.totalWordsFound = so.data.totalWordsFound + 1;
so.flush();
// draw outline in permanent sprite
drawOutline(oldOutlineSprite,startPoint,endPoint,0xDDDDDD);
// find text field and set it to gray
for(var i:int=0;i<wordsSprite.numChildren;i++) {
if (TextField(wordsSprite.getChildAt(i)).text.toUpperCase() == word) {
TextField(wordsSprite.getChildAt(i)).textColor = 0x777777;
}
}
// see if all have been found
numFound++;
if (numFound == usedWords.length) {
if (so.data.difficulty == "Easy") {
so.data.easyWon = so.data.easyWon + 1;
}
if (so.data.difficulty == "Medium") {
so.data.mediumWon = so.data.mediumWon + 1;
}
if (so.data.difficulty == "Hard") {
so.data.hardWon = so.data.hardWon + 1;
}
so.flush();
endGame();
}
}
I'm hesitant to post an answer as I'm not really sure what's going on, but hopefully this info will help:
Keep your words in the arrays with spaces, that's a good idea. When you want to check against the words in your game, just convert both words to the same format using a function. eg:
var wordList:Array = ("New York,New Jersey,South Carolina,North Carolina").split(",");
var selectedWord:String = "NEWYORK";
// minWord converts all words to the same format of no spaces and all lower case.
function minWord(word:String):String {
return word.replace(/\s/g, "").toLowerCase();
}
// this loop checks all the words from your array against the selectedWord.
for each(var word:String in wordList) {
trace(minWord(word) + " == " + minWord(selectedWord) + "; ", minWord(word) == minWord(selectedWord));
}
Hope that helps!