Debian Codegraph @

bin/frozen-bubble

raw ◀ ▶
4 Debian patches touch this file
1 #!/usr/bin/perl
2 #*****************************************************************************
3 #
4 # Frozen-Bubble
5 #
6 # Copyright (c) 2000-2010 The Frozen-Bubble Team
7 #
8 # Originally sponsored by Mandriva <http://www.mandriva.com/>
9 #
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License version 2, as
12 # published by the Free Software Foundation.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program; if not, write to the Free Software
21 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
22 #
23 #******************************************************************************
24 #
25 # Design & Programming by Guillaume Cottenceau between Oct 2001 and Jan 2002.
26 # Level Editor parts by Kim Joham and David Joham between Oct 2002 and Jan 2003.
27 # Network game by Guillaume Cottenceau in 2004, 2006 (blah!).
28 #
29 # Check official home: http://www.frozen-bubble.org/
30 #
31 #******************************************************************************
32 #
33 # Yes it uses Perl, you non-believer :-).
34 #
35
36 #use diagnostics;
37 use strict;
38
39 use vars qw($TARGET_ANIM_SPEED $BUBBLE_SIZE $ROW_SIZE $LAUNCHER_SPEED $BUBBLE_SPEED $MALUS_BUBBLE_SPEED $TIME_APPEARS_NEW_ROOT
40 %POS %POS_1P %POS_2P %MENUPOS $KEYS %actions %angle %pdata $app %apprects $event %rects %sticked_bubbles %root_bubbles
41 $background $background_orig @bubbles_images $gcwashere %bubbles_anim %launched_bubble %tobe_launched %next_bubble $recorddir %recorddata $playdata
42 $shooter_lowgfx $sdl_flags $mixer $mixer_enabled $music_disabled $sfx_disabled $no_echo @playlist %sound %music %pinguin %canon
43 $graphics_level @update_rects $CANON_ROTATIONS_NB %malus_bubble %falling_bubble %exploding_bubble %malus_gfx %pangocontext $private $no_time_limit
44 %sticking_bubble $time %imgbin $TIME_HURRY_WARN $TIME_HURRY_MAX $TIMEOUT_PINGUIN_SLEEP $FREE_FALL_CONSTANT @joysticks $joysticksinfo
45 $direct @PLAYERS @ALL_PLAYERS %levels $display_on_app_disabled $addicted_time $start_time $time_1pgame $time_netgame $fullscreen $rcfile %hiscorefiles
46 $HISCORES $HISCORES_MPTRAIN $HISCORES_MPTRAIN_CHAINREACTION
•47 $total_launched_bubbles
48 $lev_number $playermalus $mptrainingdiff $loaded_levelset $direct_levelset $chainreaction %chains %img_mini $frame $sock $gameserver $mynick
49 $continuegamewhenplayersleave $singleplayertargetting $mylatitude $mylongitude %autokick $replayparam $autorecord $comment $saveframes $saveframesbase $saveframescounter);
50
51 use Getopt::Long;
52 use Data::Dumper;
53 use Locale::Maketext::Simple;
54 use Math::Trig;
55 use IO::File;
56 use Time::HiRes qw(gettimeofday);
57 use Compress::Bzip2;
•58 use File::Temp;
59
60 use SDL;
61 use SDL::Rect;
62 use SDL::Surface;
63 use SDL::Video;
64 use SDL::Event;
65 use SDL::Events;
66 use SDL::Color;
67 use SDL::Cursor;
68 use SDL::Mixer;
69 use SDL::Mixer::Samples;
70 use SDL::Mixer::Channels;
71 use SDL::Mixer::Music;
72 use SDL::Mixer::MixChunk;
73 use SDL::Mixer::MixMusic;
74 use SDL::Joystick;
75 use SDL::Mouse;
76 use SDL::Image;
77 use Games::FrozenBubble::Config;
78 use Games::FrozenBubble::Stuff;
79 use Games::FrozenBubble::Net;
80 use Games::FrozenBubble::NetDiscover;
81 use Games::FrozenBubble::Symbols;
82 use Games::FrozenBubble::LevelEditor;
83
84
85 $| = 1;
86
87 $FPATH = $Games::FrozenBubble::Config::FPATH;
88 $FLPATH = $Games::FrozenBubble::Config::FLPATH;
89
90
91 Locale::Maketext::Simple->import(Path => "$FPATH/locale", Style => 'gettext', Export => 'gettext');
92
93 $TARGET_ANIM_SPEED = 20; # number of milliseconds that should last between two animation frames
94 $LAUNCHER_SPEED = 0.03; # speed of rotation of launchers
95 $BUBBLE_SPEED = 10; # speed of movement of launched bubbles
96 $MALUS_BUBBLE_SPEED = 30; # speed of movement of "malus" launched bubbles
97 $CANON_ROTATIONS_NB = 100; # number of rotations of images for canon
98
99 $TIMEOUT_PINGUIN_SLEEP = 200;
100 $FREE_FALL_CONSTANT = 0.5;
101 $KEYS = {
102 p1 => { left => SDLK_LEFT, right => SDLK_RIGHT, fire => SDLK_UP, center => SDLK_DOWN },
103 p2 => { left => SDLK_x, right => SDLK_v, fire => SDLK_c, center => SDLK_d },
104 misc => { fs => SDLK_f, chat => SDLK_RETURN, send_malus_to_rp1 => SDLK_F1, send_malus_to_rp2 => SDLK_F2, send_malus_to_rp3 => SDLK_F3,
105 send_malus_to_rp4 => SDLK_F4, send_malus_to_all => SDLK_F10, next_playlist_elem => SDLK_TAB, save_record => SDLK_PRINT,
106 toggle_music => SDLK_F11, toggle_sound => SDLK_F12, raise_volume => SDLK_KP_PLUS, lower_volume => SDLK_KP_MINUS }
107 };
108 $sdl_flags = SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_HWACCEL | SDL_ASYNCBLIT;
109 $mixer = 0;
110 $graphics_level = 3;
111 @PLAYERS = qw(p1 p2);
112 @ALL_PLAYERS = qw(p1 p2 rp1 rp2 rp3 rp4);
113 $playermalus = 0;
114 $mptrainingdiff = 30;
115 $chainreaction = 0;
116 $mynick = (($^O eq 'MSWin32') ? getlogin() : ($ENV{USER} ? $ENV{USER} : 'unnamed'));
117 $HISCORES = [];
118 $HISCORES_MPTRAIN = [];
119 $HISCORES_MPTRAIN_CHAINREACTION = [];
120
121 my $RECORD_PROTOCOL_LEVEL = 0;
122
123 $rcfile = "$FBHOME/rc";
124 my $keys_orig = $KEYS;
125 eval(cat_($rcfile));
126 $KEYS->{misc}{chat} or ($KEYS->{p1}, $KEYS->{p2}) = ($KEYS->{p2}, $KEYS->{p1}); #- for upgrades
127 $KEYS->{misc}{$_} ||= $keys_orig->{misc}{$_} foreach keys %{$keys_orig->{misc}}; #-
128 eval(cat_($hiscorefiles{levels} = "$FBHOME/highscores"));
129 eval(cat_($hiscorefiles{mptrain} = "$FBHOME/highscores-mptrain"));
130
131 ###passing language to Locale::Maketext::Simple
132 my ($lang) = split(':', $ENV{LANGUAGE});
133 gettext_lang($lang);
134 our $is_rtl = $ENV{LANGUAGE} =~ /^fa/;
135
136 print " [[ Frozen-Bubble-$Games::FrozenBubble::RELEASE_VERSION ]]\n\n";
137 print ' http://www.frozen-bubble.org/
138
139 Copyright (c) 2000-2010 The Frozen-Bubble Team.
140
141 Artwork: Alexis Younes
142 Amaury Amblard-Ladurantie
143 Soundtrack: Matthias Le Bidan
144 Design & Programming: Guillaume Cottenceau
145 Level Editor: Kim and David Joham
146 Additional network programming: Mark Glines
147
148 Originally sponsored by Mandriva <http://www.mandriva.com/>
149
150 This program is free software; you can redistribute it and/or modify
151 it under the terms of the GNU General Public License version 2, as
152 published by the Free Software Foundation.
153
154 ';
155
156 #- become a friend of BooK
157 GetOptions("fullscreen|fs!" => \$fullscreen,
158 "no-sound|ns" => sub { $mixer = 'SOUND_DISABLED' },
159 "no-music|nm" => \$music_disabled,
160 "no-sfx" => \$sfx_disabled,
161 "playlist=s" => sub { @playlist = -d $_[1] ? glob("$_[1]/*") : cat_($_[1]) },
162 "slow-machine" => sub { $graphics_level = 2 },
163 "very-slow-machine" => sub { $graphics_level = 1 },
164 "direct" => \$direct,
165 "solo" => sub { $direct = 1; @PLAYERS = ('p1') },
166 "chain-reaction" => \$chainreaction,
167 "colour-blind|cb" => \$colourblind,
168 "player-malus=i" => \$playermalus,
169 "mp-training-difficulty=i" => \$mptrainingdiff,
170 "level|l=i" => sub { $levels{current} = $_[1]; $direct = 1; @PLAYERS = ('p1') },
171 "levelset=s" => sub { $direct_levelset = $_[1]; $levels{current} = 1; $direct = 1; @PLAYERS = ('p1') },
172 "no-time-limit" => \$no_time_limit,
173 "master-server=s" => \$Games::FrozenBubble::Net::masterserver,
174 "gameserver|gs=s" => sub { $gameserver = $_[1]; $direct = 1; @PLAYERS = qw(p1 rp1); $pdata{gametype} = 'net' },
175 "no-echo" => \$no_echo,
176 "my-nick=s" => \$mynick,
177 "private" => \$private,
178 "joysticks-info" => \$joysticksinfo,
179 "record=s" => sub { if (!-d $_[1]) { die("$_[1] does not exist.\n") } else { $recorddir = $_[1] } },
180 "auto-record" => \$autorecord,
181 "replay=s" => \$replayparam,
182 "save-frames=s" => sub { if (!-d $_[1]) { die("$_[1] does not exist.\n") } else { $saveframes = $_[1] } },
183 "comment=s" => \$comment,
184 "help" => sub { print "Usage: ", basename($0), " [OPTION]...
185 --fullscreen start in fullscreen mode
186 --no-fullscreen don't start in fullscreen mode
187 --no-sound don't try to start any sound stuff
188 --no-music disable music (only)
189 --no-sfx disable sound effects (only)
190 --playlist <file> use all files listed in the given file as music files and play them
191 --playlist <directory> use all files inside the given directory as music files and play them
192 --slow-machine enable slow machine mode (disable a few animations)
193 --very-slow-machine enable very slow machine mode (disable all that can be disabled)
194 --solo directly start solo (1p) game, with random levels if no -l<#n> is given
195 --direct directly start (2p) game (don't display menu)
196 --gameserver <host[:port]> directly start NET/LAN game connecting to this game server (if port is omitted, default port is used)
197 --level <#n> directly start the n-th level (implies -so)
198 --levelset<name> directly start with the specified levelset name
199 --no-time-limit disable time limit for shooting (e.g. kids mode)
200 --chain-reaction enable chain-reaction (when applicable)
201 --player-malus <#n> add a malus of n to the left player (can be negative)
202 --mp-training-difficulty <#n> set the average duration between receiving malus bubbles in 1 player multiplayer training (default 30 (= every 30 seconds on average), the lower the harder)
203 --colour-blind use bubbles for colourblind people
204 --joysticks-info print information about detected joystick(s) on startup
205 --no-echo when sound is enabled, disable echoing each typed character with a typewriter sound
•206 --my-nick <nick> for net/lan games, use this nick instead of username (max 8 chars, ASCII alphanumeric plus dash and underscore only)
207 --private when starting a net game, don't use http://hostip.info/ to retrieve your geographical position to send it to other players
208 --record <dir> specify the recording directory (normally, records are saved in the directory '$FBHOME/records')
209 --auto-record automatically record all applicable games (normally, a record is triggered by hitting the Print Screen key during a game)
210 --comment '...' add the comment enclosed between simple quotes to records (must not contain anything else than ASCII), it will be shown on console when playing back the record later
211 --replay <file|URL> replay the specified savegame
212 --save-frames <dir> specify a directory where all (game) frames will be recorded; as the game is slowed down, can only be used with --replay; typical use case is then to build a video out of the frames (see manpage)
213 ";
214 exit(0);
215 });
216
217 $mynick = sanitize_nick($mynick);
218 $saveframes && !$replayparam and print STDERR "--save-frames can only be used with --replay\n";
219
220
221 #- ------------------------------------------------------------------------
222
223 sub i18n_number {
224 my ($number) = @_;
225 my $out = '';
226 foreach my $char (split //, $number) {
227 if ($char eq '0') { $out .= loc("0"); }
228 elsif ($char eq '1') { $out .= loc("1"); }
229 elsif ($char eq '2') { $out .= loc("2"); }
230 elsif ($char eq '3') { $out .= loc("3"); }
231 elsif ($char eq '4') { $out .= loc("4"); }
232 elsif ($char eq '5') { $out .= loc("5"); }
233 elsif ($char eq '6') { $out .= loc("6"); }
234 elsif ($char eq '7') { $out .= loc("7"); }
235 elsif ($char eq '8') { $out .= loc("8"); }
236 elsif ($char eq '9') { $out .= loc("9"); }
237 elsif ($char eq '.') { $out .= loc("."); }
238 else { $out .= $char; }
239 }
240 return $out;
241 }
242
243 sub format_addiction {
244 my ($seconds, $i18n) = @_;
245 my $h = int($seconds/3600);
246 my $m = int(($seconds-$h*3600)/60);
247 my $s = int($seconds-$h*3600-$m*60);
248 if (!$i18n) {
249 return ($h ? "${h}h " : '') . ($m ? sprintf('%'.($h ? '02' : '').'dm ', $m) : '') . sprintf('%'.($m ? '02' : '').'ds', $s);
250 } else {
251 if ($h) {
252 $m = sprintf("%02d", $m);
253 }
254 if ($m) {
255 $s = sprintf("%02d", $s);
256 }
257 $h = i18n_number($h);
258 $m = i18n_number($m);
259 $s = i18n_number($s);
260 if ($h) {
261 return loc("%sh %sm %ss", $h, $m, $s);
262 } elsif ($m) {
263 return loc("%sm %ss", $m, $s);
264 } else {
265 return loc("%ss", $s);
266 }
267 }
268 }
269
270 END {
271 if ($app && $addicted_time) {
•272 print "\nAddicted for ", format_addiction($addicted_time/1000, 0), ", ", $total_launched_bubbles, " bubbles were launched.\n";
273 }
274 }
275
276
277 #- ----------- sound related stuff ----------------------------------------
278
279 sub play_sound($) {
280 $mixer_enabled && $mixer && !$sfx_disabled && $sound{$_[0]} and SDL::Mixer::Channels::play_channel(-1, $sound{$_[0]}, 0);
281 }
282
283 our $current_theoretical_music;
284 my $mus; #- I need to keep a reference on the music or it will be collected at the end of this function, thus I manually collect previous music
285
286 sub play_music($) {
287 my ($name) = @_;
288 $current_theoretical_music = $name;
289 $mixer_enabled && $mixer && !$music_disabled or return;
290 @playlist && SDL::Mixer::Music::playing_music and return;
291 SDL::delay(10) while SDL::Mixer::Music::fading_music; #- mikmod will deadlock if we try to fade_out while still fading in
292 SDL::Mixer::Music::playing_music and SDL::Mixer::Music::fade_out_music(500);
293 SDL::delay(400);
294 SDL::delay(10) while SDL::Mixer::Music::playing_music; #- mikmod will segfault if we try to load a music while old one is still fading out
295 my %musics = (intro => '/snd/introzik.ogg', main1p => '/snd/frozen-mainzik-1p.ogg', main2p => '/snd/frozen-mainzik-2p.ogg');
296 if (@playlist) {
297 my $tryanother = sub {
298 my $elem = chomp_(shift @playlist);
299 $elem or return -1;
300 -f $elem or return 0;
301 push @playlist, $elem;
302 $mus = SDL::Mixer::Music::load_MUS($elem) if -e $elem;
303 if ($mus) {
304 print STDERR "[Playlist] playing `$elem'\n";
305 SDL::Mixer::Music::play_music($mus, 0);
306 return 1;
307 } else {
308 print STDERR "Warning, could not create new music from '$elem' (reason: ", SDL::get_error(), ").\n";
309 return 0;
310 }
311 };
312 while ($tryanother->() == 0) {};
313 } else {
314 $mus = SDL::Mixer::Music::load_MUS("$FPATH$musics{$name}") if -e "$FPATH$musics{$name}";
315 if ($mus) {
316 SDL::Mixer::Music::play_music($mus, -1);
317 $music{current} = $name;
318 } else {
319 print STDERR "Warning, could not create new music from '$FPATH$musics{$name}' (reason: ", SDL::get_error(), ").\n";
320 }
321 }
322 }
323
324 sub init_sound() {
325 eval {
326 SDL::Mixer::open_audio( 22050, AUDIO_S16SYS, 2,1024);
327 };
328 if ($@) {
329 $@ =~ s| at \S+ line.*\n||;
330 print STDERR "\nWarning: can't initialize sound (reason: $@).\n";
331 return 0;
332 }
333
334 $mixer = 1;
335 print "[Sound Init] ";
336 my @sounds = qw(stick destroy_group newroot newroot_solo lose hurry pause menu_change menu_selected rebound launch malus noh snore cancel typewriter applause chatted);
337 foreach (@sounds) {
338 my $sound_path = "$FPATH/snd/$_.ogg";
339 $sound{$_} = SDL::Mixer::Samples::load_WAV($sound_path);
340 if (UNIVERSAL::isa($sound{$_}, 'HASH') ? $sound{$_}{-data} : ${$sound{$_}}) {
341 $sound{$_}->volume(100);
342 } else {
343 print STDERR "Warning, could not create new sound from '$sound_path'.\n";
344 }
345 }
346 return 1;
347 }
348
349
350 #- ----------- graphics related stuff --------------------------------------
351
352 sub add_default_rect($) {
353 my ($surface) = @_;
354 $rects{$surface} = SDL::Rect->new(0,0,$surface->w, $surface->h);
355 }
356
357 sub mini_graphics {
358 my ($p) = @_;
359 return @PLAYERS >= 3 && $p =~ /rp/;
360 }
361
362 sub translate_mini_image {
363 my ($image) = @_;
364 if (mini_graphics($::p_) || ($::p_ eq '' && mini_graphics($::p))) {
365 $img_mini{$image} and return $img_mini{$image};
366 }
367 return $image;
368 }
369
370 sub put_image($$$) {
371 my ($image, $x, $y) = @_;
372 $image = translate_mini_image($image);
373 $rects{$image} or die "please don't call me with no rects\n".backtrace();
374 my $drect = SDL::Rect->new($x, $y, $image->w, $image->h);
375 SDL::Video::blit_surface($image, $rects{$image}, $app, $drect);
376 push @update_rects, $drect;
377 }
378
379 sub erase_image_from($$$$) {
380 my ($image, $x, $y, $img) = @_;
381 $image = translate_mini_image($image);
382 my $drect = SDL::Rect->new($x, $y, $image->w, $image->h);
383 SDL::Video::blit_surface( $img, $drect, $app, $drect);
384 push @update_rects, $drect;
385 }
386
387 sub erase_image($$$) {
388 my ($image, $x, $y) = @_;
389 erase_image_from($image, $x, $y, $background);
390 }
391
392 sub put_image_to_background($$$) {
393 my ($image, $x, $y) = @_;
394 my $drect;
395 $image = translate_mini_image($image);
396 ($x == 0 && $y == 0) and print "put_image_to_background: warning, X and Y are 0\n".backtrace();
397 if ($y > 0) {
398 $drect = SDL::Rect->new($x, $y, $image->w, $image->h);
399 $display_on_app_disabled or SDL::Video::blit_surface ($image, $rects{$image}, $app, $drect);
400 SDL::Video::blit_surface($image , $rects{$image}, $background, $drect);
401 } else { #- clipping seems to not work when from one Surface to another Surface, so I need to do clipping by hand
402 $drect = SDL::Rect->new( $x, 0, $image->w, $image->h + $y);
403 my $irect = SDL::Rect->new( 0 , -$y , $image->w, $image->h + $y);
404 $display_on_app_disabled or SDL::Video::blit_surface($image, $irect, $app, $drect);
405 SDL::Video::blit_surface($image, $irect, $background, $drect);
406 }
407 push @update_rects, $drect;
408 }
409
410 sub remove_image_from_background($$$) {
411 my ($image, $x, $y) = @_;
412 $image = translate_mini_image($image);
413 ($x == 0 && $y == 0) and print "remove_image_from_background: warning, X and Y are 0\n";
414 my $drect = SDL::Rect->new( $x, $y, $image->w, $image->h);
415 SDL::Video::blit_surface( $background_orig, $drect, $background, $drect);
416 SDL::Video::blit_surface( $background_orig, $drect, $app, $drect);
417 push @update_rects, $drect;
418 }
419
420 sub remove_images_from_background {
421 my ($player, @images) = @_;
422 foreach my $image (@images) {
423 ($image->{'x'} == 0 && $image->{'y'} == 0) and print "remove_images_from_background: warning, X and Y are 0\n";
424 my $img = translate_mini_image($image->{img});
425 my $drect = SDL::Rect->new( $image->{'x'}, $image->{'y'}, $img->w, $img->h );
426 SDL::Video::blit_surface($background_orig, $drect, $background, $drect);
427 SDL::Video::blit_surface($background_orig, $drect, $app, $drect);
428 push @update_rects, $drect;
429 }
430 }
431
432 sub put_allimages_to_background($) {
433 my ($player) = @_;
434 put_image_to_background($_->{img}, $_->{'x'}, $_->{'y'}) foreach @{$sticked_bubbles{$player}};
435 }
436
437 sub switch_image_on_background($$$;$) {
438 my ($image, $x, $y, $save) = @_;
439 my $drect = SDL::Rect->new( $x, $y, $image->w, $image->h);
440 if ($save) {
441 $save = SDL::Surface->new( SDL_SWSURFACE, $image->w, $image->h, 32, 0 , 0, 0, 0);
442 #- grrr... this piece of shit of Amask made the surfaces slightly modify along the print/erase of "Hurry" and "Pause".... took me so much time to debug and find that the problem came from a bug when Amask is set to 0xFF000000 (while it's -supposed- to be set to 0xFF000000 with 32-bit graphics!!)
443 SDL::Video::blit_surface($background, $drect, $save, $rects{$image});
444 }
445 SDL::Video::blit_surface($image, $rects{$image} || SDL::Rect->new(0, 0, $image->w, $image->h), $background, $drect);
446 SDL::Video::blit_surface($background, $drect, $app, $drect);
447 push @update_rects, $drect;
448 return $save;
449 }
450
451 sub add_image_file($) {
452 my ($file) = @_;
453 my $img;
454 eval {
455 $img = SDL::Image::load( $file);
456 };
457 $@ and die "FATAL: Couldn't load '$file' into a SDL::Surface.\n";
458 add_default_rect($img);
459 return $img;
460 }
461
462 sub add_image($) {
463 return add_image_file("$FPATH/gfx/$_[0]");
464 }
465
466 sub add_images {
467 return map { add_image_file($_) } glob("$FPATH/gfx/$_[0]");
468 }
469
470 sub add_bubble_image($) {
471 my ($file) = @_;
472 my $bubble = add_image($file);
473 push @bubbles_images, $bubble;
474 return $bubble;
475 }
476
477
478 #- ----------- generic game stuff -----------------------------------------
479
480 sub iter_players(&) {
481 my ($f, @p) = @_;
482 my $bt = backtrace();
483 $bt =~ /\nmain::iter_players\b/ and die "iter_players: assert failed -- iter_players can't be called recursively sorry\n$bt";
484 @p or @p = @PLAYERS;
485 local $::p;
486 foreach $::p (@p) {
487 mini_graphics($::p) or goto normal_sizes; #- can't use an if block because of local
488 local $BUBBLE_SIZE = $BUBBLE_SIZE / 2;
489 local $BUBBLE_SPEED = $BUBBLE_SPEED / 2;
490 local $ROW_SIZE = $ROW_SIZE / 2;
491 local $FREE_FALL_CONSTANT = $FREE_FALL_CONSTANT / 2;
492 normal_sizes:
493 &$f;
494 }
495 }
496 sub iter_players_(&) { #- so that I can do an iter_players_ from within an iter_players
497 my ($f, @p) = @_;
498 my $bt = backtrace();
499 $bt =~ /\nmain::iter_players_\b/ and die "iter_players_: assert failed -- iter_players_ can't be called recursively sorry\n$bt";
500 @p or @p = @PLAYERS;
501 local $::p_;
502 foreach $::p_ (@p) {
503 &$f;
504 }
505 }
506 sub iter_players_but_first(&) {
507 my ($f) = @_;
508 my (undef, @p) = @PLAYERS;
509 &iter_players($f, @p);
510 }
511 sub iter_local_players(&) {
512 my ($f) = @_;
513 my @p = grep { !/rp/ } @PLAYERS;
514 &iter_players($f, @p);
515 }
516 sub iter_distant_players(&) {
517 my ($f) = @_;
518 my @p = grep { /rp/ } @PLAYERS;
519 &iter_players($f, @p);
520 }
521 sub iter_distant_players_(&) {
522 my ($f) = @_;
523 my @p = grep { /rp/ } @PLAYERS;
524 &iter_players_($f, @p);
525 }
526
527 sub is_1p_game() { @PLAYERS == 1 }
528 sub is_mp_game() { any { /rp/ } @PLAYERS }
529 sub is_2p_game() { @PLAYERS == 2 && !is_mp_game() }
530
531 sub is_leader() {
532 my $me = unpack('C', $pdata{p1}{id});
533 my $is_leader = 1;
534 iter_players_but_first {
535 $pdata{$::p}{left} or $is_leader &&= unpack('C', $pdata{$::p}{id}) > $me;
536 };
537 return $is_leader;
538 }
539 sub is_local_player($) {
540 my ($player) = @_;
541 $player !~ /rp/;
542 }
543 sub is_distant_player($) {
544 my ($player) = @_;
545 $player =~ /rp/;
546 }
547
548 sub mp_ping_if_needed {
549 my ($ticks_ref) = @_;
550 if (SDL::get_ticks() - $$ticks_ref > 1000) {
551 Games::FrozenBubble::Net::gsend('p');
552 $$ticks_ref = SDL::get_ticks();
553 }
554 }
555
556 sub mp_propagate {
557 my ($key, $value, $ticks_ref) = @_;
558 if (is_leader()) {
559 dbgnet("as leader, sending $key$value");
560 Games::FrozenBubble::Net::gsend("$key$value");
561 return $value;
562 } else {
563 my $m = Games::FrozenBubble::Net::grecv_get1msg();
564 mp_ping_if_needed($ticks_ref);
565 if ($m->{msg} !~ /^\Q$key\E(.+)/) {
566 if ($m->{msg} eq 'l') {
567 print "Server said that one of the players left - probably because of too high lag.\n";
568 } else {
569 print "Network protocol error: waiting for $key, received $m->{msg} - from $pdata{id2p}{$m->{id}}.\n";
570 }
571 die 'quit';
572 } else {
573 dbgnet("duly received awaited message $m->{msg} - from $pdata{id2p}{$m->{id}}");
574 return $1;
575 }
576 }
577 }
578
579 sub living_players() {
580 my @living;
581 iter_players_ {
582 if (!$pdata{$::p_}{left} && $pdata{$::p_}{state} eq 'ingame') {
583 push @living, $::p_;
584 }
585 };
586 return @living;
587 }
588
589 sub notleft_players() {
590 my $amount = 0;
591 iter_players_ {
592 $pdata{$::p_}{left} or $amount++;
593 };
594 return $amount;
595 }
596
597 #- ----------- bubble game stuff ------------------------------------------
598
599 sub calc_real_pos_given_arraypos($$$) {
600 my ($cx, $cy, $player) = @_;
601 ($POS{$player}{left_limit} + $cx * $BUBBLE_SIZE + odd($cy+$pdata{$player}{oddswap}) * $BUBBLE_SIZE/2,
602 $POS{$player}{top_limit} + $cy * $ROW_SIZE);
603 }
604
605 sub calc_real_pos($$) {
606 my ($b, $player) = @_;
607 ($b->{'x'}, $b->{'y'}) = calc_real_pos_given_arraypos($b->{cx}, $b->{cy}, $player);
608 }
609
610 sub get_array_yclosest($$) {
611 my ($y, $player) = @_;
612 return int(($y-$POS{$player}{top_limit}+$ROW_SIZE/2) / $ROW_SIZE);
613 }
614
615 sub get_array_closest_pos($$$) { # roughly the opposite than previous function
616 my ($x, $y, $player) = @_;
617 my $ny = get_array_yclosest($y, $player);
618 my $nx = int(($x-$POS{$player}{left_limit}+$BUBBLE_SIZE/2 - odd($ny+$pdata{$player}{oddswap})*$BUBBLE_SIZE/2)/$BUBBLE_SIZE);
619 return ($nx, $ny);
620 }
621
622 sub is_collision($$$) {
623 my ($bub, $x, $y) = @_;
624 my $DISTANCE_COLLISION_SQRED = sqr($BUBBLE_SIZE * 0.82);
625 my $xs = sqr($bub->{x} - $x);
626 ($xs > $DISTANCE_COLLISION_SQRED) and return 0;
627 return ($xs + sqr($bub->{'y'} - $y)) < $DISTANCE_COLLISION_SQRED;
628 }
629
630 sub create_bubble_given_img($) {
631 my ($img) = @_;
632 my %bubble;
633 ref($img) eq 'SDL::Surface' or die "<$img> seems to not be a valid image\n" . backtrace();
634 $bubble{img} = $img;
635 $bubble{neighbours} = [];
636 return \%bubble;
637 }
638
639 sub create_bubble_given_img_num($) {
640 my ($num) = @_;
641 return create_bubble_given_img($bubbles_images[$num]);
642 }
643
644 sub validate_nextcolor($$) {
645 my ($num, $player) = @_;
646 return !is_1p_game() || member($num, map { get_bubble_num($_) } @{$sticked_bubbles{$player}});
647 }
648
649 sub each_index(&@) {
650 my $f = shift;
651 local $::i = 0;
652 foreach (@_) {
653 $f->();
654 $::i++;
655 }
656 }
657 sub get_bubble_num {
658 my ($b) = @_;
659 my $num = -1;
660 each_index { $_ eq $b->{img} and $num = $::i } @bubbles_images;
661 return $num;
662 }
663
664 sub iter_rowscols(&$) {
665 my ($f, $oddswap) = @_;
666 local $::row; local $::col;
667 foreach $::row (0 .. 11) {
668 foreach $::col (0 .. 7 - odd($::row+$oddswap)) {
669 &$f;
670 }
671 }
672 }
673
674 sub each_index(&@) {
675 my $f = shift;
676 local $::i = 0;
677 foreach (@_) {
678 &$f($::i);
679 $::i++;
680 }
681 }
682 sub img2numb { my ($i, $f) = @_; each_index { $i eq $_ and $f = $::i } @bubbles_images; return defined($f) ? $f : '-' }
683
684 sub bubble_next_to($$$$$) {
685 my ($x1, $y1, $x2, $y2, $player) = @_;
686 if ($x1 == $x2 && $y1 == $y2) {
687 print STDERR "bubble_next_to: assert failed -- same bubbles ($x1:$y1;$player)\n";
688 $pdata{inconsistency} = 1;
689 die 'quit';
690 }
691 return to_bool((sqr($x1+odd($y1+$pdata{$player}{oddswap})*0.5 - ($x2+odd($y2+$pdata{$player}{oddswap})*0.5)) + sqr($y1 - $y2)) < 3);
692 }
693
694 sub next_positions($$) {
695 my ($b, $player) = @_;
696 my $validate_pos = sub {
697 my ($x, $y) = @_;
698 if_($x >= 0 && $x+odd($y+$pdata{$player}{oddswap}) <= 7 && $y >= 0 && $y >= $pdata{$player}{newrootlevel} && $y <= 11,
699 [ $x, $y ]);
700 };
701 ($validate_pos->($b->{cx} - 1, $b->{cy}),
702 $validate_pos->($b->{cx} + 1, $b->{cy}),
703 $validate_pos->($b->{cx} - even($b->{cy}+$pdata{$player}{oddswap}), $b->{cy} - 1),
704 $validate_pos->($b->{cx} - even($b->{cy}+$pdata{$player}{oddswap}), $b->{cy} + 1),
705 $validate_pos->($b->{cx} - even($b->{cy}+$pdata{$player}{oddswap}) + 1, $b->{cy} - 1),
706 $validate_pos->($b->{cx} - even($b->{cy}+$pdata{$player}{oddswap}) + 1, $b->{cy} + 1));
707 }
708
709 #- bubble ends its life sticked somewhere
710 sub real_stick_bubble {
711 my ($bubble, $xpos, $ypos, $player, $neighbours_ok) = @_;
712 $bubble->{cx} = $xpos;
713 $bubble->{cy} = $ypos;
714 foreach (@{$sticked_bubbles{$player}}) {
715 if (bubble_next_to($_->{cx}, $_->{cy}, $bubble->{cx}, $bubble->{cy}, $player)) {
716 push @{$_->{neighbours}}, $bubble;
717 $neighbours_ok or push @{$bubble->{neighbours}}, $_;
718 }
719 }
720 push @{$sticked_bubbles{$player}}, $bubble;
721 $bubble->{cy} == $pdata{$player}{newrootlevel} and push @{$root_bubbles{$player}}, $bubble;
722 calc_real_pos($bubble, $player);
723 put_image_to_background($bubble->{img}, $bubble->{'x'}, $bubble->{'y'});
724 }
725
726 sub destroy_bubbles {
727 my ($player, @bubz) = @_;
728 $graphics_level == 1 and return;
729 foreach (@bubz) {
730 $_->{speedx} = (rand(3)-1.5) / ( mini_graphics($player) ? 2 : 1 );
731 $_->{speedy} = (-rand(4)-2) / ( mini_graphics($player) ? 2 : 1 );
732 }
733 push @{$exploding_bubble{$player}}, @bubz;
734 }
735
736 sub find_bubble_group($) {
737 my ($b) = @_;
738 my @neighbours = $b;
739 my @group;
740 while (1) {
741 push @group, @neighbours;
742 @neighbours = grep { $b->{img} eq $_->{img} && !member($_, @group) } fastuniq(map { @{$_->{neighbours}} } @neighbours);
743 last if !@neighbours;
744 }
745 @group;
746 }
747
748 sub stick_bubble($$$$$) {
749 my ($bubble, $xpos, $ypos, $player, $count_for_root) = @_;
750 my @falling;
751 my $need_redraw = 0;
752 @{$bubble->{neighbours}} = grep { bubble_next_to($_->{cx}, $_->{cy}, $xpos, $ypos, $player) } @{$sticked_bubbles{$player}};
753
754 #- in multiple chain reactions, it's possible that the group doesn't exist anymore in some rare situations :/
755 exists $bubble->{chaindestx} && !@{$bubble->{neighbours}} and return;
756
757 my @will_destroy = difference2([ find_bubble_group($bubble) ], [ $bubble ]);
758
759 if (@will_destroy <= 1) {
760 #- stick
761 play_sound('stick');
762 real_stick_bubble($bubble, $xpos, $ypos, $player, 1);
763 $sticking_bubble{$player} = $bubble;
764 $pdata{$player}{sticking_step} = 0;
765 } else {
766 #- destroy the group
767 play_sound('destroy_group');
768 foreach my $b (difference2([ fastuniq(map { @{$_->{neighbours}} } @will_destroy) ], \@will_destroy)) {
769 @{$b->{neighbours}} = difference2($b->{neighbours}, \@will_destroy);
770 }
771 @{$sticked_bubbles{$player}} = difference2($sticked_bubbles{$player}, \@will_destroy);
772 @{$root_bubbles{$player}} = difference2($root_bubbles{$player}, \@will_destroy);
773
774 $bubble->{'cx'} = $xpos;
775 $bubble->{'cy'} = $ypos;
776 calc_real_pos($bubble, $player);
777 destroy_bubbles($player, @will_destroy, $bubble);
778
779 #- find falling bubbles
780 $_->{distance_to_root} = 0 foreach @{$sticked_bubbles{$player}};
781 my @still_sticked;
782 my @neighbours = @{$root_bubbles{$player}};
783 my $distance_to_root;
784 while (1) {
785 $_->{distance_to_root} = ++$distance_to_root foreach @neighbours;
786 push @still_sticked, @neighbours;
787 @neighbours = grep { $_->{distance_to_root} == 0 } map { @{$_->{neighbours}} } @neighbours;
788 last if !@neighbours;
789 }
790 @falling = difference2($sticked_bubbles{$player}, \@still_sticked);
791 @{$sticked_bubbles{$player}} = difference2($sticked_bubbles{$player}, \@falling);
792
793 #- chain-reaction on falling bubbles
794 if ($chainreaction) {
795 my @falling_colors = map { $_->{img} } @falling;
796 #- optimize a bit by first calculating bubbles that are next to another bubble of the same color
797 my @grouped_bubbles = grep {
798 my $b = $_;
799 member($b->{img}, @falling_colors) && any { $b->{img} eq $_->{img} } @{$b->{neighbours}}
800 } @{$sticked_bubbles{$player}};
801 if (@grouped_bubbles) {
802 #- all positions on which we can't chain-react
803 my @occupied_positions = map { $_->{cy}*8 + $_->{cx} } @{$sticked_bubbles{$player}};
804 push @occupied_positions, map { $_->{chaindestcy}*8 + $_->{chaindestcx} } @{$chains{$player}{falling_chained}};
805 #- examine groups beginning at the root bubbles, for the case in which
806 #- there is a group that will fall from an upper chain-reaction
807 foreach my $pos (sort { $a->{distance_to_root} <=> $b->{distance_to_root} } @grouped_bubbles) {
808 #- now examine if there is a free position to chain-react in it
809 foreach my $npos (next_positions($pos, $player)) {
810 #- we can't chain-react somewhere if it explodes a group already chained
811 next if any { $pos->{cx} == $_->{cx} && $pos->{cy} == $_->{cy} }
812 map { @{$chains{$player}{chained_bubbles}{$_}}} keys %{$chains{$player}{chained_bubbles}};
813 if (!member($npos->[1]*8 + $npos->[0], @occupied_positions)) {
814 #- find a suitable falling bubble for that free position
815 foreach my $falling (@falling) {
816 next if member($falling, @{$chains{$player}{falling_chained}});
817 if ($pos->{img} eq $falling->{img}) {
818 ($falling->{chaindestcx}, $falling->{chaindestcy}) = ($npos->[0], $npos->[1]);
819 ($falling->{chaindestx}, $falling->{chaindesty}) = calc_real_pos_given_arraypos($npos->[0], $npos->[1], $player);
820 push @{$chains{$player}{falling_chained}}, $falling;
821 push @occupied_positions, $npos->[1]*8 + $npos->[0];
822
823 #- next lines will allow not to chain-react on the same group from two different positions,
824 #- and even to not chain-react on a group that will itself fall from a chain-reaction
825 @{$falling->{neighbours}} = grep { bubble_next_to($_->{cx}, $_->{cy}, $npos->[0], $npos->[1], $player) } @{$sticked_bubbles{$player}};
826 my @chained_bubbles = find_bubble_group($falling);
827 $_->{mark} = 0 foreach @{$sticked_bubbles{$player}};
828 my @still_sticked;
829 my @neighbours = difference2($root_bubbles{$player}, \@chained_bubbles);
830 while (1) {
831 $_->{mark} = 1 foreach @neighbours;
832 push @still_sticked, @neighbours;
833 @neighbours = difference2([ grep { $_->{mark} == 0 } map { @{$_->{neighbours}} } @neighbours ],
834 \@chained_bubbles);
835 last if !@neighbours;
836 }
837 @{$chains{$player}{chained_bubbles}{$falling}} = difference2($sticked_bubbles{$player}, \@still_sticked);
838 last;
839 }
840 }
841 }
842 }
843 }
844 #- now examine all chaining bubbles. for each one, check that consequences of all other chaining bubbles
845 #- do not cancel it. start by the lowest falling as they are likely to be the first to reach destination.
846 foreach my $falling (sort { $b->{cy} <=> $a->{cy} } @falling) {
847 next if !exists $falling->{chaindestx};
848 #- is this chain still possible, given all the other chains?
849 #- first calculate all other chained
850 my @other_chained_bubbles;
851 foreach my $falling2 (@falling) {
852 next if $falling eq $falling2 || !exists $falling2->{chaindestx};
853 push @other_chained_bubbles, find_bubble_group($falling2);
854 }
855 #- second calculate the still sticked bubbles given all other chained bubbles removed,
856 #- and check if this chain is still possible
857 $_->{mark} = 0 foreach @{$sticked_bubbles{$player}};
858 my @still_sticked;
859 my @neighbours = difference2($root_bubbles{$player}, \@other_chained_bubbles);
860 while (1) {
861 $_->{mark} = 1 foreach @neighbours;
862 push @still_sticked, @neighbours;
863 @neighbours = difference2([ grep { $_->{mark} == 0 } map { @{$_->{neighbours}} } @neighbours ],
864 \@other_chained_bubbles);
865 last if !@neighbours;
866 }
867 my @chained_bubbles = grep { member($_, @still_sticked) } find_bubble_group($falling);
868 if (@chained_bubbles < 2) {
869 #- ok then, suppress this one
870 delete $falling->{chaindestx};
871 }
872 }
873 }
874 }
875
876 #- prepare falling bubbles
877 if ($graphics_level > 1 || $chainreaction) {
878 my $max_cy_falling = fold_left { $::b->{cy} > $::a ? $::b->{cy} : $::a } 0, @falling; #- I have a fold_left in my prog! :-)
879 my ($shift_on_same_line, $line) = (0, $max_cy_falling);
880 foreach (sort { $b->{cy}*8 + $b->{cx} <=> $a->{cy}*8 + $a->{cx} } @falling) { #- sort bottom-to-up / right-to-left
881 $line != $_->{cy} and $shift_on_same_line = 0;
882 $line = $_->{cy};
883 $_->{wait_fall} = ($max_cy_falling - $_->{cy})*5 + $shift_on_same_line;
884 $shift_on_same_line++;
885 $_->{speed} = 0;
886 }
887 push @{$falling_bubble{$player}}, @falling;
888 }
889
890 remove_images_from_background($player, @will_destroy, @falling);
891 #- redraw neighbours because parts of neighbours have been erased by previous statement
892 put_image_to_background($_->{img}, $_->{'x'}, $_->{'y'})
893 foreach grep { !member($_, @will_destroy) && !member($_, @falling) } fastuniq(map { @{$_->{neighbours}} } @will_destroy, @falling);
894 $need_redraw = 1;
895 }
896
897 if ($count_for_root) {
898 $pdata{$player}{newroot}++;
899 if ($pdata{$player}{newroot} == $TIME_APPEARS_NEW_ROOT-1) {
900 $pdata{$player}{newroot_prelight} = 2;
901 $pdata{$player}{newroot_prelight_step} = 0;
902 }
903 if ($pdata{$player}{newroot} == $TIME_APPEARS_NEW_ROOT) {
904 $pdata{$player}{newroot_prelight} = 1;
905 $pdata{$player}{newroot_prelight_step} = 0;
906 }
907 if ($pdata{$player}{newroot} > $TIME_APPEARS_NEW_ROOT) {
908 my $_1p_mode = is_1p_game() && $levels{current} ne 'mp_train';
909 $need_redraw = 1;
910 $pdata{$player}{newroot_prelight} = 0;
911 play_sound($_1p_mode ? 'newroot_solo' : 'newroot');
912 $pdata{$player}{newroot} = 0;
913 $pdata{$player}{oddswap} = !$pdata{$player}{oddswap};
914 remove_images_from_background($player, @{$sticked_bubbles{$player}});
915 foreach (@{$sticked_bubbles{$player}}) {
916 $_->{'cy'}++;
917 calc_real_pos($_, $player);
918 }
919 foreach (@{$falling_bubble{$player}}) {
920 exists $_->{chaindestx} or next;
921 $_->{chaindestcy}++;
922 $_->{chaindesty} += $ROW_SIZE;
923 }
924 put_allimages_to_background($player);
925 if ($_1p_mode) {
926 $pdata{$player}{newrootlevel}++;
927 print_compressor();
928 } else {
929 @{$root_bubbles{$player}} = ();
930 real_stick_bubble(create_bubble_given_img_num($pdata{$player}{nextcolors}[$_]), $_, 0, $player, 0) foreach (0..(7-$pdata{$player}{oddswap}));
931 delete $pdata{$player}{nextcolors};
932 }
933 }
934 }
935
936 if ($need_redraw) {
937 my $malus_val = @will_destroy + @falling - 2;
938 $malus_val > 0 && !is_mp_game() and $malus_val += ($player eq 'p1' ? $playermalus : -$playermalus);
939 $malus_val < 0 and $malus_val = 0;
940 SDL::Video::blit_surface($background, $apprects{$player}, $app, $apprects{$player});
941 malus_change($malus_val, $player);
942 }
943 }
944
945 sub redraw_chat_message_if_needed {
946 my ($player) = @_;
947 if ($pdata{current_chat_messages}{$player}) {
948 my $img = @PLAYERS == 2 ? $imgbin{void_chat_small_p2} : member($player, qw(rp1 rp3)) ? $imgbin{void_chat_small_rp1_rp3} : $imgbin{void_chat_small_rp2_rp4};
949 put_image_to_background($img, $POS{$player}{chatting}{x}, $POS{$player}{chatting}{'y'});
950 print_('ingame_small_chat', $background,
951 $POS{$player}{chatting}{x} + 3, $POS{$player}{chatting}{'y'} + 3, $pdata{current_chat_messages}{$player}, $img->w - 6, 'center');
952 erase_image($img, $POS{$player}{chatting}{x}, $POS{$player}{chatting}{'y'});
953 }
954 }
955
956 sub print_next_bubble($$;$) {
957 my ($img, $player, $not_on_top_next) = @_;
958 if (is_mp_game() && $player eq 'p1' && $pdata{p1}{chatting}) {
959 return;
960 }
961 put_image_to_background($img, $next_bubble{$player}{'x'}, $next_bubble{$player}{'y'});
962 $not_on_top_next or put_image_to_background($bubbles_anim{on_top_next},
963 $POS{$player}{left_limit} + $POS{$player}{next_bubble}{x} + $POS{$player}{on_top_next_relpos}{x},
964 $POS{$player}{next_bubble}{'y'} + $POS{$player}{on_top_next_relpos}{'y'});
965 redraw_chat_message_if_needed($player);
966 }
967
968 sub generate_new_bubble($$) {
969 my ($player, $num) = @_;
970 $tobe_launched{$player} = $next_bubble{$player};
971 $tobe_launched{$player}{'x'} = ($POS{$player}{left_limit}+$POS{$player}{right_limit})/2 - $BUBBLE_SIZE/2;
972 $tobe_launched{$player}{'y'} = $POS{$player}{'initial_bubble_y'};
973 $next_bubble{$player} = create_bubble_given_img_num($num);
974 $next_bubble{$player}{'x'} = $POS{$player}{left_limit}+$POS{$player}{next_bubble}{x}; #- necessary to keep coordinates, for verify_if_end
975 $next_bubble{$player}{'y'} = $POS{$player}{next_bubble}{'y'};
976 print_next_bubble($next_bubble{$player}{img}, $player);
977 }
978
979
980 #- ----------- game stuff -------------------------------------------------
981
982 our $smg_lineheight = 16;
983
984 sub mp_train_time_left {
985 my $seconds = 120.99 - (($recorddata{frame} * $TARGET_ANIM_SPEED) / 1000);
986 $seconds < 0 and $seconds = 0;
987 return $seconds;
988 }
989
990 our ($mp_train_xpos, $mp_train_ypos) = (32, 177);
991 sub mp_train_print_time {
992 my $drect = SDL::Rect->new($mp_train_xpos, $mp_train_ypos, $imgbin{void_mp_training}->w, 30);
993 my $seconds = mp_train_time_left();
994 my $m = int($seconds/60);
995 my $s = int($seconds-$m*60); length($s) == 1 and $s = "0$s";
996 print_('ingame', $background, $mp_train_xpos, $mp_train_ypos, loc("%s'%s\"", i18n_number($m), i18n_number($s)), $imgbin{void_mp_training}->w, 'center');
997 }
998
999 sub handle_progress($) {
1000 my ($p) = @_;
1001 if (defined($pdata{$p}{newrootlast})) {
1002 if ($pdata{$p}{newroot} != $pdata{$p}{newrootlast}) {
1003 my $height = $imgbin{progress_red}->h + 1;
1004 my $xpos = $POS{$p}{progress}{x};
1005 my $ypos = $POS{$p}{progress}{y};
1006 put_image_to_background($imgbin{progress_green}, $xpos, $ypos + $pdata{$p}{newrootlast}*$height);
1007 put_image_to_background($imgbin{progress_red}, $xpos, $ypos + $pdata{$p}{newroot}*$height);
1008 $pdata{$p}{newrootlast} = $pdata{$p}{newroot};
1009 }
1010
1011 } else {
1012 my $height = $imgbin{progress_red}->h + 1;
1013 my $xpos = $POS{$p}{progress}{x};
1014 my $ypos = $POS{$p}{progress}{y};
1015 $pdata{$p}{newrootlast} = 0;
1016 push @update_rects, SDL::Rect->new($xpos, $ypos, $imgbin{progress_red}->w, $height*(1 + $TIME_APPEARS_NEW_ROOT));
1017 for (my $i = 0; $i <= $TIME_APPEARS_NEW_ROOT; $i++) {
1018 put_image_to_background($imgbin{$i ? "progress_green" : "progress_red"}, $xpos, $ypos + $i*$height);
1019 }
1020 }
1021 }
1022
1023 sub handle_graphics($) {
1024 my ($fun) = @_;
1025
1026 iter_players {
1027 $pdata{$::p}{state} eq 'left' and next; #- remote players already left in a previous subgame in mp game
1028 #- bubbles
1029 foreach ($launched_bubble{$::p}, if_($fun ne \&erase_image, $tobe_launched{$::p})) {
1030 $_ and $fun->($_->{img}, $_->{'x'}, $_->{'y'});
1031 }
1032 if ($fun eq \&put_image && $pdata{$::p}{newroot_prelight}) {
1033 if ($pdata{$::p}{newroot_prelight_step}++ > 30*$pdata{$::p}{newroot_prelight}) {
1034 $pdata{$::p}{newroot_prelight_step} = 0;
1035 }
1036 if ($pdata{$::p}{newroot_prelight_step} <= 8) {
1037 my $hurry_overwritten = 0;
1038 foreach my $b (@{$sticked_bubbles{$::p}}) {
1039 next if ($graphics_level == 1 && $b->{'cy'} > 0); #- in low graphics, only prelight first row
1040 $b->{'cx'}+1 == $pdata{$::p}{newroot_prelight_step} and put_image($b->{img}, $b->{'x'}, $b->{'y'});
1041 $b->{'cx'} == $pdata{$::p}{newroot_prelight_step} and put_image($bubbles_anim{white}, $b->{'x'}, $b->{'y'});
1042 $b->{'cy'} > 6 and $hurry_overwritten = 1;
1043 }
1044 $hurry_overwritten && $pdata{$::p}{hurry_save_img} and print_hurry($::p, 1); #- hurry was potentially overwritten
1045 }
1046 }
1047 if ($sticking_bubble{$::p} && $graphics_level > 1) {
1048 my $b = $sticking_bubble{$::p};
1049 if ($fun eq \&erase_image) {
1050 put_image($b->{img}, $b->{'x'}, $b->{'y'});
1051 } else {
1052 if ($pdata{$::p}{sticking_step} == @{$bubbles_anim{stick}}) {
1053 $sticking_bubble{$::p} = undef;
1054 } else {
1055 put_image(${$bubbles_anim{stick}}[$pdata{$::p}{sticking_step}], $b->{'x'}, $b->{'y'});
1056 if ($pdata{$::p}{sticking_step_slowdown}) {
1057 $pdata{$::p}{sticking_step}++;
1058 $pdata{$::p}{sticking_step_slowdown} = 0;
1059 } else {
1060 $pdata{$::p}{sticking_step_slowdown}++;
1061 }
1062 }
1063 }
1064 }
1065
1066 #- shooter
1067 if ($graphics_level > 1) {
1068 my $num = int($angle{$::p}*$CANON_ROTATIONS_NB/($PI/2) + 0.5)-$CANON_ROTATIONS_NB;
1069 $fun->($canon{mini_graphics($::p) ? 'img_mini' : 'img'}{$num},
1070 $POS{$::p}{canon}{x} + $canon{mini_graphics($::p) ? 'data_mini' : 'data'}{$num}->[0],
1071 $POS{$::p}{canon}{'y'} + $canon{mini_graphics($::p) ? 'data_mini' : 'data'}{$num}->[1]);
1072 } else {
1073 $fun->($shooter_lowgfx,
1074 $POS{$::p}{simpleshooter}{x} + $POS{$::p}{simpleshooter}{diameter}*cos($angle{$::p}),
1075 $POS{$::p}{simpleshooter}{'y'} - $POS{$::p}{simpleshooter}{diameter}*sin($angle{$::p}));
1076 }
1077
1078 #- penguins
1079 if (!is_mp_game() || $::p ne 'p1' || !$pdata{p1}{chatting}) {
1080 if ($graphics_level == 3) {
1081 my $player = @PLAYERS == 2 && $::p eq 'rp1' ? 'p2' : $::p;
1082 $fun->($pinguin{$player}{$pdata{$::p}{ping_right}{state}}[$pdata{$::p}{ping_right}{img}],
1083 $POS{$player}{left_limit}+$POS{$player}{pinguin}{x}, $POS{$player}{pinguin}{'y'});
1084 }
1085 }
1086
1087 handle_progress($::p);
1088
1089 #- chat message in mp
1090 if (is_mp_game() && $pdata{$::p}{chat_msg_delay}) {
1091 $pdata{$::p}{chat_msg_delay}--;
1092 if (!$pdata{$::p}{chat_msg_delay}) {
1093 my $img = @PLAYERS == 2 ? $imgbin{void_chat_small_p2} : member($::p, qw(rp1 rp3)) ? $imgbin{void_chat_small_rp1_rp3} : $imgbin{void_chat_small_rp2_rp4};
1094 remove_image_from_background($img, $POS{$::p}{chatting}{x}, $POS{$::p}{chatting}{'y'});
1095 $pdata{current_chat_messages}{$::p} = undef;
1096 print_next_bubble($next_bubble{$::p}{img}, $::p);
1097 if (member($::p, 'rp3', 'rp4')) {
1098 print_scores($background);
1099 print_scores($app);
1100 }
1101 }
1102 }
1103
1104 #- moving bubbles --> I want them on top of the rest
1105 foreach (@{$malus_bubble{$::p}}, @{$falling_bubble{$::p}}, @{$exploding_bubble{$::p}}) {
1106 $fun->($_->{img}, $_->{'x'}, $_->{'y'});
1107 }
1108
1109 };
1110
1111 if ($levels{current} eq 'mp_train' && $pdata{state} eq 'game') {
1112 if ($fun ne \&erase_image) {
1113 my $drect = SDL::Rect->new($mp_train_xpos, $mp_train_ypos, $imgbin{void_mp_training}->w, 30);
1114 SDL::Video::blit_surface($background_orig, $drect, $background, $drect);
1115 mp_train_print_time();
1116 SDL::Video::blit_surface($background, $drect, $app, $drect);
1117 push @update_rects, $drect;
1118 my $seconds = mp_train_time_left();
1119 if ($seconds == 0) {
1120 put_image($imgbin{void_panel}, $MENUPOS{xpos_panel}, $MENUPOS{ypos_panel});
1121 my $y = $MENUPOS{ypos_panel} + 30;
1122 my @messages = ('', '', '', '', loc("Your score after two minutes:"), '', $pdata{p1}{score}, '', loc("Press any key."));
1123 foreach (@messages) {
1124 print_('menu', $app, $MENUPOS{xpos_panel}, $y, $_, $imgbin{void_panel}->w, 'center');
1125 $y += $smg_lineheight;
1126 }
1127 SDL::Video::update_rect($app, 0, 0, 0, 0);
1128 play_sound('cancel');
1129 Games::FrozenBubble::CStuff::fbdelay(1000);
1130 SDL::Events::pump_events() while SDL::Events::poll_event($event) != 0;
1131 grab_key() eq SDLK_ESCAPE() and die 'quit';
1132 handle_new_hiscores();
1133 die 'new_game';
1134 }
1135 }
1136 }
1137 }
1138
1139 #- extract it from "handle_graphics" to optimize a bit animations
1140 sub update_malus($$) {
1141 my ($fun, $p) = @_;
1142 my $malus_nb = @{$pdata{$p}{malus}};
1143 my $y_shift = 0;
1144 while ($malus_nb > 0) {
1145 my $print = sub($) {
1146 my ($type) = @_;
1147 my $type_real = translate_mini_image($type);
1148 $fun->($type, $POS{$p}{malus}{x} - $type_real->w/2, $POS{$p}{malus}{'y'} - $y_shift - $type_real->h);
1149 $y_shift += $type_real->h - 1;
1150 };
1151 if ($malus_nb >= 7) {
1152 $print->($malus_gfx{tomate});
1153 $malus_nb -= 7;
1154 } else {
1155 $print->($malus_gfx{banane});
1156 $malus_nb--;
1157 }
1158 }
1159 }
1160
1161 sub malus_change($$) {
1162 my ($numb, $player) = @_;
1163 return if $numb == 0 || is_1p_game() && $levels{current} ne 'mp_train';
1164 if ($levels{current} eq 'mp_train' && $numb > 0) {
1165 $pdata{p1}{score} += $numb;
1166 print_scores($app);
1167 print_scores($background);
1168 return;
1169 }
1170 if ($numb > 0) {
1171 #- malus are adding up
1172 if (!is_mp_game()) {
1173 iter_players_ {
1174 if ($::p_ ne $player) {
1175 update_malus(\&remove_image_from_background, $::p_);
1176 push @{$pdata{$::p_}{malus}}, ($frame) x $numb;
1177 update_malus(\&put_image_to_background, $::p_);
1178 }
1179 };
1180
1181 } else {
1182 if (is_local_player($player)) { #- remote players handled when receiving the 'g' message
1183 if (!$pdata{sendmalustoone}) {
1184 my @living = living_players();
1185 if (@living > 1) {
1186 $numb = int($numb/(@living-1) + 0.99);
1187 iter_players_ {
1188 if ($::p_ ne $player && member($::p_, @living)) {
1189 is_mp_game() and Games::FrozenBubble::Net::gsend("g$pdata{$::p_}{nick}:$numb");
1190 update_malus(\&remove_image_from_background, $::p_);
1191 push @{$pdata{$::p_}{malus}}, ($frame) x $numb;
1192 update_malus(\&put_image_to_background, $::p_);
1193 }
1194 };
1195 }
1196 } else {
1197 my $p = $pdata{sendmalustoone};
1198 is_mp_game() and Games::FrozenBubble::Net::gsend("g$pdata{$p}{nick}:$numb");
1199 iter_players_ { #- get mini graphics
1200 if ($::p_ eq $p) {
1201 update_malus(\&remove_image_from_background, $::p_);
1202 push @{$pdata{$::p_}{malus}}, ($frame) x $numb;
1203 update_malus(\&put_image_to_background, $::p_);
1204 }
1205 };
1206 }
1207 }
1208 }
1209 } else {
1210 #- malus are decreasing
1211 update_malus(\&remove_image_from_background, $player);
1212 shift @{$pdata{$player}{malus}} while $numb++;
1213 update_malus(\&put_image_to_background, $player);
1214 }
1215 }
1216
1217 sub print_compressor() {
1218 my $x = $POS{compressor_xpos};
1219 my $y = $POS{p1}{top_limit} + $pdata{$PLAYERS[0]}{newrootlevel} * $ROW_SIZE;
1220 my ($comp_main, $comp_ext) = ($imgbin{compressor_main}, $imgbin{compressor_ext});
1221
1222 my $drect = SDL::Rect->new($x - $comp_main->w/2, 0, $comp_main->w, $y);
1223 SDL::Video::blit_surface($background_orig, $drect, $background, $drect);
1224 $display_on_app_disabled or SDL::Video::blit_surface($background_orig, $drect, $app, $drect);
1225 push @update_rects, $drect;
1226
1227 put_image_to_background($comp_main, $x - $comp_main->w/2, $y - $comp_main->h);
1228
1229 $y -= $comp_main->h - 3;
1230
1231 while ($y > 0) {
1232 put_image_to_background($comp_ext, $x - $comp_ext->w/2, $y - $comp_ext->h);
1233 $y -= $comp_ext->h;
1234 }
1235 }
1236
1237 sub print_ {
1238 my ($kind, $surface, $x, $y, $text, $size, $alignment, $callback) = @_;
1239 printf("print_: " . join(' ', (caller(1))) . " $text\n") if $ENV{FB_DEBUG};
1240 exists $pangocontext{$kind} or die "$kind is no kind\n";
1241 if ($size) {
1242 #- instead of segfaulting
1243 my $minsize = width($kind, $text);
1244 if ($minsize > $size) {
1245 $size = $minsize;
1246 }
1247 }
1248 my $surf = Games::FrozenBubble::CStuff::sdlpango_draw_givenalignment($pangocontext{$kind}{context_bg}, $text, $size || -1, $alignment || 'left');
1249 if ($callback) {
1250 if (!$callback->('about-to-draw', $surf)) {
1251 #- callback said do not draw
1252 return;
1253 }
1254 }
1255 SDL::Video::blit_surface($surf, SDL::Rect->new(0, 0, $surf->w, $surf->h), $surface, SDL::Rect->new($x + 1, $y + 1, $surf->w, $surf->h));
1256 $surf = Games::FrozenBubble::CStuff::sdlpango_draw_givenalignment($pangocontext{$kind}{context_fg}, $text, $size || -1, $alignment || 'left');
1257 #printf("sdlpango_draw_givenalignment: %s, %s, %s, %s\n", $kind, $text, $size || -1, $alignment || 'left');
1258 #printf("SDL::Rect->new($x, $y, " . $surf->w . ", " . $surf->h . ")\n");
1259 SDL::Video::blit_surface($surf, SDL::Rect->new(0, 0, $surf->w, $surf->h), $surface, SDL::Rect->new($x, $y, $surf->w, $surf->h));
1260 }
1261
1262 sub width {
1263 my ($kind, $text) = @_;
1264 exists $pangocontext{$kind} or die "$kind is no kind\n";
1265 my $size = Games::FrozenBubble::CStuff::sdlpango_getsize($pangocontext{$kind}{context_fg}, $text, -1);
1266 return $size->[0];
1267 }
1268
1269 sub mp_disconnect_with_reason {
1270 my (@messages) = @_;
1271 put_image($imgbin{void_panel}, $MENUPOS{xpos_panel}, $MENUPOS{ypos_panel});
1272 my $y = $MENUPOS{ypos_panel} + 30;
1273 foreach (@messages) {
1274 print_('menu', $app, $MENUPOS{xpos_panel} + 10, $y, $_, $imgbin{void_panel}->w - 20, 'center');
1275 $y += $smg_lineheight;
1276 }
1277 SDL::Video::update_rect($app, 0, 0, 0, 0);
1278 play_sound('cancel');
1279 Games::FrozenBubble::CStuff::fbdelay(2000);
1280 SDL::Events::pump_events() while SDL::Events::poll_event($event) != 0;
1281 grab_key();
1282 die 'quit';
1283 }
1284
1285 sub check_mp_connection {
1286 if (!Games::FrozenBubble::Net::isconnected()) {
1287 if ($pdata{gametype} eq 'lan') {
1288 mp_disconnect_with_reason('', '', '', '', loc("Lost connection to server!"), '', loc("Hoster aborted the game."));
1289 } else {
1290 mp_disconnect_with_reason('', '', '', '', loc("Lost connection to server!"), '', loc("Your lag is probably too high."));
1291 }
1292 }
1293 }
1294
1295 sub update_say_mp {
1296 put_image($imgbin{void_chat}, $POS{p1}{chatting}{x}, $POS{p1}{chatting}{'y'});
1297 callback_entry('print', { xpos => $POS{p1}{chatting}{x} + 15, ypos => $POS{p1}{chatting}{'y'} + 5, font => 'ingame_chat', maxlen => $imgbin{void_chat}->w - 30 });
1298 push @update_rects, $apprects{main};
1299 }
1300
1301 sub cleanup_chatting {
1302 $pdata{p1}{chatting} = 0;
1303 SDL::Events::enable_key_repeat(0, 0);
1304 remove_image_from_background($imgbin{void_chat}, $POS{p1}{chatting}{x}, $POS{p1}{chatting}{'y'});
1305 print_next_bubble($next_bubble{p1}{img}, 'p1');
1306 redraw_attackingme();
1307 }
1308
1309 sub set_sendmalustoone {
1310 my ($whoto) = @_;
1311 $pdata{sendmalustoone} = undef;
1312 iter_distant_players_ {
1313 remove_image_from_background($imgbin{attack}{$::p_}, $POS{$::p_}{attack}{x}, $POS{$::p_}{attack}{'y'});
1314 };
1315 if (member($whoto, living_players()) && $pdata{p1}{state} ne 'lost') {
1316 $pdata{sendmalustoone} = $whoto;
1317 put_image_to_background($imgbin{attack}{$pdata{sendmalustoone}}, $POS{$pdata{sendmalustoone}}{attack}{x}, $POS{$pdata{sendmalustoone}}{attack}{'y'});
1318 }
1319 if ($pdata{protocollevel} >= 1) {
1320 Games::FrozenBubble::Net::gsend("A$pdata{$pdata{sendmalustoone}}{nick}");
1321 }
1322 }
1323
1324 sub redraw_attackingme {
1325 $pdata{p1}{chatting} and return;
1326 my $xpos = $POS{p1}{attackme}{x};
1327 my $drect = SDL::Rect->new($xpos, $POS{p1}{attackme}{'y'}, 3*24 + $imgbin{attackme}{rp1}->w, $imgbin{attackme}{rp1}->h);
1328 SDL::Video::blit_surface($background_orig, $drect, $background, $drect);
1329 SDL::Video::blit_surface($background_orig, $drect, $app, $drect);
1330 push @update_rects, $drect;
1331 foreach my $attackingme (@{$pdata{attackingme}}) {
1332 put_image_to_background($imgbin{attackme}{$attackingme}, $xpos, $POS{p1}{attackme}{'y'});
1333 $xpos += 24;
1334 }
1335 }
1336
1337 sub handle_mp_messages {
1338 my ($msg) = @_;
1339
1340 #- in order to keep ordering of actions executed in update_game, we must tolerate only one action at a time
1341 my $check_action_possible = sub {
1342 my ($m, $player) = @_;
1343 #- we check also the presence of malus bubbles, because if the malus order has lagged much
1344 #- we might receive a fire or even a stick command before the malus bubbles are sticked,
1345 #- this would provoke a local inconsistency; same for chain reacted bubbles not finished yet
1346 if ($actions{$player}{mp_fire}
1347 || $actions{$player}{mp_stick}
1348 || @{$malus_bubble{$player}}
1349 || $chainreaction && any { exists $_->{chaindestx} } @{$falling_bubble{$player}}) {
1350 unshift @$msg, $m;
1351 return 0;
1352 } else {
1353 return 1;
1354 }
1355 };
1356
1357 my %latestangle = (); #- for smoothing, need to handle last angle only
1358
1359 while (@$msg) {
1360 my $m = shift @$msg;
1361 my $player = $pdata{id2p}{$m->{id}};
1362 if (!$player) {
1363 printf "Network protocol error: player with id '%d' doesn't exist. You're not a regular Frozen-Bubble client, aren't you?\n", ord($m->{id});
1364 die 'quit';
1365 }
1366 if ($pdata{$player}{left}) {
1367 print STDERR "$pdata{$player}{nick}: you don't exist (anymore), go away!\n";
1368 next;
1369 }
1370 my ($command, $params) = $m->{msg} =~ /^(.)(.*)/;
1371 dbgnet("message received: from=$player message=$m->{msg}");
1372 if ($command eq 'l') {
1373 iter_players { #- need iter_players to get the small graphics change for free
1374 if ($::p eq $player) {
1375 $pdata{$::p}{left} = 1;
1376 $pdata{$::p}{still_game_messages} = 0;
1377 lose($::p);
1378 }
1379 };
1380 } elsif ($command eq 'f') {
1381 $check_action_possible->($m, $player) or last;
1382 $actions{$player}{mp_fire} = 1;
1383 ($angle{$player}, $pdata{$player}{nextcolor}) = $params =~ /(.+):(.+)/;
1384 } elsif ($command eq 'r') {
1385 $actions{$player}{left} = 0;
1386 $actions{$player}{right} = 0;
1387 $actions{$player}{center} = 0;
1388 if ($params eq 'l') {
1389 $actions{$player}{left} = 1;
1390 } elsif ($params eq 'r') {
1391 $actions{$player}{right} = 1;
1392 } elsif ($params eq 'c') {
1393 $actions{$player}{center} = 1;
1394 }
1395 } elsif ($command eq 'a') {
1396 $latestangle{$player} = $params;
1397 } elsif ($command eq 's') {
1398 $check_action_possible->($m, $player) or last;
1399 #- we can't rely on locally animated launched bubble, to ensure game
1400 #- consistency we transmit stick positions
1401 $actions{$player}{mp_stick} = 1;
1402 ($pdata{$player}{stickcx}, $pdata{$player}{stickcy}, $pdata{$player}{stickcol}, my $newrootcols) = $params =~ /(.+):(.+):(.+):(.*)/;
1403 @{$pdata{$player}{nextcolors}} = split / /, $newrootcols;
1404 } elsif ($command eq 'g') {
1405 my ($destplayer, $numb) = $params =~ /(.+):(.+)/;
1406 iter_players {
1407 if ($pdata{$::p}{nick} eq $destplayer) {
1408 update_malus(\&remove_image_from_background, $::p);
1409 push @{$pdata{$::p}{malus}}, ($frame) x $numb;
1410 update_malus(\&put_image_to_background, $::p);
1411 }
1412 };
1413 } elsif ($command eq 'm') {
1414 #- we may receive new malus bubbles after a distant player is dead already
1415 #- ignore them instead of wrongly overlaying frozen bubbles
1416 if ($pdata{$player}{state} eq 'ingame') {
1417 my ($num, $cx, $cy, $sticky) = $params =~ /(.+):(.+):(.+):(.+)/;
1418 my $b = create_bubble_given_img_num($num);
1419 $b->{cx} = $cx;
1420 $b->{cy} = $cy;
1421 $b->{'stick_y'} = $sticky;
1422 iter_players { #- need iter_players to get the small graphics change for free
1423 if ($::p eq $player) {
1424 calc_real_pos($b, $::p);
1425 push @{$malus_bubble{$player}}, $b;
1426 malus_change(-1, $player);
1427 }
1428 };
1429 }
1430 } elsif ($command eq 'M') {
1431 my ($cx, $sticky) = $params =~ /(.+):(.+)/;
1432 #- if network cuts several malussticks in two parts, it's possible that
1433 #- one malusstick from the first part trigger a lose; at next game run,
1434 #- the player has lost and his malus bubbles were cleaned up, so malusstick
1435 #- is not possible, but this is no big deal
1436 if ($pdata{$player}{state} eq 'ingame') {
1437 foreach (@{$malus_bubble{$player}}) {
1438 if ($_->{cx} == $cx && $_->{'stick_y'} == $sticky) {
1439 $_->{mp_stick} = 1;
1440 goto ok_malusstick;
1441 }
1442 }
1443 die "could not find malus bubble to malusstick!\n";
1444 ok_malusstick:
1445 }
1446 } elsif ($command eq 'F') {
1447 #- this is coming too soon. it needs to be collected in the algo to restart a game.
1448 unshift @$msg, $m;
1449 last;
1450 } elsif ($command eq 't') {
1451 $pdata{current_chat_messages}{$player} = $params;
1452 $pdata{$player}{chat_msg_delay} = 500;
1453 play_sound('chatted');
1454 redraw_chat_message_if_needed($player);
1455 push @update_rects, $apprects{main};
1456 } elsif ($command eq 'A') {
1457 if ($params eq '') {
1458 @{$pdata{attackingme}} = difference2($pdata{attackingme}, [ $player ]);
1459 } else {
1460 if ($params eq $pdata{p1}{nick}) {
1461 if (!member($player, @{$pdata{attackingme}})) {
1462 push @{$pdata{attackingme}}, $player;
1463 }
1464 } else {
1465 @{$pdata{attackingme}} = difference2($pdata{attackingme}, [ $player ]);
1466 }
1467 }
1468 redraw_attackingme();
1469 } else {
1470 print STDERR "****** Unrecognized command: $m->{msg}\n";
1471 }
1472 }
1473
1474 foreach my $player (keys %latestangle) {
1475 #- try to smoothen on network lag
1476 my $difference = $latestangle{$player} - $angle{$player};
1477 if (abs($difference) > 0.15) {
1478 #- we're lagging. ignore that to prevent jerks. hope this is temporary.
1479 #- I know this will behave bad on high lags but hey I can't do no miracle buddy.
1480 } else {
1481 #- we're not lagging so much. but smoothen it up.
1482 $angle{$player} += $difference / 2;
1483 }
1484 }
1485
1486 }
1487
1488 sub handle_whenever_events {
1489 my ($keypressed) = @_;
1490
1491 if ($keypressed eq $KEYS->{misc}{fs}) {
1492 $fullscreen = !$fullscreen;
1493 SDL::Video::wm_toggle_fullscreen($app);
1494 }
1495 if ($keypressed eq $KEYS->{misc}{toggle_sound}) {
1496 if (!$mixer_enabled) {
1497 if ($mixer || init_sound()) {
1498 $mixer_enabled = 1;
1499 play_music($current_theoretical_music);
1500 }
1501 } else {
1502 if ($mixer_enabled && $mixer && SDL::Mixer::Music::playing_music) {
1503 SDL::delay(10) while SDL::Mixer::Music::fading_music; #- mikmod will deadlock if we try to fade_out while still fading in
1504 SDL::Mixer::Music::playing_music and SDL::Mixer::Music::halt_music;
1505 SDL::delay(10) while SDL::Mixer::Music::playing_music; #- mikmod will segfault if we try to load a music while old one is still fading out
1506 }
1507 $mixer_enabled = 0;
1508 }
1509 }
1510 if ($mixer_enabled && $mixer && $keypressed eq $KEYS->{misc}{toggle_music}) {
1511 if ($music_disabled) {
1512 $music_disabled = undef;
1513 play_music($current_theoretical_music);
1514 } else {
1515 $music_disabled = 1;
1516 SDL::Mixer::Music::halt_music;
1517 }
1518 }
1519 if ($mixer_enabled && $mixer && @playlist && $keypressed eq $KEYS->{misc}{next_playlist_elem}) {
1520 SDL::Mixer::Music::halt_music;
1521 play_music('dummy');
1522 }
1523 if ($mixer_enabled && $mixer && $keypressed eq $KEYS->{misc}{raise_volume}) {
1524 my $to = int(min(SDL::Mixer::Music::volume_music(-1) + SDL::Mixer::MIX_MAX_VOLUME()/10, SDL::Mixer::MIX_MAX_VOLUME()));
1525 SDL::Mixer::Music::volume_music($to);
1526 SDL::Mixer::Channels::volume(-1, $to);
1527 }
1528 if ($mixer_enabled && $mixer && $keypressed eq $KEYS->{misc}{lower_volume}) {
1529 my $to = int(max(SDL::Mixer::Music::volume_music(-1) - SDL::Mixer::MIX_MAX_VOLUME()/10, 0));
1530 SDL::Mixer::Music::volume_music($to);
1531 SDL::Mixer::Channels::volume(-1, $to);
1532 }
1533 }
1534
1535 sub handle_game_events() {
1536
1537 if ($levels{current} eq 'mp_train' && @{$malus_bubble{p1}} == 0 && @{$pdata{p1}{malus}} == 0) {
1538 if (int(rand($mptrainingdiff*(1000/$TARGET_ANIM_SPEED))) == 0) {
1539 push @{$pdata{p1}{malus}}, ($frame) x (1 + int(rand(6)));
1540 }
1541 }
1542
1543 if ($playdata) {
1544 play();
1545 SDL::Events::pump_events();
1546 while (SDL::Events::poll_event($event) != 0) {
1547 if ($event->type == SDL_QUIT) {
1548 cleanup_and_exit();
1549 }
1550 my $keypressed = extended_keypress($event);
1551 handle_whenever_events($keypressed);
1552 if ($keypressed eq SDLK_ESCAPE) {
1553 die 'quit';
1554 }
1555 if ($keypressed eq SDLK_PAUSE) {
1556 my $time_pause = SDL::get_ticks();
1557 SDL::Events::pump_events() while SDL::Events::poll_event($event) != 0;
1558 pause_playdata:
1559 while (1) {
1560 while (SDL::Events::poll_event($event) != 0) {
1561 if ($event->type == SDL_QUIT) {
1562 cleanup_and_exit();
1563 }
1564 my $keypressed = extended_keypress($event);
1565 if ($keypressed) {
1566 $start_time += SDL::get_ticks() - $time_pause;
1567 return;
1568 }
1569 }
1570 }
1571 }
1572 if ($keypressed && $pdata{demo}) {
1573 die 'quit';
1574 }
1575 }
1576 return;
1577 }
1578
1579 SDL::Events::pump_events();
1580 while (SDL::Events::poll_event($event) != 0) {
1581 my $keypressed = extended_keypress($event);
1582 if ($keypressed) {
1583
1584 if (is_mp_game() && $pdata{p1}{chatting}) {
1585 if (($keypressed eq SDLK_RETURN() || $keypressed eq SDLK_KP_ENTER())) {
1586 if (callback_entry('gettext') > 0) {
1587 Games::FrozenBubble::Net::gsend('t' . join('', callback_entry('gettext')));
1588 }
1589 cleanup_chatting();
1590 } elsif ($event->type == SDL_KEYDOWN && !member($keypressed, SDLK_RETURN(), SDLK_KP_ENTER(), SDLK_TAB())) {
1591 callback_entry('keypressed', { event => $event, maxlen => $imgbin{void_chat}->w - 30, font => 'ingame_chat' });
1592 callback_entry('moved');
1593 update_say_mp();
1594 }
1595
1596 } else {
1597 iter_local_players {
1598 foreach my $action (qw(left right fire center)) {
1599 if ($keypressed eq $KEYS->{$::p}{$action}) {
1600 $actions{$::p}{$action} = 1;
1601 if (is_mp_game() && $action ne 'fire') {
1602 $action =~ /./; #- first letter
1603 Games::FrozenBubble::Net::gsend("r$&");
1604 }
1605 last;
1606 }
1607 }
1608 };
1609
1610 if ($keypressed eq $KEYS->{misc}{chat} && is_mp_game()) {
1611 callback_entry('reset');
1612 $pdata{p1}{chatting} = 1;
1613 SDL::Events::enable_key_repeat(200, 50);
1614 put_image_to_background($imgbin{void_chat}, $POS{p1}{chatting}{x}, $POS{p1}{chatting}{'y'});
1615 }
1616
1617 if ($keypressed eq SDLK_PAUSE && !is_mp_game()) {
1618 my $time_pause = SDL::get_ticks();
1619 play_sound('pause');
1620 $mixer_enabled && $mixer and SDL::Mixer::Music::pause_music;
1621 my $back_saved = switch_image_on_background($imgbin{back_paused}, 0, 0, 1);
1622 my $index;
1623 pause_label:
1624 while (1) {
1625 my $ticks = SDL::get_ticks();
1626 erase_image(${$imgbin{paused}}[$index], 320-${$imgbin{paused}}[$index]->w/2-5, 240-${$imgbin{paused}}[$index]->h/2-4);
1627 put_image(${$imgbin{paused}}[$index], 320-${$imgbin{paused}}[$index]->w/2-5, 240-${$imgbin{paused}}[$index]->h/2-4);
1628 SDL::Video::update_rects($app, @update_rects);
1629 @update_rects = ();
1630 SDL::delay(20);
1631 SDL::Events::pump_events();
1632 while (SDL::Events::poll_event($event) != 0) {
1633 if ($event->type == SDL_QUIT) {
1634 cleanup_and_exit();
1635 }
1636 my $keypressed = extended_keypress($event);
1637 if ($keypressed) {
1638 handle_whenever_events($keypressed);
1639 if (member($keypressed, SDLK_PAUSE, SDLK_ESCAPE, SDLK_RETURN, SDLK_SPACE)) {
1640 last pause_label;
1641 }
1642 }
1643 }
1644 if (++$index == @{$imgbin{paused}}) {
1645 $index = 11;
1646 }
1647 my $to_wait = $TARGET_ANIM_SPEED - (SDL::get_ticks() - $ticks);
1648 $to_wait > 0 and Games::FrozenBubble::CStuff::fbdelay($to_wait);
1649 }
1650 switch_image_on_background($back_saved, 0, 0);
1651 iter_local_players { $actions{$::p}{left} = 0; $actions{$::p}{right} = 0; };
1652 $mixer_enabled && $mixer and SDL::Mixer::Music::resume_music;
1653 SDL::Events::pump_events() while SDL::Events::poll_event($event) != 0;
1654 SDL::Video::update_rect($app, 0, 0, 0, 0);
1655 $start_time += SDL::get_ticks() - $time_pause;
1656 is_1p_game() and $time_1pgame += SDL::get_ticks() - $time_pause;
1657 return;
1658 }
1659
1660 if (is_mp_game() && @PLAYERS >= 3 && $singleplayertargetting) {
1661 foreach my $rp (qw(rp1 rp2 rp3 rp4)) {
1662 if ($keypressed eq $KEYS->{misc}{"send_malus_to_$rp"}) {
1663 set_sendmalustoone($rp);
1664 }
1665 }
1666 if ($keypressed eq $KEYS->{misc}{send_malus_to_all}) {
1667 set_sendmalustoone(undef);
1668 }
1669 }
1670
1671 if ($levels{current} !~ /^\d+$/ && $keypressed eq $KEYS->{misc}{save_record}) {
1672 print "This game will be recorded when it's over.\n";
1673 $recorddata{save} = 1;
1674 }
1675
1676 handle_whenever_events($keypressed);
1677 }
1678 }
1679
1680 $keypressed = undef;
1681 if ($event->type == SDL_KEYUP) {
1682 $keypressed = $event->key_sym;
1683 } elsif ($event->type == SDL_JOYAXISMOTION || $event->type() == SDL_JOYBUTTONUP) {
1684 $keypressed = translate_joystick_tokey($event);
1685 if ($event->type == SDL_JOYAXISMOTION && $keypressed !~ /^joystick\|axisvalue\|\d+\|\d+\|0$/) { #- we treat position at 0 as KEYUP
1686 $keypressed = undef;
1687 }
1688 $keypressed =~ s/^joystick\|buttonup/joystick|buttondown/;
1689 }
1690
1691 if ($keypressed) {
1692 iter_local_players {
1693 foreach my $action (qw(left right fire center)) {
1694 if ($keypressed eq $KEYS->{$::p}{$action}) {
1695 $actions{$::p}{$action} = 0;
1696 is_mp_game() && $action ne 'fire' and Games::FrozenBubble::Net::gsend('r');
1697 last;
1698 } elsif ($keypressed =~ /^joystick\|axisvalue\|(\d+)\|(\d+)\|0$/ && $KEYS->{$::p}{$action} =~ /^joystick\|axisvalue\|$1\|$2\|/) {
1699 $actions{$::p}{$action} = 0;
1700 is_mp_game() && $action ne 'fire' and Games::FrozenBubble::Net::gsend('r');
1701 #- no last, there might be two values of the same axis
1702 }
1703 }
1704 }
1705 }
1706
1707 if ($event->type == SDL_KEYDOWN && $event->key_sym == SDLK_ESCAPE) {
1708 if (is_mp_game()) {
1709 if ($pdata{p1}{chatting}) {
1710 cleanup_chatting();
1711 play_sound('cancel');
1712 } else {
1713 $pdata{p1}{left} = 1;
1714 lose('p1');
1715 die 'quit';
1716 }
1717 } else {
1718 $pdata{p1}{left} = 1;
1719 die 'quit';
1720 }
1721 }
1722 if ($event->type == SDL_QUIT) {
1723 cleanup_and_exit();
1724 }
1725 }
1726
1727 if (is_mp_game()) {
1728 $pdata{p1}{chatting} && callback_entry('ping') and update_say_mp();
1729
1730 my @messages = Games::FrozenBubble::Net::grecv();
1731 check_mp_connection();
1732 $recorddata{mp_messages} = deep_copy(\@messages); #- if we don't do a deep copy, the dumped data will be recursive for delayed messages
1733
1734 handle_mp_messages(\@messages);
1735
1736 Games::FrozenBubble::Net::gdelay_messages(@messages);
1737 }
1738
1739 record();
1740 }
1741
1742 sub record {
1743 $recorddata{frame}++;
1744 #- check for differences
1745 my %newdata;
1746 iter_players {
1747 foreach my $action (keys %{$actions{$::p}}) {
1748 $action =~ /^mp/ and next; #- mp actions will be generated by saving the mp messages
1749 if ($recorddata{lastactions}{$::p}{$action} ne $actions{$::p}{$action}) {
1750 $newdata{actions}{$::p}{$action} = $actions{$::p}{$action};
1751 }
1752 }
1753 };
1754 #- save if at least one difference or mp messages
1755 if (%newdata || @{$recorddata{mp_messages} || []}) {
1756 @{$recorddata{mp_messages} || []} and @{$newdata{mp_messages}} = @{$recorddata{mp_messages}};
1757 push @{$recorddata{data}}, [ $recorddata{frame}, \%newdata ];
1758 }
1759 #- save current state
1760 iter_players {
1761 foreach my $action (keys %{$actions{$::p}}) {
1762 $recorddata{lastactions}{$::p}{$action} = $actions{$::p}{$action};
1763 }
1764 };
1765 }
1766
1767 our $recordnumber = 0;
1768 sub save_record_if_needed {
1769 if (($recorddata{save} || $autorecord) && $levels{current} !~ /^\d+$/ && @{$recorddata{data}} > 1 && !$pdata{p1}{left}) {
1770 if (!$recorddir) {
1771 $recorddir = "$FBHOME/records";
1772 print "Notice: no recorddir was specified on commandline; recording in '$recorddir'\n";
1773 mkdir $recorddir;
1774 }
1775 my $filename = sprintf("$recorddir/fb_record_%08d", $recordnumber++);
1776 -f $filename || -f "$filename.bz2" and return save_record_if_needed();
1777 my $record = shift @{$recorddata{data}};
1778 my $data = "record_protocol:$RECORD_PROTOCOL_LEVEL\n"
1779 . "players:" . join(',', @PLAYERS) . "\n"
1780 . "gametype:$pdata{gametype}\n"
1781 . "current_level:$levels{current}\n"
1782 . "chainreaction:$chainreaction\n"
1783 . "time:" . time() . "\n"
1784 . "srand:$record->{srand}\n";
1785 if (exists $record->{bubbles}) {
1786 $data .= "bubbles:" . join(',', @{$record->{bubbles}}) . "\n";
1787 }
1788 $comment and $data .= "comment:$comment\n";
1789 if (is_mp_game()) {
1790 $data .= "mp_result:$pdata{state}\n";
1791 iter_players {
1792 $data .= "player_id:$::p|$pdata{$::p}{id}\n"
1793 . "player_nick:$::p|$pdata{$::p}{nick}\n";
1794 };
1795 }
1796 foreach my $item (@{$recorddata{data}}) {
1797 foreach my $playeractions (keys %{$item->[1]{actions}}) {
1798 foreach my $action (keys %{$item->[1]{actions}{$playeractions}}) {
1799 $data .= "frame_action:$item->[0]|$playeractions|$action|$item->[1]{actions}{$playeractions}{$action}\n";
1800 }
1801 }
1802 if (exists $item->[1]{mp_messages}) {
1803 foreach my $mpmessage (@{$item->[1]{mp_messages}}) {
1804 $data .= "frame_mpmessage:$item->[0]|$mpmessage->{id}|$mpmessage->{msg}\n";
1805 }
1806 }
1807 }
1808 my $bz = Compress::Bzip2::bzopen($filename . ".bz2", 'w');
1809 if($bz->bzwrite($data)) {
1810 $filename .= ".bz2";
1811 }
1812 else {
1813 output($filename, $data);
1814 }
1815 $bz->bzclose() if $bz;
1816
1817 print "Record saved in '$filename'. Start Frozen-Bubble with '--replay $filename' to replay the game.\n";
1818 return 1;
1819 }
1820 }
1821
1822 sub play {
1823 $recorddata{frame}++;
1824 my $nextdata = $playdata->[0];
1825 if ($nextdata) {
1826 if ($nextdata->[0] == $recorddata{frame}) {
1827 foreach my $p (keys %{$nextdata->[1]{actions}}) {
1828 my %pnew = %{$nextdata->[1]{actions}{$p}};
1829 $actions{$p}{$_} = $pnew{$_} foreach keys %pnew;
1830 }
1831 $nextdata->[1]{mp_messages} and handle_mp_messages($nextdata->[1]{mp_messages});
1832 shift @$playdata;
1833 }
1834 } else {
1835 if ($pdata{demo}) {
1836 die 'quit';
1837 }
1838 }
1839 }
1840
1841 sub print_scores($) {
1842 my ($surface) = @_;
1843 iter_players_ { #- sometimes called from within a iter_players so...
1844 my $score = @PLAYERS == 1 ? ($pdata{$::p_}{score} eq 'random' ? loc("Random level")
1845 : $levels{current} eq 'mp_train' ? loc("Score: %s", i18n_number($pdata{$::p_}{score}))
1846 : loc("Level %s", i18n_number($pdata{$::p_}{score}))) : i18n_number($pdata{$::p_}{score});
1847 is_mp_game() and $score = sprintf("%s: %s", $pdata{$::p_}{nick}, i18n_number($score));
1848 my $width = width(mini_graphics($::p_) ? 'ingame_small' : 'ingame', $score);
1849 my $xpos = $POS{$::p_}{scores}{x} - $width/2;
1850 my $drect = SDL::Rect->new($xpos, $POS{$::p_}{scores}{'y'}, $width, mini_graphics($::p_) ? 12 : 24);
1851 SDL::Video::blit_surface($background_orig, $drect, $surface, $drect);
1852 push @update_rects, $drect;
1853 if (mini_graphics($::p_)) {
1854 print_('ingame_small', $surface, $xpos, $POS{$::p_}{scores}{'y'}, $score);
1855 } else {
1856 print_('ingame', $surface, $xpos, $POS{$::p_}{scores}{'y'}, $score);
1857 }
1858 redraw_chat_message_if_needed($::p_);
1859 };
1860 }
1861
1862 sub cleanup_player_bubbles {
1863 my ($player) = @_;
1864 @{$malus_bubble{$player}} = ();
1865 #- reverse sort for freezing effect and win effect
1866 @{$sticked_bubbles{$player}} = sort { $b->{'cx'}+$b->{'cy'}*10 <=> $a->{'cx'}+$a->{'cy'}*10 } @{$sticked_bubbles{$player}};
1867 remove_hurry($player);
1868 @{$falling_bubble{$player}} = grep { !exists $_->{chaindestx} } @{$falling_bubble{$player}};
1869 $sticking_bubble{$player} = undef;
1870 $launched_bubble{$player} and destroy_bubbles($player, $launched_bubble{$player});
1871 $launched_bubble{$player} = undef;
1872 $pdata{$player}{newroot_prelight} = 0;
1873 }
1874
1875 sub win {
1876 my ($player) = @_;
1877 if (!$continuegamewhenplayersleave) {
1878 every { !$pdata{$_}{left} } @PLAYERS and $pdata{$player}{score}++;
1879 } else {
1880 $pdata{$player}{score}++;
1881 }
1882 $pdata{$player}{ping_right}{state} = 'win';
1883 $pdata{$player}{ping_right}{img} = 0;
1884 print_scores($background);
1885 print_scores($app);
1886 cleanup_player_bubbles($player);
1887 }
1888
1889 sub lose {
1890 my ($player) = @_;
1891 $pdata{$player}{ping_right}{state} = 'lose_to';
1892 $pdata{$player}{ping_right}{img} = 0;
1893 if (!$pdata{$player}{left}) {
1894 foreach ($launched_bubble{$player}, $tobe_launched{$player}, @{$malus_bubble{$player}}) {
1895 $_ or next;
1896 $_->{img} = $bubbles_anim{lose};
1897 $_->{'x'}--;
1898 $_->{'y'}--;
1899 }
1900 print_next_bubble($bubbles_anim{lose}, $player, 1);
1901 }
1902 cleanup_player_bubbles($player);
1903
1904 if (is_mp_game()) {
1905 $pdata{$player}{state} = 'lost';
1906 my @living = living_players();
1907 if (@living == 1) {
1908 if ((!$continuegamewhenplayersleave && any { $pdata{$_}{left} } @PLAYERS)
1909 || (every { $pdata{$_}{still_game_messages} == 0 } @PLAYERS)) {
1910 #- if some players have left and we want to end the game,
1911 #- or if we've already nothing to wait from others, directly go to won state
1912 win($living[0]);
1913 $pdata{state} = "won $living[0]";
1914 } else {
1915 #- tentatively suppose we've found the winner, but we need to confirm it by network
1916 #- first, in rare case of two last players dying at the same time
1917 my $winnernick = $pdata{$living[0]}{nick};
1918 $pdata{state} = "finished $living[0]:$winnernick 0";
1919 #- if I am about to leave, destinations need to receive leave not finished message, else they'll
1920 #- be waiting forever for it (and there's no point anyway)
1921 if (!$pdata{p1}{left}) {
1922 Games::FrozenBubble::Net::gsend("F$winnernick");
1923 }
1924 }
1925 } else {
1926 if ($pdata{sendmalustoone} eq $player || $player eq 'p1') {
1927 set_sendmalustoone(undef);
1928 }
1929 }
1930 if ($pdata{$player}{left}) {
1931 if (is_distant_player($player)) {
1932 put_image_to_background(mini_graphics($player) ? $imgbin{"left_${player}_mini"} : $imgbin{left_rp1},
1933 $POS{$player}{left}{x}, $POS{$player}{left}{y}); #}}
1934 }
1935 @{$sticked_bubbles{$player}} = ();
1936 play_sound('cancel');
1937 } else {
1938 play_sound('lose');
1939 }
1940
1941 } else {
1942 play_sound('lose');
1943 $pdata{state} = "lost $player";
1944 is_2p_game() and win($player eq 'p1' ? 'p2' : 'p1');
1945 }
1946 ret:
1947 }
1948
1949 sub verify_if_end {
1950 iter_players {
1951 if ($pdata{state} eq 'game' && any { $_->{cy} > 11 } @{$sticked_bubbles{$::p}}) {
1952 lose($::p);
1953 }
1954 };
1955
1956 if (is_1p_game() && $levels{current} ne 'mp_train' && @{$sticked_bubbles{$PLAYERS[0]}} == 0) {
1957 put_image_to_background($imgbin{win_panel_1player}, $POS{centerpanel}{x}, $POS{centerpanel}{'y'});
1958 $pdata{state} = "won $PLAYERS[0]";
1959 $pdata{$PLAYERS[0]}{ping_right}{state} = 'win';
1960 $pdata{$PLAYERS[0]}{ping_right}{img} = 0;
1961 if ($levels{current} ne 'random') {
1962 $levels{current} and $levels{current}++;
1963 if ($levels{current} && !$levels{$levels{current}}) {
1964 $levels{current} = 'WON';
1965 @{$falling_bubble{$PLAYERS[0]}} = @{$exploding_bubble{$PLAYERS[0]}} = ();
1966 die 'quit';
1967 }
1968 }
1969 }
1970 }
1971
1972 sub print_hurry($;$) {
1973 my ($player, $dont_save_background) = @_;
1974 $player = @PLAYERS == 2 && $player eq 'rp1' ? 'p2' : $player;
1975 my $t = switch_image_on_background($imgbin{hurry}{$player}, $POS{$player}{left_limit} + $POS{$player}{hurry}{x}, $POS{$player}{hurry}{'y'}, 1);
1976 $dont_save_background or $pdata{$player}{hurry_save_img} = $t;
1977 }
1978 sub remove_hurry($) {
1979 my ($player) = @_;
1980 $player = @PLAYERS == 2 && $player eq 'rp1' ? 'p2' : $player;
1981 $pdata{$player}{hurry_save_img} and
1982 switch_image_on_background($pdata{$player}{hurry_save_img}, $POS{$player}{left_limit} + $POS{$player}{hurry}{x}, $POS{$player}{hurry}{'y'});
1983 $pdata{$player}{hurry_save_img} = undef;
1984 }
1985
1986 sub update_lost {
1987 my ($player) = @_;
1988
1989 return if odd($frame);
1990
1991 if (@{$sticked_bubbles{$player}}) {
1992 my $b = shift @{$sticked_bubbles{$player}};
1993 put_image_to_background($bubbles_anim{lose}, --$b->{'x'}, --$b->{'y'});
1994
1995 if (@{$sticked_bubbles{$player}} == 0) {
1996 if ($graphics_level == 1 && $pdata{state} =~ /^lost (.*)/ && !is_1p_game()) {
1997 put_image_to_background($imgbin{win}{$player eq 'p1' ? 'p2' : 'p1'}, $POS{centerpanel}{x}, $POS{centerpanel}{'y'});
1998 }
1999 if (is_1p_game()) {
2000 put_image_to_background($imgbin{lose}, $POS{centerpanel}{'x'}, $POS{centerpanel}{'y'});
2001 play_sound('noh');
2002 }
2003 }
2004 }
2005
2006 if (!is_mp_game()) {
2007 SDL::Events::pump_events();
2008 while (SDL::Events::poll_event($event) != 0) {
2009 if ($event->type == SDL_QUIT) {
2010 cleanup_and_exit();
2011 }
2012 if ($event->type == SDL_KEYDOWN && $event->key_sym == SDLK_ESCAPE) {
2013 die 'new_game';
2014 }
2015 if (!@{$sticked_bubbles{$player}}) {
2016 if ($event->type == SDL_KEYDOWN || $event->type == SDL_JOYBUTTONUP) {
2017 die 'new_game';
2018 }
2019 }
2020 }
2021 }
2022
2023 my $still_sticked = sum(map { @{$sticked_bubbles{$_}} } @PLAYERS);
2024 if ($pdata{state} eq 'won ' && $still_sticked == 1) {
2025 put_image($imgbin{void_panel}, $MENUPOS{xpos_panel}, $MENUPOS{ypos_panel});
2026 print_('menu', $app, $MENUPOS{xpos_panel}, $MENUPOS{ypos_panel} + 30, loc("Draw game!"), $imgbin{void_panel}->w - 20, 'center');
2027 SDL::Video::update_rect($app, 0, 0, 0, 0);
2028 }
2029 }
2030
2031 sub update_won {
2032 my ($player) = @_;
2033
2034 return if odd($frame);
2035
2036 iter_players { #- need iter_players to get the small graphics change for free if we're in multiplayer
2037 if ($::p eq $player) {
2038 if (@{$sticked_bubbles{$::p}} && $graphics_level > 1) {
2039 my $b = shift @{$sticked_bubbles{$::p}};
2040 destroy_bubbles($::p, $b);
2041 remove_image_from_background($b->{img}, $b->{'x'}, $b->{'y'});
2042 #- be sure to redraw at least upper line
2043 foreach (@{$b->{neighbours}}) {
2044 next if !member($_, @{$sticked_bubbles{$::p}});
2045 put_image_to_background($_->{img}, $_->{'x'}, $_->{'y'});
2046 }
2047 } else {
2048 @{$sticked_bubbles{$::p}} = ();
2049 }
2050 }
2051 };
2052 }
2053
2054 sub decode_postgame_message($) {
2055 my ($msg) = @_;
2056 my $player = $pdata{id2p}{$msg->{id}};
2057 $player ||= 'UNKNOWN';
2058 if ($msg->{msg} =~ /^F(.*)/) {
2059 $pdata{$player}{still_game_messages} = 0;
2060 dbgnet("decoded postgame message: from=$player msg=finished $1");
2061 return "$player finished $1";
2062 } elsif ($pdata{$player}{still_game_messages}) {
2063 dbgnet("decoded postgame message: from=$player msg=gamemsg");
2064 return "$player gamemsg";
2065 } elsif ($msg->{msg} eq 'n') {
2066 $pdata{$player}{ready4newgame} = 1;
2067 dbgnet("decoded postgame message: from=$player msg=newgame");
2068 return "$player newgame";
2069 } else {
2070 if ($msg->{msg} ne 'l') {
2071 print "Postgame 'other' message from $player not a leave - $msg->{msg} - should not!\n";
2072 }
2073 dbgnet("decoded postgame message: from=$player msg=other");
2074 return "$player other";
2075 }
2076 }
2077
2078 #- ----------- mainloop helper --------------------------------------------
2079
2080 sub update_game() {
2081
2082 if ($pdata{state} eq 'game') {
2083 handle_game_events();
2084 iter_players {
2085 if ($pdata{$::p}{state} eq 'lost') {
2086 update_lost($::p);
2087
2088 } elsif ($pdata{$::p}{state} eq 'ingame') {
2089 $actions{$::p}{left} and $angle{$::p} += $LAUNCHER_SPEED;
2090 $actions{$::p}{right} and $angle{$::p} -= $LAUNCHER_SPEED;
2091 if ($actions{$::p}{center}) {
2092 if ($angle{$::p} >= $PI/2 - $LAUNCHER_SPEED
2093 && $angle{$::p} <= $PI/2 + $LAUNCHER_SPEED) {
2094 $angle{$::p} = $PI/2;
2095 } else {
2096 $angle{$::p} += ($angle{$::p} < $PI/2) ? $LAUNCHER_SPEED : -$LAUNCHER_SPEED;
2097 }
2098 }
2099 ($angle{$::p} < 0.1) and $angle{$::p} = 0.1;
2100 ($angle{$::p} > $PI-0.1) and $angle{$::p} = $PI-0.1;
2101 if (is_mp_game() && is_local_player($::p) && ($actions{$::p}{left} || $actions{$::p}{right} || $actions{$::p}{center})) {
2102 Games::FrozenBubble::Net::gsend(sprintf("a%.2f", $angle{$::p}));
2103 }
2104 if (every { ! exists $_->{chaindestx} } @{$falling_bubble{$::p}}) {
2105 $pdata{$::p}{hurry}++;
2106 }
2107 if ((!$no_time_limit || is_mp_game()) && $pdata{$::p}{hurry} > $TIME_HURRY_WARN) {
2108 my $oddness = odd(int(($pdata{$::p}{hurry}-$TIME_HURRY_WARN)/(500/$TARGET_ANIM_SPEED))+1);
2109 if ($pdata{$::p}{hurry_oddness} xor $oddness) {
2110 if ($oddness) {
2111 play_sound('hurry');
2112 print_hurry($::p);
2113 } else {
2114 remove_hurry($::p)
2115 }
2116 }
2117 $pdata{$::p}{hurry_oddness} = $oddness;
2118 }
2119
2120 if ($actions{$::p}{mp_fire}
2121 || (is_local_player($::p)
2122 && ($actions{$::p}{fire} || ((!$no_time_limit || is_mp_game()) && $pdata{$::p}{hurry} == $TIME_HURRY_MAX))
2123 && !$launched_bubble{$::p}
2124 && !(any { exists $_->{chaindestx} } @{$falling_bubble{$::p}})
2125 && !@{$malus_bubble{$::p}})) {
2126 play_sound('launch');
•2127 $total_launched_bubbles++;
2128 $launched_bubble{$::p} = $tobe_launched{$::p};
2129 $launched_bubble{$::p}->{direction} = $angle{$::p};
2130 $tobe_launched{$::p} = undef;
2131 $actions{$::p}{fire} = 0;
2132 $actions{$::p}{hadfire} = 1;
2133 $pdata{$::p}{hurry} = 0;
2134 remove_hurry($::p);
2135 if (is_local_player($::p)) {
2136 do {
2137 $pdata{$::p}{nextcolor} = int(rand(@bubbles_images));
2138 } while (!validate_nextcolor($pdata{$::p}{nextcolor}, $::p) && @{$sticked_bubbles{$::p}});
2139 }
2140 if (is_mp_game()) {
2141 if (is_local_player($::p)) {
2142 Games::FrozenBubble::Net::gsend(sprintf("f%.3f:$pdata{$::p}{nextcolor}", $angle{$::p}));
2143 } else {
2144 $actions{$::p}{mp_fire} = 0;
2145 }
2146 }
2147 }
2148
2149 if ($launched_bubble{$::p}) {
2150 if (!$pdata{$::p}{freezelaunchedbubble}) {
2151 $launched_bubble{$::p}->{'x_old'} = $launched_bubble{$::p}->{'x'}; # save coordinates for potential collision
2152 $launched_bubble{$::p}->{'y_old'} = $launched_bubble{$::p}->{'y'};
2153 $launched_bubble{$::p}->{'x'} += $BUBBLE_SPEED * cos($launched_bubble{$::p}->{direction});
2154 $launched_bubble{$::p}->{'y'} -= $BUBBLE_SPEED * sin($launched_bubble{$::p}->{direction});
2155 if ($launched_bubble{$::p}->{x} < $POS{$::p}{left_limit}) {
2156 play_sound('rebound');
2157 $launched_bubble{$::p}->{x} = 2 * $POS{$::p}{left_limit} - $launched_bubble{$::p}->{x};
2158 $launched_bubble{$::p}->{direction} -= 2*($launched_bubble{$::p}->{direction}-$PI/2);
2159 }
2160 if ($launched_bubble{$::p}->{x} > $POS{$::p}{right_limit} - $BUBBLE_SIZE) {
2161 play_sound('rebound');
2162 $launched_bubble{$::p}->{x} = 2 * ($POS{$::p}{right_limit} - $BUBBLE_SIZE) - $launched_bubble{$::p}->{x};
2163 $launched_bubble{$::p}->{direction} += 2*($PI/2-$launched_bubble{$::p}->{direction});
2164 }
2165 }
2166 if (!exists $pdata{$::p}{nextcolors}) {
2167 @{$pdata{$::p}{nextcolors}} = map { int(rand(@bubbles_images)) } 0..7;
2168 }
2169 if ($actions{$::p}{mp_stick}) {
2170 $actions{$::p}{mp_stick} = 0;
2171 stick_bubble($launched_bubble{$::p}, $pdata{$::p}{stickcx}, $pdata{$::p}{stickcy}, $::p, 1);
2172 $launched_bubble{$::p} = undef;
2173 $pdata{$::p}{freezelaunchedbubble} = 0;
2174 } elsif ($launched_bubble{$::p}->{'y'} <= $POS{$::p}{top_limit} + $pdata{$::p}{newrootlevel} * $ROW_SIZE) {
2175 my ($cx, $cy) = get_array_closest_pos($launched_bubble{$::p}->{x}, $launched_bubble{$::p}->{'y'}, $::p);
2176 if (is_local_player($::p)) {
2177 my $col = get_bubble_num($launched_bubble{$::p});
2178 is_mp_game() and Games::FrozenBubble::Net::gsend("s$cx:$cy:$col:@{$pdata{$::p}{nextcolors}}");
2179 stick_bubble($launched_bubble{$::p}, $cx, $cy, $::p, 1);
2180 $launched_bubble{$::p} = undef;
2181 } else {
2182 $pdata{$::p}{freezelaunchedbubble} = 1;
2183 }
2184 } else {
2185 foreach (@{$sticked_bubbles{$::p}}) {
2186 if (is_collision($launched_bubble{$::p}, $_->{'x'}, $_->{'y'})) {
2187 my ($cx, $cy) = get_array_closest_pos(($launched_bubble{$::p}->{'x_old'}+$launched_bubble{$::p}->{'x'})/2,
2188 ($launched_bubble{$::p}->{'y_old'}+$launched_bubble{$::p}->{'y'})/2,
2189 $::p);
2190 if (is_local_player($::p)) {
2191 my $col = get_bubble_num($launched_bubble{$::p});
2192 is_mp_game() and Games::FrozenBubble::Net::gsend("s$cx:$cy:$col:@{$pdata{$::p}{nextcolors}}");
2193 stick_bubble($launched_bubble{$::p}, $cx, $cy, $::p, 1);
2194 $launched_bubble{$::p} = undef;
2195
2196 #- malus generation
2197 if (!any { $_->{chaindestx} } @{$falling_bubble{$::p}}) {
2198 my $malusfreezeframes = 20;
2199 @{$pdata{$::p}{malus}} > 0 && $frame > $pdata{$::p}{malus}[0] + $malusfreezeframes and play_sound('malus');
2200 while (@{$pdata{$::p}{malus}} > 0 && $frame > $pdata{$::p}{malus}[0] + $malusfreezeframes && @{$malus_bubble{$::p}} < 7) {
2201 my $num = int(rand(@bubbles_images));
2202 my $b = create_bubble_given_img_num($num);
2203 $b->{num} = $num;
2204 do {
2205 $b->{'cx'} = int(rand(7));
2206 } while (member($b->{'cx'}, map { $_->{'cx'} } @{$malus_bubble{$::p}}));
2207 $b->{'cy'} = 12;
2208 $b->{'stick_y'} = -1;
2209 foreach (@{$sticked_bubbles{$::p}}) {
2210 if ($_->{'cy'} > $b->{'stick_y'}) {
2211 if ($_->{'cx'} == $b->{'cx'}
2212 || odd($_->{'cy'}+$pdata{$::p}{oddswap}) && ($_->{'cx'}+1) == $b->{'cx'}) {
2213 $b->{'stick_y'} = $_->{'cy'};
2214 }
2215 }
2216 }
2217 $b->{'stick_y'}++;
2218 calc_real_pos($b, $::p);
2219 push @{$malus_bubble{$::p}}, $b;
2220 malus_change(-1, $::p);
2221 }
2222 #- sort them and shift them
2223 @{$malus_bubble{$::p}} = sort { $a->{'cx'} <=> $b->{'cx'} } @{$malus_bubble{$::p}};
2224 my $shifting = 0;
2225 $_->{'y'} += ($shifting += 7) + int(rand(20)) foreach @{$malus_bubble{$::p}};
2226 if (is_mp_game()) {
2227 Games::FrozenBubble::Net::gsend("m$_->{num}:$_->{cx}:$_->{cy}:$_->{stick_y}") foreach @{$malus_bubble{$::p}};
2228 }
2229 }
2230
2231 } else {
2232 $pdata{$::p}{freezelaunchedbubble} = 1;
2233 }
2234 last;
2235 }
2236 }
2237 }
2238 }
2239
2240 !$tobe_launched{$::p} and generate_new_bubble($::p, $pdata{$::p}{nextcolor});
2241
2242 if (!$actions{$::p}{left} && !$actions{$::p}{right} && !$actions{$::p}{hadfire}) {
2243 $pdata{$::p}{sleeping}++;
2244 } else {
2245 $pdata{$::p}{sleeping} = 0;
2246 $pdata{$::p}{ping_right}{movelatency} = -20;
2247 }
2248 if ($pdata{$::p}{sleeping} > $TIMEOUT_PINGUIN_SLEEP && $pdata{$::p}{ping_right}{state} !~ /wait/) {
2249 $pdata{$::p}{ping_right}{state} = 'wait_to';
2250 $pdata{$::p}{ping_right}{img} = 0;
2251 }
2252 if ($pdata{$::p}{sleeping} <= $TIMEOUT_PINGUIN_SLEEP && $pdata{$::p}{ping_right}{state} =~ /wait/) {
2253 $pdata{$::p}{ping_right}{state} = 'normal';
2254 }
2255 foreach my $direction ('left', 'right') {
2256 if ($pdata{$::p}{ping_right}{state} eq "${direction}_to" && !($actions{$::p}{$direction})) {
2257 $pdata{$::p}{ping_right}{state} = "${direction}_from";
2258 $pdata{$::p}{ping_right}{img} = @{$pinguin{$::p}{$pdata{$::p}{ping_right}{state}}} - $pdata{$::p}{ping_right}{img};
2259 }
2260 if ($pdata{$::p}{ping_right}{state} eq $direction && !($actions{$::p}{$direction})) {
2261 $pdata{$::p}{ping_right}{state} = "${direction}_from";
2262 $pdata{$::p}{ping_right}{img} = 0;
2263 }
2264 if ($actions{$::p}{$direction}) {
2265 if ($pdata{$::p}{ping_right}{state} eq "${direction}_to") {
2266 #- we're animating towards, nothing to do
2267 } elsif ($pdata{$::p}{ping_right}{state} eq $direction) {
2268 #- we're there, nothing to do
2269 } elsif ($pdata{$::p}{ping_right}{state} eq "${direction}_from") {
2270 #- we're coming from there, should not happen that much, flicker no big deal
2271 $pdata{$::p}{ping_right}{state} = $direction;
2272 } else {
2273 $pdata{$::p}{ping_right}{state} = "${direction}_to";
2274 $pdata{$::p}{ping_right}{img} = 0;
2275 }
2276 }
2277 }
2278 if ($actions{$::p}{hadfire}) {
2279 $pdata{$::p}{ping_right}{state} = 'action';
2280 $pdata{$::p}{ping_right}{img} = 0;
2281 $actions{$::p}{hadfire} = 0;
2282 }
2283
2284 if ($pdata{$::p}{ping_right}{img} >= @{$pinguin{$::p}{$pdata{$::p}{ping_right}{state}}}) {
2285 $pdata{$::p}{ping_right}{img} = 0;
2286 }
2287 }
2288 };
2289
2290 verify_if_end();
2291
2292 } elsif ($pdata{state} =~ /^lost (.*)/) {
2293 #- 1p and 2p game only state
2294
2295 my $loser = $1;
2296 update_lost($loser);
2297 is_2p_game() and update_won($loser eq 'p1' ? 'p2' : 'p1');
2298
2299 } elsif ($pdata{state} =~ /^finished (\S+):(\S+) (\S+)/) {
2300 my $supposed_winner_player = $1;
2301 my $supposed_winner_nick = $2;
2302 my $timeout_counter = $3;
2303
2304 if ($playdata) {
2305 $pdata{state} = $recorddata{pdatas}{mp_result};
2306 if ($pdata{state} eq 'won ') {
2307 lose($supposed_winner_player); #- draw game
2308 } else {
2309 win($supposed_winner_player);
2310 }
2311
2312 } else {
2313 SDL::Events::pump_events() while SDL::Events::poll_event($event) != 0;
2314 #- mp game only state when we're trying to figure out if this is not a draw game
2315
2316 if (my $msg = Games::FrozenBubble::Net::grecv_get1msg_ifdata()) {
2317 my $result = decode_postgame_message($msg);
2318 iter_players { dbgnet("\tstill game message of=$pdata{$::p}{nick} value=$pdata{$::p}{still_game_messages}"); };
2319 if ($result =~ /^(\S+) finished (\S+)/) {
2320 my $remote_winner_nick = $2;
2321 if ($remote_winner_nick ne $supposed_winner_nick) {
2322 #- players don't agree with who won the game, this is a draw game
2323 lose($supposed_winner_player);
2324 $pdata{state} = "won ";
2325 } else {
2326 if (every { $pdata{$_}{still_game_messages} == 0 } @PLAYERS) {
2327 win($supposed_winner_player);
2328 $pdata{state} = "won $supposed_winner_player";
2329 }
2330 }
2331 } elsif ($result =~ /^(\S+) other/) {
2332 $pdata{$pdata{id2p}{$msg->{id}}}{left} = 1;
2333 win($supposed_winner_player);
2334 $pdata{state} = "won $supposed_winner_player";
2335 } elsif ($result !~ /^(\S+) gamemsg/) {
2336 #- delay other players already asking for a new game (we're waiting for agreement on winner from others)
2337 Games::FrozenBubble::Net::gdelay_messages($msg);
2338 }
2339
2340 } else {
2341 check_mp_connection();
2342 #- timeout for receiving the winners. it could happen when a client is badly killed.
2343 $timeout_counter++;
2344 if ($timeout_counter > 10 * (1000/$TARGET_ANIM_SPEED) ) { #- 10 seconds
2345 mp_disconnect_with_reason('', '', '', '', '', loc("Lost synchronization %s!", 1));
2346 } else {
2347 $pdata{state} = "finished $supposed_winner_player:$supposed_winner_nick $timeout_counter";
2348 }
2349 }
2350 }
2351
2352 } elsif ($pdata{state} =~ /^won (.*)/) {
2353 #- mp and 1p game only state
2354
2355 my $events_pumped;
2356 my $winner = $1;
2357 if (is_mp_game()) {
2358 $winner and update_won($winner);
2359 iter_players {
2360 if ($::p ne $winner) {
2361 update_lost($::p);
2362 }
2363 };
2364 check_mp_connection();
2365 $frame % (1000/$TARGET_ANIM_SPEED) == 0 and Games::FrozenBubble::Net::gsend('p');
2366 }
2367 if (!$winner || @{$exploding_bubble{$winner}} == 0) {
2368 my $still_needwait = 0;
2369 #- still wait if some bubbles are not yet "frozen"
2370 iter_players {
2371 $still_needwait += @{$sticked_bubbles{$::p}};
2372 };
2373 if (!$still_needwait) {
2374 SDL::Events::pump_events();
2375 $events_pumped = 1;
2376
2377 my $mp_newgame = sub {
2378 if ((!$continuegamewhenplayersleave && any { $pdata{$_}{left} } @PLAYERS)
2379 || ($continuegamewhenplayersleave && notleft_players() <= 1)
2380 || ($pdata{scorelimit} && any { $pdata{$_}{score} == $pdata{scorelimit} } @PLAYERS)) {
2381 die 'quit';
2382 };
2383 dbgnet("send newgame 'n'");
2384 Games::FrozenBubble::Net::gsend('n');
2385 my $timeout_counter;
2386
2387 while (1) {
2388 if (my $msg = Games::FrozenBubble::Net::grecv_get1msg_ifdata()) {
2389 my $result = decode_postgame_message($msg);
2390 if ($result =~ /^(\S+) other/) {
2391 $pdata{$pdata{id2p}{$msg->{id}}}{left} = 1;
2392 !$continuegamewhenplayersleave || notleft_players() <= 1 and die 'quit';
2393 }
2394 }
2395 iter_distant_players {
2396 !$pdata{$::p}{left} && $pdata{$::p}{ready4newgame} == 0 and goto still_waiting;
2397 };
2398 die 'new_game';
2399 still_waiting:
2400 SDL::Events::pump_events();
2401 while (SDL::Events::poll_event($event) != 0) {
2402 if ($event->type == SDL_KEYDOWN && $event->key_sym == SDLK_ESCAPE()) {
2403 die 'quit';
2404 }
2405 }
2406 check_mp_connection();
2407 Games::FrozenBubble::CStuff::fbdelay($TARGET_ANIM_SPEED);
2408 $frame++;
2409 $frame % (1000/$TARGET_ANIM_SPEED) == 0 and Games::FrozenBubble::Net::gsend('p');
2410 $timeout_counter++;
2411 if ($timeout_counter > 10 * (1000/$TARGET_ANIM_SPEED) ) { #- 10 seconds
2412 mp_disconnect_with_reason('', '', '', '', '', loc("Lost synchronization %s!", 2));
2413 }
2414 }
2415 };
2416
2417 while (SDL::Events::poll_event($event) != 0) {
2418 if ($event->type == SDL_QUIT) {
2419 cleanup_and_exit();
2420 }
2421 if ($event->type == SDL_KEYDOWN && $event->key_sym == SDLK_ESCAPE()) {
2422 die 'quit';
2423 }
2424 if ($event->type == SDL_KEYDOWN || $event->type == SDL_JOYBUTTONUP) {
2425 if ($playdata) {
2426 die 'quit';
2427 } elsif (is_mp_game()) {
2428 $mp_newgame->();
2429 } else {
2430 die 'new_game';
2431 }
2432 }
2433 }
2434
2435 if (is_mp_game()) {
2436 if (my $msg = Games::FrozenBubble::Net::grecv_get1msg_ifdata()) {
2437 my $result = decode_postgame_message($msg);
2438 if ($result =~ /^(\S+) newgame/) {
2439 $mp_newgame->();
2440 } elsif ($result =~ /^(\S+) other/) {
2441 $pdata{$pdata{id2p}{$msg->{id}}}{left} = 1;
2442 !$continuegamewhenplayersleave || notleft_players() <= 1 and die 'quit';
2443 }
2444 }
2445 check_mp_connection();
2446 }
2447 }
2448 }
2449 if (!$events_pumped) {
2450 SDL::Events::pump_events();
2451 while (SDL::Events::poll_event($event) != 0) {
2452 if ($event->type == SDL_QUIT) {
2453 cleanup_and_exit();
2454 }
2455 if ($event->type == SDL_KEYDOWN && $event->key_sym == SDLK_ESCAPE) {
2456 die 'quit';
2457 }
2458 }
2459 }
2460
2461 } else {
2462 die "oops unhandled game state ($pdata{state})\n";
2463 }
2464
2465 if (is_mp_game()) {
2466 $frame % (1000/$TARGET_ANIM_SPEED) == 0 and Games::FrozenBubble::Net::gsend('p');
2467 }
2468
2469 #- things that need to be updated in all states of the game
2470 iter_players {
2471 my $malus_end = [];
2472 foreach my $b (@{$malus_bubble{$::p}}) {
2473 !$b->{freeze} and $b->{'y'} -= $MALUS_BUBBLE_SPEED;
2474 if (get_array_yclosest($b->{'y'}, $::p) <= $b->{'stick_y'}) {
2475 if (is_local_player($::p)) {
2476 real_stick_bubble($b, $b->{'cx'}, $b->{'stick_y'}, $::p, 0);
2477 push @$malus_end, $b;
2478 #- remote decode_postgame_message will not like receiving the M command after we sent the F command
2479 is_mp_game() && $pdata{state} eq 'game' and Games::FrozenBubble::Net::gsend("M$b->{cx}:$b->{stick_y}");
2480 } else {
2481 $b->{freeze} = 1;
2482 }
2483 }
2484 if ($b->{mp_stick}) {
2485 real_stick_bubble($b, $b->{'cx'}, $b->{'stick_y'}, $::p, 0);
2486 push @$malus_end, $b;
2487 }
2488 }
2489 @$malus_end and @{$malus_bubble{$::p}} = difference2($malus_bubble{$::p}, $malus_end);
2490
2491 my $falling_end = [];
2492 foreach my $b (@{$falling_bubble{$::p}}) {
2493 if ($b->{wait_fall}) {
2494 $b->{wait_fall}--;
2495 } else {
2496 my $maxy = @PLAYERS == 2 ? 380 : member($::p, 'rp1', 'rp2') ? 185 : member($::p, 'rp3', 'rp4') ? 415 : 380;
2497 if (exists $b->{chaindestx} && ($b->{'y'} > $maxy || $b->{chaingoingup})) {
2498 my $acceleration = $FREE_FALL_CONSTANT*3;
2499 if (!$b->{chaingoingup}) {
2500 my $time_to_zero = $b->{speed}/$acceleration;
2501 my $distance_to_zero = $b->{speed} * ($b->{speed}/$acceleration + 1) / 2;
2502 my $tobe_sqrted = 1 + 8/$acceleration*($b->{'y'}-$b->{chaindesty}+$distance_to_zero);
2503 if ($tobe_sqrted < 0) {
2504 #- avoid SQRT of a negative number
2505 $b->{speedx} = 0;
2506 } else {
2507 my $time_to_destination = (-1 + sqrt($tobe_sqrted)) / 2;
2508 if ($time_to_zero + $time_to_destination == 0) {
2509 #- avoid division by zero
2510 $b->{speedx} = 0;
2511 } else {
2512 $b->{speedx} = ($b->{chaindestx} - $b->{x}) / ($time_to_zero + $time_to_destination);
2513 }
2514 }
2515 $b->{chaingoingup} = 1;
2516 }
2517 $b->{speed} -= $acceleration;
2518 $b->{x} += $b->{speedx};
2519 if (abs($b->{x} - $b->{chaindestx}) < abs($b->{speedx})) {
2520 $b->{'x'} = $b->{chaindestx};
2521 $b->{speedx} = 0;
2522 }
2523 $b->{'y'} += $b->{speed};
2524 $b->{'y'} < $b->{chaindesty} and push @$falling_end, $b;
2525 } else {
2526 $b->{'y'} += $b->{speed};
2527 $b->{speed} += $FREE_FALL_CONSTANT;
2528 }
2529 }
2530 $b->{'y'} > 470 && !exists $b->{chaindestx} and push @$falling_end, $b;
2531 }
2532 @$falling_end and @{$falling_bubble{$::p}} = difference2($falling_bubble{$::p}, $falling_end);
2533 foreach (@$falling_end) {
2534 exists $_->{chaindestx} or next;
2535 @{$chains{$::p}{falling_chained}} = difference2($chains{$::p}{falling_chained}, [ $_ ]);
2536 delete $chains{$::p}{chained_bubbles}{$_};
2537 stick_bubble($_, $_->{chaindestcx}, $_->{chaindestcy}, $::p, 0);
2538 }
2539
2540 my $exploding_end = [];
2541 foreach my $b (@{$exploding_bubble{$::p}}) {
2542 $b->{'x'} += $b->{speedx};
2543 $b->{'y'} += $b->{speedy};
2544 $b->{speedy} += $FREE_FALL_CONSTANT;
2545 push @$exploding_end, $b if $b->{'y'} > 470;
2546 }
2547 if (@$exploding_end) {
2548 @{$exploding_bubble{$::p}} = difference2($exploding_bubble{$::p}, $exploding_end);
2549 if (!@{$exploding_bubble{$::p}} && !@{$sticked_bubbles{$::p}}) {
2550 if ($pdata{state} =~ /^lost (.*)/ && $::p ne $1 && !is_1p_game()) {
2551 put_image($imgbin{win}{$::p}, $POS{centerpanel}{'x'}, $POS{centerpanel}{'y'});
2552 }
2553 if (is_mp_game() && $pdata{state} =~ /^won (.*)/) {
2554 my $winner = $1;
2555 my $img = $winner eq 'p1' ? $imgbin{win_panel_p1_net} : @PLAYERS == 2 ? $imgbin{win}{rp3} : $imgbin{win}{$winner};
2556 put_image($img, $POS{centerpanel}{x}, $POS{centerpanel}{'y'});
2557 print_('ingame', $app, 264, 300, $pdata{$winner}{nick}, 198, 'center');
2558 my $xpos = @PLAYERS <= 3 ? 352 : @PLAYERS == 4 ? 348 : 322;
2559 iter_players_ {
2560 if ($::p_ ne $winner) {
2561 my $img = @PLAYERS == 2 && $::p_ eq 'rp1' ? $imgbin{net_lose}{rp3} : $imgbin{net_lose}{$::p_}; #- fix colors
2562 put_image($img, $xpos, 264);
2563 $xpos += 32;
2564 }
2565 };
2566 }
2567 }
2568 }
2569
2570 if (member($pdata{$::p}{ping_right}{state}, qw(action right_to right_from left_to left_from wait_to wait win lose_to lose))) {
2571 $pdata{$::p}{ping_right}{img}++;
2572 # print "...state $pdata{$::p}{ping_right}{state} image $pdata{$::p}{ping_right}{img}\n";
2573 if ($pdata{$::p}{ping_right}{img} == @{$pinguin{$::p}{$pdata{$::p}{ping_right}{state}}}) {
2574 # print "finish images of state $pdata{$::p}{ping_right}{state} (" . int(@{$pinguin{$::p}{$pdata{$::p}{ping_right}{state}}}) . ")\n";
2575 if ($pdata{$::p}{ping_right}{state} eq 'right_to') {
2576 $pdata{$::p}{ping_right}{state} = 'right';
2577 } elsif ($pdata{$::p}{ping_right}{state} eq 'left_to') {
2578 $pdata{$::p}{ping_right}{state} = 'left';
2579 } elsif ($pdata{$::p}{ping_right}{state} eq 'wait_to') {
2580 $pdata{$::p}{ping_right}{state} = 'wait';
2581 } elsif ($pdata{$::p}{ping_right}{state} eq 'wait') {
2582 #- wait loops, don't change state
2583 } elsif ($pdata{$::p}{ping_right}{state} eq 'win') {
2584 #- simple loop, don't change state
2585 } elsif ($pdata{$::p}{ping_right}{state} eq 'lose_to') {
2586 $pdata{$::p}{ping_right}{state} = 'lose';
2587 } elsif ($pdata{$::p}{ping_right}{state} eq 'lose') {
2588 #- lose loops, don't change state
2589 } else {
2590 $pdata{$::p}{ping_right}{state} = 'normal';
2591 }
2592 $pdata{$::p}{ping_right}{img} = 0;
2593 # print "=> state $pdata{$::p}{ping_right}{state}\n";
2594 }
2595 }
2596
2597 };
2598
2599 #- advance playlist when the current song finished
2600 $mixer_enabled && $mixer && @playlist && !SDL::Mixer::Music::playing_music and play_music('dummy');
2601 }
2602
2603 #- ----------- init stuff -------------------------------------------------
2604
2605 our $init_step = 0;
2606 sub print_step($) {
2607 my ($txt) = @_;
2608 print $txt;
2609 SDL::Events::pump_events();
2610 while (SDL::Events::poll_event($event)) {
2611 if ($event->type == SDL_QUIT || ($event->type == SDL_KEYDOWN && $event->key_sym == SDLK_ESCAPE)) {
2612 cleanup_and_exit();
2613 }
2614 }
2615 put_image($imgbin{loading_step}, 100 + $init_step*12, 10);
2616 if ($init_step == 0) {
2617 put_image($imgbin{loading_step_initial}, 100 + $_*12, 10) foreach 1..11;
2618 }
2619 SDL::Video::update_rect($app, 0, 0, 0, 0);
2620 $init_step++;
2621 }
2622
2623 sub load_levelset {
2624 my ($levelset_name) = @_;
2625
2626 -e $levelset_name or die "No such levelset ($levelset_name).\n";
2627
2628 $loaded_levelset = $levelset_name;
2629 my $row_numb = 0;
2630 my $curr_level = $levels{current};
2631
2632 %levels = ();
2633 $levels{current} = $curr_level;
2634 $lev_number = 1;
2635
2636 foreach my $line (cat_($levelset_name)) {
2637 if ($line !~ /\S/) {
2638 if ($row_numb) {
2639 $lev_number++;
2640 $row_numb = 0;
2641 }
2642 } else {
2643 my $col_numb = 0;
2644 foreach (split ' ', $line) {
2645 /-/ or push @{$levels{$lev_number}}, { cx => $col_numb, cy => $row_numb, img_num => $_ };
2646 $col_numb++;
2647 }
2648 $row_numb++;
2649 }
2650 }
2651 }
2652
2653 sub init_game() {
2654 -r "$FPATH/$_" or die "[*ERROR*] the datafiles seem to be missing! (could not read `$FPATH/$_')\n".
2655 " The datafiles need to go to `$FPATH'.\n"
2656 foreach qw(gfx snd data);
2657
2658 print '[SDL Init] ';
2659 # $app = SDL::App->new(
2660 # -icon => "$FPATH/gfx/pinguins/window_icon_penguin.png",
2661 # -flags => $sdl_flags | ($fullscreen ? SDL_FULLSCREEN : 0),
2662 # -title => 'Frozen-Bubble 2',
2663 # -width => 640,
2664 # -height => 480
2665 # );
2666
2667 SDL::init(SDL_INIT_EVERYTHING);
2668 $app = SDL::Video::set_video_mode(640, 480, 24, $sdl_flags | ($fullscreen ? SDL_FULLSCREEN : 0));
2669 unless ($app)
2670 {
2671
2672 warn "Couldn't make app ".SDL::get_error(). "\n Try software fallback";
2673 $app = SDL::Video::set_video_mode(640, 480, 24, SDL_SWSURFACE | ($fullscreen ? SDL_FULLSCREEN : 0));
2674 die "Couldn't make app ".SDL::get_error() unless $app;
2675
2676 }
2677 SDL::Video::wm_set_icon(SDL::Video::load_BMP("$FPATH/gfx/pinguins/window_icon_penguin.png"));
2678 SDL::Video::wm_set_caption('Frozen-Bubble 2', 'Frozen-Bubble 2');
2679
2680 my $joys = SDL::Joystick::num_joysticks();
2681 $joysticksinfo and print "\nfound $joys joystick(s)\n";
2682 for (my $i = 0; $i < $joys; $i++) {
•2683 my $jname = SDL::Joystick::name(SDL::Joystick::index($joysticks[$i])) || 'unknown joystick' ;
2684 push @joysticks, SDL::Joystick->new($i) unless $jname =~ /accelerometer/i;
2685 $joysticksinfo and print "\t" . ($i + 1) . ": $jname\n";
2686 }
2687 $frame = 0;
2688
2689 $apprects{main} = SDL::Rect->new( 0, 0, $app->w, $app->h);
2690 $event = SDL::Event->new;
2691 SDL::Events::enable_unicode(1);
2692 SDL::Mouse::show_cursor(0);
2693 $imgbin{loading} = add_image('loading.png');
2694 put_image($imgbin{loading}, 10, 10);
2695 SDL::Video::update_rect($app, 0, 0, 0, 0);
2696 $imgbin{loading_step} = add_image('loading_step.png');
2697 $imgbin{loading_step_initial} = add_image('loading_step_initial.png');
2698
2699 print_step('[Graphics');
2700 $imgbin{back_2p} = SDL::Image::load("$FPATH/gfx/backgrnd.png");
2701 $imgbin{back_1p} = SDL::Image::load("$FPATH/gfx/back_one_player.png");
2702 $imgbin{back_mp} = SDL::Image::load("$FPATH/gfx/back_multiplayer.png");
2703 $background = SDL::Surface->new( SDL_SWSURFACE, $app->w, $app->h, 32, 0, 0, 0, 0);
2704 $background_orig = SDL::Surface->new( SDL_SWSURFACE, $app->w, $app->h, 32, 0, 0, 0, 0);
2705
2706 Games::FrozenBubble::CStuff::sdlpango_init();
2707 $pangocontext{netdialogs} = { params => { desc => 'sans 10', fg => 'white', bg => 'black' } };
2708 $pangocontext{netdialogs_servermsg} = { params => { desc => 'sans italic 10', fg => 'white', bg => 'black' } };
2709 $pangocontext{menu} = { params => { desc => 'sans 11', fg => 'white', bg => 'black' } };
2710 $pangocontext{bold_menu} = { params => { desc => 'sans 11 bold', fg => 'white', bg => 'black' } };
2711 $pangocontext{ingame} = { params => { desc => 'sans 14', fg => 'white', bg => 'black' } };
2712 $pangocontext{ingame_chat} = { params => { desc => 'sans 10', fg => 'black', bg => 'white' } };
2713 $pangocontext{ingame_small} = { params => { desc => 'sans 8', fg => 'white', bg => 'black' } };
2714 $pangocontext{ingame_small_chat} = { params => { desc => 'sans 8', fg => 'white', bg => 'black' } };
2715 $pangocontext{$_}{context_fg} = Games::FrozenBubble::CStuff::sdlpango_createcontext($pangocontext{$_}{params}{fg}, $pangocontext{$_}{params}{desc}) foreach keys %pangocontext;
2716 $pangocontext{$_}{context_bg} = Games::FrozenBubble::CStuff::sdlpango_createcontext($pangocontext{$_}{params}{bg}, $pangocontext{$_}{params}{desc}) foreach keys %pangocontext;
2717
2718 foreach my $ball (1..8) {
2719 my $img = add_bubble_image('balls/bubble-'.($colourblind && 'colourblind-')."$ball.gif");
2720 $img_mini{$img} = add_image('balls/bubble-'.($colourblind && 'colourblind-')."${ball}-mini.png");
2721 }
2722 $bubbles_anim{white} = add_image("balls/bubble_prelight.png");
2723 $img_mini{$bubbles_anim{white}} = add_image("balls/bubble_prelight-mini.png");
2724 $bubbles_anim{lose} = add_image("balls/bubble_lose.png");
2725 $img_mini{$bubbles_anim{lose}} = add_image("balls/bubble_lose-mini.png");
2726 $bubbles_anim{on_top_next} = add_image("on_top_next.png");
2727 $img_mini{$bubbles_anim{on_top_next}} = add_image("on_top_next-mini.png");
2728 foreach my $step (0..6) {
2729 push @{$bubbles_anim{stick}}, my $img = add_image("balls/stick_effect_$step.png");
2730 $img_mini{$img} = add_image("balls/stick_effect_${step}-mini.png")
2731 }
2732
2733 $shooter_lowgfx = add_image("shooter-lowgfx.png");
2734 my $shooter = add_image("shooter.png");
2735 my $shooter_mini = add_image("shooter-mini.png");
2736 foreach my $number (-$CANON_ROTATIONS_NB..$CANON_ROTATIONS_NB) {
2737 my $angle = $number*($PI/2)/$CANON_ROTATIONS_NB;
2738
2739 # rendering all high-quality canons
2740 $canon{img}{$number} = SDL::Surface->new( SDL_SWSURFACE, $shooter->w, $shooter->h, 32, 0xFF000000, 0xFF0000, 0xFF00, 0xFF);
2741 Games::FrozenBubble::CStuff::rotate_bicubic($canon{img}{$number}, $shooter, $angle);
2742 $canon{data}{$number} = Games::FrozenBubble::CStuff::autopseudocrop($canon{img}{$number});
2743 #- now crop (and use native RGBA ordering)
2744 my $replace = SDL::Surface->new( SDL_SWSURFACE, $canon{data}{$number}[2], $canon{data}{$number}[3], 32, 0xFF000000, 0xFF0000, 0xFF00, 0xFF);
2745 SDL::Video::set_alpha($canon{img}{$number}, 0, 0);
2746 SDL::Video::blit_surface( $canon{img}{$number}, SDL::Rect->new( $canon{data}{$number}[0], $canon{data}{$number}[1],
2747 $canon{data}{$number}[2], $canon{data}{$number}[3]),
2748 $replace, SDL::Rect->new(0, 0, $canon{img}{$number}->w, $canon{img}{$number}->h));
2749 $canon{img}{$number} = $replace;
2750 add_default_rect($canon{img}{$number});
2751
2752 # rendering all mid-quality canons
2753 $canon{img_mini}{$number} = SDL::Surface->new( SDL_SWSURFACE, $shooter_mini->w, $shooter_mini->h, 32, 0xFF000000, 0xFF0000, 0xFF00, 0xFF);
2754 Games::FrozenBubble::CStuff::rotate_bicubic($canon{img_mini}{$number}, $shooter_mini, $angle);
2755 $canon{data_mini}{$number} = Games::FrozenBubble::CStuff::autopseudocrop($canon{img_mini}{$number});
2756 #- now crop (and use native RGBA ordering)
2757 my $replace2 = SDL::Surface->new( SDL_SWSURFACE, $canon{data_mini}{$number}[2], $canon{data_mini}{$number}[3], 32, 0xFF000000, 0xFF0000, 0xFF00, 0xFF);
2758 SDL::Video::set_alpha($canon{img_mini}{$number}, 0, 0);
2759 SDL::Video::blit_surface( $canon{img_mini}{$number}, SDL::Rect->new( $canon{data_mini}{$number}[0], $canon{data_mini}{$number}[1],
2760 $canon{data_mini}{$number}[2], $canon{data_mini}{$number}[3]), $replace2,
2761 SDL::Rect->new(0,0,$canon{img_mini}{$number}->w,$canon{img_mini}{$number}->h));
2762 $canon{img_mini}{$number} = $replace2;
2763 add_default_rect($canon{img_mini}{$number});
2764
2765 $number eq -$CANON_ROTATIONS_NB/2 and print_step('.');
2766 $number eq 0 and print_step('.');
2767 $number eq $CANON_ROTATIONS_NB/2 and print_step('.');
2768 }
2769
2770 print_step('.');
2771 $malus_gfx{banane} = add_image('banane.png');
2772 $img_mini{$malus_gfx{banane}} = add_image('banane-mini.png');
2773 $malus_gfx{tomate} = add_image('tomate.png');
2774 $img_mini{$malus_gfx{tomate}} = add_image('tomate-mini.png');
2775
2776 $imgbin{back_paused} = add_image('back_paused.png');
2777 push @{$imgbin{paused}}, add_image("pause_00$_.png") foreach '01'..'35';
2778 $imgbin{lose} = add_image('lose_panel.png');
2779 $imgbin{progress_red} = add_image('dot_red.png');
2780 $imgbin{progress_green} = add_image('dot_green.png');
2781 $imgbin{win_panel_1player} = add_image('win_panel_1player.png');
2782 $imgbin{win_panel_p1_net} = add_image('win_panel_p1_net.png');
2783 $imgbin{compressor_main} = add_image('compressor_main.png');
2784 $imgbin{compressor_ext} = add_image('compressor_ext.png');
2785
2786 $imgbin{back_menu} = SDL::Image::load( "$FPATH/gfx/menu/back_start.png");
2787 $imgbin{stamp} = add_image('menu/stamp.png');
2788 $imgbin{menu_closedeye_green_left} = add_image('menu/backgrnd-closedeye-left-green.png');
2789 $imgbin{menu_closedeye_green_right} = add_image('menu/backgrnd-closedeye-right-green.png');
2790 $imgbin{menu_closedeye_purple_left} = add_image('menu/backgrnd-closedeye-left-purple.png');
2791 $imgbin{menu_closedeye_purple_right} = add_image('menu/backgrnd-closedeye-right-purple.png');
2792 $imgbin{menu_logo} = add_image('menu/fblogo.png');
2793 $imgbin{menu_logo_mask} = add_image('menu/fblogo-mask.png');
2794 $imgbin{txt_1pgame_off} = add_image('menu/txt_1pgame_off.png');
2795 $imgbin{txt_1pgame_over} = add_image('menu/txt_1pgame_over.png');
2796 $imgbin{txt_2pgame_off} = add_image('menu/txt_2pgame_off.png');
2797 $imgbin{txt_2pgame_over} = add_image('menu/txt_2pgame_over.png');
2798 $imgbin{txt_netgame_off} = add_image('menu/txt_netgame_off.png');
2799 $imgbin{txt_netgame_over} = add_image('menu/txt_netgame_over.png');
2800 $imgbin{txt_langame_off} = add_image('menu/txt_langame_off.png');
2801 $imgbin{txt_langame_over} = add_image('menu/txt_langame_over.png');
2802 $imgbin{txt_editor_off} = add_image('menu/txt_editor_off.png');
2803 $imgbin{txt_editor_over} = add_image('menu/txt_editor_over.png');
2804 $imgbin{txt_keys_off} = add_image('menu/txt_keys_off.png');
2805 $imgbin{txt_keys_over} = add_image('menu/txt_keys_over.png');
2806 $imgbin{txt_graphics_off} = add_image('menu/txt_graphics_off.png');
2807 $imgbin{txt_graphics_over} = add_image('menu/txt_graphics_over.png');
2808 $imgbin{txt_highscores_off} = add_image('menu/txt_highscores_off.png');
2809 $imgbin{txt_highscores_over} = add_image('menu/txt_highscores_over.png');
2810 $imgbin{void_panel} = add_image('menu/void_panel.png');
2811 $imgbin{'1p_panel'} = add_image('menu/1p_panel.png');
2812 $imgbin{void_chat} = add_image('void_chat.png');
2813 $imgbin{void_chat_small_p2} = add_image('void_chat_small_p2.png');
2814 $imgbin{void_chat_small_rp1_rp3} = add_image('void_chat_small_rp1_rp3.png');
2815 $imgbin{void_chat_small_rp2_rp4} = add_image('void_chat_small_rp2_rp4.png');
2816 $imgbin{void_mp_training} = add_image('void_mp_training.png');
2817 $imgbin{ping_low} = add_image('menu/ping-low.png');
2818 $imgbin{ping_mid} = add_image('menu/ping-mid.png');
2819 $imgbin{ping_high} = add_image('menu/ping-high.png');
2820 $imgbin{menu_cursor}{'1pgame'} = [ map { add_image("menu/anims/1pgame_00$_.png") } ('01'..'30') ];
2821 $imgbin{menu_cursor}{'2pgame'} = [ map { add_image("menu/anims/p1p2_00$_.png") } ('01'..'30') ];
2822 $imgbin{menu_cursor}{langame} = [ map { add_image("menu/anims/langame_00$_.png") } ('01'..'70') ];
2823 $imgbin{menu_cursor}{netgame} = [ map { add_image("menu/anims/netgame_00$_.png") } ('01'..'89') ];
2824 $imgbin{menu_cursor}{editor} = [ map { add_image("menu/anims/editor_00$_.png") } ('01'..'67') ];
2825 $imgbin{menu_cursor}{graphics3} = [ map { add_image("menu/anims/gfx-l1_00$_.png") } ('01'..'30') ];
2826 $imgbin{menu_cursor}{graphics2} = [ map { add_image("menu/anims/gfx-l2_00$_.png") } ('01'..'30') ];
2827 $imgbin{menu_cursor}{graphics1} = [ add_image("menu/anims/gfx-l3_0001.png") ];
2828 $imgbin{menu_cursor}{keys} = [ map { add_image("menu/anims/keys_00$_.png") } ('01'..'80') ];
2829 $imgbin{menu_cursor}{highscores} = [ map { add_image("menu/anims/highscore_00$_.png") } ('01'..'89') ];
2830 my $flags = SDL_ALPHA_OPAQUE;
2831 foreach my $cursortype (keys %{$imgbin{menu_cursor}}) {
2832 foreach my $img (@{$imgbin{menu_cursor}{$cursortype}}) {
2833
2834 my $alpha = SDL::Surface->new( SDL_SWSURFACE, $img->w, $img->h, 32, 0xFF000000,0xFF0000,0xFF00,0xFF);
2835 SDL::Video::set_alpha($img, $flags, 0 ); #- for RGBA->RGBA blits, SDL_SRCALPHA must be removed or destination alpha is preserved
2836 SDL::Video::blit_surface($img, SDL::Rect->new(0,0,$img->w,$img->h), $alpha, SDL::Rect->new(0,0,$img->w,$img->h));
2837 Games::FrozenBubble::CStuff::alphaize($alpha);
2838 push @{$imgbin{menu_cursor}{"${cursortype}alpha"}}, $alpha;
2839 SDL::Video::set_alpha($img, SDL_SRCALPHA | SDL_ALPHA_OPAQUE, 0);
2840 }
2841 }
2842 $imgbin{left_rp1} = add_image('left-rp1.png');
2843 $imgbin{"left_${_}_mini"} = add_image("left-${_}-mini.png") foreach qw(rp1 rp2 rp3 rp4);
2844 $imgbin{highlight_server} = add_image('menu/highlight-server.png');
2845
2846 #- little flags
2847 foreach my $f (glob("$FPATH/gfx/flags/*.png")) {
2848 $f =~ /flag-(\S+)\.png/;
2849 $imgbin{flag}{$1} = add_image_file($f);
2850 }
2851
2852 my @levelsets = sort glob("$FBLEVELS/*");
2853
2854 #- scrolling banner
2855 $imgbin{banner_artwork} = add_image('menu/banner_artwork.png');
2856 $imgbin{banner_soundtrack} = add_image('menu/banner_soundtrack.png');
2857 $imgbin{banner_cpucontrol} = add_image('menu/banner_cpucontrol.png');
2858 $imgbin{banner_leveleditor} = add_image('menu/banner_leveleditor.png');
2859
2860 $MENUPOS{xpos_panel} = (640 - $imgbin{void_panel}->w) / 2;
2861 $MENUPOS{ypos_panel} = (480 - $imgbin{void_panel}->h) / 2;
2862
2863 #- 1p and 2p menu images
2864 $imgbin{txt_1pmenu_off} = add_image('menu/txt_menu_1p_off.png');
2865 $imgbin{txt_1pmenu_over} = add_image('menu/txt_menu_1p_over.png');
2866 $imgbin{txt_1pmenu_play_all_levels_text} = add_image('menu/txt_play_all_levels_text.png');
2867 $imgbin{txt_1pmenu_play_all_levels_outlined_text} = add_image('menu/txt_play_all_levels_outlined_text.png');
2868 $imgbin{txt_1pmenu_pick_start_level_text} = add_image('menu/txt_pick_start_level_text.png');
2869 $imgbin{txt_1pmenu_pick_start_level_outlined_text} = add_image('menu/txt_pick_start_level_outlined_text.png');
2870 $imgbin{txt_1pmenu_play_random_levels_text} = add_image('menu/txt_play_random_levels_text.png');
2871 $imgbin{txt_1pmenu_play_random_levels_outlined_text} = add_image('menu/txt_play_random_levels_outlined_text.png');
2872 $imgbin{txt_1pmenu_mp_train_text} = add_image('menu/txt_multiplayer_training_text.png');
2873 $imgbin{txt_1pmenu_mp_train_outlined_text} = add_image('menu/txt_multiplayer_training_outlined_text.png');
2874
2875 #- net game setup images
2876 $imgbin{back_netgame} = add_image('back_netgame.png');
2877 $imgbin{netspot_free} = add_image('netspot.png');
2878 $imgbin{netspot_playing} = add_image('netspot-playing.png');
2879 $imgbin{netspot_insamegame} = add_image('netspot-insamegame.png');
2880 $imgbin{netspot_self} = [ map { add_image("netspot-self-$_.png") } qw(1 2 3 4 5 6 7 8 9 A B C D) ];
2881
2882 #- hiscore
2883 $imgbin{back_hiscores} = add_image('back_hiscores.png');
2884 $imgbin{hiscore_frame} = add_image('hiscore_frame.png');
2885 $imgbin{hiscore_levelset} = add_image('hiscore-levelset.png');
2886 $imgbin{hiscore_mptraining} = add_image('hiscore-mptraining.png');
2887
2888 local @PLAYERS = @ALL_PLAYERS; #- load all images even if -so commandline option was passed
2889 iter_players {
2890 print_step('.');
2891 $imgbin{hurry}{$::p} = add_image("hurry_$::p.png");
2892 $imgbin{win}{$::p} = add_image("win_panel_$::p.png");
2893 $::p ne 'p2' and $imgbin{net_lose}{$::p} = add_image("net_lose_$::p.png");
2894 if ($::p =~ /^r/) {
2895 $imgbin{attack}{$::p} = add_image("attack_$::p.png");
2896 $imgbin{attackme}{$::p} = add_image("attackme_$::p.png");
2897 }
2898 $pdata{$::p}{score} = 0;
2899 my $p = $::p;
2900 $pinguin{$::p}{normal} = [ add_image("pinguins/anime-shooter_${p}_0020.png") ];
2901 $pinguin{$::p}{action} = [ map { add_image("pinguins/anime-shooter_${p}_00$_.png") } (21..50) ];
2902 $pinguin{$::p}{left_to} = [ map { add_image("pinguins/anime-shooter_${p}_00$_.png") } reverse ('02'..'19') ];
2903 $pinguin{$::p}{left} = [ add_image("pinguins/anime-shooter_${p}_0001.png") ];
2904 $pinguin{$::p}{left_from} = [ map { add_image("pinguins/anime-shooter_${p}_00$_.png") } ('02'..'19') ];
2905 $pinguin{$::p}{right_to} = [ map { add_image("pinguins/anime-shooter_${p}_00$_.png") } (51..70) ];
2906 $pinguin{$::p}{right} = [ add_image("pinguins/anime-shooter_${p}_0071.png") ];
2907 $pinguin{$::p}{right_from} = [ map { add_image("pinguins/anime-shooter_${p}_00$_.png") } reverse (51..71) ];
2908 $pinguin{$::p}{wait_to} = [ map { add_image("pinguins/wait_${p}_00$_.png") } ('01'..'74') ];
2909 $pinguin{$::p}{wait} = [ map { add_image("pinguins/wait_${p}_00$_.png") } (75..97) ];
2910 $pinguin{$::p}{win} = [ map { add_image("pinguins/win_${p}_00$_.png") } ('01'..'68') ];
2911 $pinguin{$::p}{lose_to} = [ map { add_image("pinguins/loose_${p}_00$_.png") } ('01'..'64') ];
2912 $pinguin{$::p}{lose} = [ map { add_image("pinguins/loose_${p}_0$_.png") } ('065'..'158') ];
2913 };
2914
2915 print_step('] ');
2916
2917 if ($mixer eq 'SOUND_DISABLED') {
2918 $mixer_enabled = 0;
2919 $mixer = undef;
2920 } elsif (!defined($mixer_enabled) || $mixer_enabled) {
2921 $mixer_enabled = init_sound();
2922 }
2923
2924 #- the RGBA effects algorithms assume little endian RGBA surfaces
2925 #my $replace = SDL::Surface->new( SDL_SWSURFACE, $imgbin{menu_logo}->w, $imgbin{menu_logo}->h, 32, 0, 0, 0, 0);
2926 #SDL::Video::set_alpha($imgbin{menu_logo}, SDL_SRCALPHA, 0); #- for RGBA->RGBA blits, SDL_SRCALPHA must be removed or destination alpha is preserved
2927 #SDL::Video::blit_surface($imgbin{menu_logo}, SDL::Rect->new(0,0,$imgbin{menu_logo}->w,$imgbin{menu_logo}->h), $replace, SDL::Rect->new(0,0,$imgbin{menu_logo}->w,$imgbin{menu_logo}->h));
2928 # $imgbin{menu_logo} = $replace;
2929 add_default_rect($imgbin{menu_logo} );
2930
2931 $lev_number = 0;
2932 load_levelset("$FPATH/data/levels");
2933
2934 Games::FrozenBubble::CStuff::init_effects($FPATH);
2935 $addicted_time = 0;
•2936 $total_launched_bubbles = 0;
2937
2938 $start_time = 0;
2939 print "Ready.\n";
2940 }
2941
2942 sub open_level($) {
2943 my ($level) = @_;
2944
2945 $level eq 'WON' and $level = $lev_number;
2946
2947 $levels{$level} or die "No such level or void level ($level).\n";
2948 foreach my $l (@{$levels{$level}}) {
2949 iter_players {
2950 my $img = $l->{img_num} =~ /^\d+$/ ? $bubbles_images[$l->{img_num}] : $bubbles_anim{lose};
2951 real_stick_bubble(create_bubble_given_img($img), $l->{cx}, $l->{cy}, $::p, 0);
2952 };
2953 }
2954 }
2955
2956 sub translate_joystick_tokey($) {
2957 my ($event) = @_;
2958 my $which = $event->jaxis_which;
2959 if ($event->type == SDL_JOYAXISMOTION) {
2960 my $axis = $event->jaxis_axis;
2961 my $value = $event->jaxis_value;
2962 if ($value <= -10000) { #- should work properly with analog joysticks
2963 return "joystick|axisvalue|$which|$axis|-10000";
2964 } elsif ($value >= 10000) {
2965 return "joystick|axisvalue|$which|$axis|10000";
2966 } else {
2967 return "joystick|axisvalue|$which|$axis|0";
2968 }
2969 } elsif ($event->type() == SDL_JOYBUTTONDOWN) {
2970 my $button = $event->jbutton_button + 1;
2971 return "joystick|buttondown|$which|$button";
2972 } elsif ($event->type() == SDL_JOYBUTTONUP) {
2973 my $button = $event->jbutton_button + 1;
2974 return "joystick|buttonup|$which|$button";
2975 }
2976 }
2977
2978 sub extended_keypress($) {
2979 my ($event) = @_;
2980 if ($event->type == SDL_KEYDOWN) {
2981 return $event->key_sym;
2982 } elsif ($event->type == SDL_JOYAXISMOTION || $event->type() == SDL_JOYBUTTONDOWN) {
2983 my $keypressed = translate_joystick_tokey($event);
2984 if ($keypressed =~ /^joystick\|axisvalue\|\d+\|\d+\|0$/) { #- we treat position at 0 as KEYUP
2985 $keypressed = undef;
2986 }
2987 return $keypressed;
2988 }
2989 }
2990
2991 sub grab_key {
2992 my $keyp;
2993
2994 do {
2995 SDL::Events::wait_event($event);
2996 if ($event->type == SDL_KEYDOWN) {
2997 $keyp = $event->key_sym;
2998 } elsif ($event->type == SDL_JOYAXISMOTION || $event->type() == SDL_JOYBUTTONDOWN) {
2999 $keyp = translate_joystick_tokey($event);
3000 }
3001 } while (!defined($keyp));
3002
3003 #- so that using "capital" letter should work
3004 if (member($keyp, SDLK_LSHIFT(), SDLK_RSHIFT())) {
3005 return grab_key();
3006 } else {
3007 return $keyp;
3008 }
3009 }
3010
3011 sub display_highscores {
3012 my ($type, $new_entry) = @_;
3013
3014 $display_on_app_disabled = 1;
3015 @PLAYERS = ('p1');
3016 %POS = %POS_1P;
3017
3018 if ($type eq 'levels' || !defined($type)) {
3019 SDL::Video::blit_surface($imgbin{back_hiscores}, $apprects{main}, $app, $apprects{main});
3020 put_image($imgbin{hiscore_levelset}, 640 - 10 - $imgbin{hiscore_levelset}->w, 8);
3021
3022 my $initial_high_posx = 90;
3023 my ($high_posx, $high_posy) = ($initial_high_posx, 68);
3024 my $high_rect = SDL::Rect->new($POS{p1}{left_limit} & 0xFFFFFFFC, $POS{p1}{top_limit} & 0xFFFFFFFC,
3025 ($POS{p1}{right_limit}-$POS{p1}{left_limit}) & 0xFFFFFFFC, ($POS{p1}{'initial_bubble_y'}-$POS{p1}{top_limit}-10) & 0xFFFFFFFC);
3026
3027 my $centered_print = sub($$$) {
3028 my ($x, $y, $txt, $bold) = @_;
3029 print_($bold ? 'bold_menu' : 'menu', $app, $x, $y + $imgbin{hiscore_frame}->h - 8, $txt, $imgbin{hiscore_frame}->w + 12, 'center');
3030 };
3031
3032 my $old_levelset = $loaded_levelset;
3033
3034 foreach my $high (ordered_highscores()) {
3035 @{$sticked_bubbles{p1}} = ();
3036 @{$root_bubbles{p1}} = ();
3037 $pdata{p1}{newrootlevel} = 0;
3038 $pdata{p1}{oddswap} = 0;
3039 SDL::Video::blit_surface($imgbin{back_1p}, $high_rect, $background, $high_rect);
3040
3041 # try to get it from the default-levelset. If we can't, default to the
3042 # last level in the default levelset
3043 if (!$high->{piclevel}) {
3044 $loaded_levelset ne "$FPATH/data/levels" and load_levelset("$FPATH/data/levels");
3045
3046 # handle the case where the user has edited/created a levelset with more levels
3047 # than the default levelset and then got a high score
3048 if ($high->{level} > $lev_number) {
3049 open_level($lev_number);
3050 } else {
3051 open_level($high->{level});
3052 }
3053 } else {
3054 # this is the normal case. just load the level that the file tells us
3055 if ($loaded_levelset ne "$FBHOME/highlevelshistory") {
3056 load_levelset("$FBHOME/highlevelshistory");
3057 }
3058 open_level($high->{piclevel});
3059 }
3060
3061 put_image($imgbin{hiscore_frame}, $high_posx - 7, $high_posy - 6);
3062 my $tmp = SDL::Surface->new(SDL_SWSURFACE, $high_rect->w/4, $high_rect->h/4, 32);
3063 Games::FrozenBubble::CStuff::shrink($tmp, $background, 0, 0, $high_rect, 4);
3064 SDL::Video::blit_surface($tmp, SDL::Rect->new(0,0,$tmp->w,$tmp->h), $app, SDL::Rect->new($high_posx, $high_posy, $tmp->w, $tmp->h));
3065 $centered_print->($high_posx - 15, $high_posy, $high->{name}, $new_entry == $high);
3066 $centered_print->($high_posx - 15, $high_posy + 20, $high->{level} eq 'WON' ? loc("won!") : loc("level %s", i18n_number($high->{level})), $new_entry == $high);
3067 my $min = int($high->{time}/60);
3068 my $sec = int($high->{time} - $min*60); length($sec) == 1 and $sec = "0$sec";
3069 $centered_print->($high_posx - 15, $high_posy + 40, loc("%s'%s\"", i18n_number($min), i18n_number($sec)), $new_entry == $high);
3070 $high_posx += 98;
3071 $high_posx > 550 and $high_posx = $initial_high_posx, $high_posy += 175;
3072 $high_posy > 440 and last;
3073 }
3074 load_levelset($old_levelset);
3075
3076 SDL::Video::update_rect($app, 0, 0, 0, 0);
3077
3078 SDL::Events::pump_events() while SDL::Events::poll_event($event) != 0;
3079 grab_key() eq SDLK_ESCAPE() and return;
3080 }
3081
3082 if (($type eq 'mptrain' || !defined($type)) && (@$HISCORES_MPTRAIN || @$HISCORES_MPTRAIN_CHAINREACTION)) {
3083 SDL::Video::blit_surface($imgbin{back_hiscores}, $apprects{main}, $app, $apprects{main});
3084 put_image($imgbin{hiscore_mptraining}, 640 - 10 - $imgbin{hiscore_mptraining}->w, 8);
3085
3086 print_('menu', $app, 0, 50, loc("Regular"), 320, 'center');
3087 my %parts = (rank => { xpos => 80, width => 40 },
3088 name => { xpos => 120, width => 150 });
3089 if ($is_rtl) {
3090 $parts{$_}{xpos} = 640 - $parts{$_}{xpos} - $parts{$_}{width} foreach keys %parts;
3091 }
3092 my $y = 80;
3093 my $counter = 1;
3094 my $lastvalue;
3095 foreach my $high (ordered_mptrain_highscores()) {
3096 my $font = $new_entry == $high ? 'bold_menu' : 'menu';
3097 $high->{score} ne $lastvalue and print_($font, $app, $parts{rank}{xpos}, $y, "$counter. ", $parts{rank}{width}, 'right');
3098 print_($font, $app, $parts{name}{xpos}, $y, "$high->{name}: $high->{score}", $parts{name}{width});
3099 $y += $smg_lineheight + 2;
3100 $counter++;
3101 $lastvalue = $high->{score};
3102 }
3103
3104 print_('menu', $app, 320, 50, loc("Chain-reaction enabled"), 320, 'center');
3105 %parts = (rank => { xpos => 420, width => 40 },
3106 name => { xpos => 460, width => 150 });
3107 if ($is_rtl) {
3108 $parts{$_}{xpos} = 640 - $parts{$_}{xpos} - $parts{$_}{width} foreach keys %parts;
3109 }
3110 $y = 80;
3111 $counter = 1;
3112 $lastvalue = undef;
3113 foreach my $high (ordered_mptrain_highscores_chainreaction()) {
3114 my $font = $new_entry == $high ? 'bold_menu' : 'menu';
3115 $high->{score} ne $lastvalue and print_($font, $app, $parts{rank}{xpos}, $y, "$counter. ", $parts{rank}{width}, 'right');
3116 print_($font, $app, $parts{name}{xpos}, $y, "$high->{name}: $high->{score}", $parts{name}{width});
3117 $y += $smg_lineheight + 2;
3118 $counter++;
3119 $lastvalue = $high->{score};
3120 }
3121
3122 SDL::Video::update_rect($app, 0, 0, 0, 0);
3123
3124 SDL::Events::pump_events() while SDL::Events::poll_event($event) != 0;
3125 grab_key() eq SDLK_ESCAPE() and die "quit";
3126 }
3127
3128 $display_on_app_disabled = 0;
3129 }
3130
3131 sub keysym_to_char($) {
3132 my ($key) = @_;
3133 my $name = SDL::Events::get_key_name($key);
3134 return uc($name) if $name;
3135 # we will remove the below and @fbsyms::syms after testing
3136 eval("$key eq SDLK_$_()") and return uc($_) foreach @Games::FrozenBubble::Symbols::syms;
3137 if ($key >= 160 && $key <= 255) {
3138 return 'WORLD_' . ($key - 160); #- "world" keys are not exported
3139 }
3140 }
3141
3142 sub ask_from($) {
3143 my ($w) = @_;
3144 # $w->{intro} = [ 'text_intro_line1', 'text_intro_line2', ... ]
3145 # $w->{entries} = [ { q => 'question1?', a => \$var_answer1, f => 'flags' }, {...} ] flags: ONE_CHAR, SPACE
3146 # $w->{outro} = 'text_outro_uniline'
3147 # $w->{erase_background} = $background_right_one
3148
3149 put_image($imgbin{void_panel}, $MENUPOS{xpos_panel}, $MENUPOS{ypos_panel});
3150
3151 my $ypos = $MENUPOS{ypos_panel} + 12;
3152 my $lineheight = 18;
3153 my %xpos = ( questions => $is_rtl ? $MENUPOS{xpos_panel} + $imgbin{void_panel}->w*1/3 + 10 : $MENUPOS{xpos_panel},
3154 echo => $is_rtl ? $MENUPOS{xpos_panel} + $imgbin{void_panel}->w*1/3 - 100 : $MENUPOS{xpos_panel} + $imgbin{void_panel}->w*2/3 );
3155
3156 foreach my $i (@{$w->{intro}}) {
3157 print_('menu', $app, $MENUPOS{xpos_panel}, $ypos, $i, $imgbin{void_panel}->w, 'center') if $i;
3158 $ypos += $lineheight;
3159 }
3160
3161 $ypos += 10;
3162
3163 my $ok = 1;
3164 SDL::Events::enable_key_repeat(200, 50);
3165 ask_from_entries:
3166 foreach my $entry (@{$w->{entries}}) {
3167 #- in case wrapping occurred
3168 SDL::Video::blit_surface($imgbin{void_panel}, SDL::Rect->new(10, $ypos - $MENUPOS{ypos_panel}, $imgbin{void_panel}->w - 20, 30), $app,
3169 SDL::Rect->new($MENUPOS{xpos_panel} + 10, $ypos, $imgbin{void_panel}->w, $imgbin{void_panel}->h));
3170 print_('menu', $app, $xpos{questions}, $ypos, $entry->{'q'}, $imgbin{void_panel}->w*2/3 - 10, @{$w->{entries}} == 1 ? 'center' : 'right');
3171 SDL::Video::update_rect($app, 0, 0, 0, 0);
3172 my $srect_mulchar_redraw = SDL::Rect->new($xpos{echo} - 3 - $MENUPOS{xpos_panel}, $ypos - $MENUPOS{ypos_panel}, $imgbin{void_panel}->w*1/3, 30);
3173 my $drect_mulchar_redraw = SDL::Rect->new($xpos{echo} - 3, $ypos, $imgbin{void_panel}->w, $imgbin{void_panel}->h);
3174 my $x_echo = $xpos{echo};
3175 my $txt;
3176 if ($entry->{f} ne 'SPACE') {
3177 if ($entry->{f} eq 'ONE_CHAR') {
3178 my $k;
3179 while (!defined($k)) {
3180 $k = grab_key();
3181 if ($k =~ /^joystick\|axisvalue\|\d+\|\d+\|0$/) { #- we treat position at 0 as KEYUP
3182 $k = undef;
3183 }
3184 }
3185 $no_echo or play_sound('typewriter');
3186 $k == SDLK_ESCAPE and $ok = 0, last ask_from_entries;
3187 $txt = $k;
3188 if ($k =~ /^joystick\|axisvalue\|(\d+)\|(\d+)\|([-\d]+)/) {
3189 my $num = @joysticks > 1 ? $1 + 1 : '';
3190 $k = 'joy' . i18n_number($num) . '-' . (even($2) ? ($3 < 0 ? loc("left") : loc("right")) : ($3 < 0 ? loc("up") : loc("down")));
3191 } elsif ($k =~ /^joystick\|buttondown\|(\d+)\|(\d+)/) {
3192 my $num = @joysticks > 1 ? $1 + 1 : '';
3193 my $button = $2 + 1;
3194 $k = 'joy' . i18n_number($num) . '-' . loc("button") . i18n_number($2);
3195 } else {
3196 $k = keysym_to_char($k);
3197 }
3198 print_('menu', $app, $x_echo, $ypos, $k, 100, $is_rtl ? 'right' : 'left'); #- always in ASCII so need to tell it to go right in RTL
3199 } else {
3200 callback_entry('reset');
3201 ask_from_main_loop:
3202 while (1) {
3203 if (callback_entry('ping')) {
3204 SDL::Video::blit_surface($imgbin{void_panel}, $srect_mulchar_redraw, $app, $drect_mulchar_redraw);
3205 callback_entry('print', { xpos => $x_echo, ypos => $ypos, maxlen => 100, font => 'menu' });
3206 }
3207 SDL::Video::update_rect($app, 0, 0, 0, 0);
3208 SDL::Events::pump_events();
3209 while (SDL::Events::poll_event($event) != 0) {
3210 if ($event->type == SDL_KEYDOWN) {
3211 my $k = $event->key_sym;
3212 if ($k == SDLK_ESCAPE()) {
3213 $ok = 0;
3214 last ask_from_entries;
3215 } elsif ($k == SDLK_RETURN() || $k == SDLK_KP_ENTER()) {
3216 $txt = join('', callback_entry('gettext'));
3217 last ask_from_main_loop;
3218 } else {
3219 callback_entry('keypressed', { event => $event, maxlen => 100, font => 'menu' });
3220 SDL::Video::blit_surface($imgbin{void_panel}, $srect_mulchar_redraw, $app, $drect_mulchar_redraw);
3221 callback_entry('moved');
3222 callback_entry('print', { xpos => $x_echo, ypos => $ypos, maxlen => 100, font => 'menu' });
3223 }
3224 }
3225 }
3226 Games::FrozenBubble::CStuff::fbdelay($TARGET_ANIM_SPEED);
3227 }
3228 }
3229 }
3230 $entry->{answer} = $txt;
3231 $ypos += $entry->{f} eq 'SPACE' ? $lineheight / 2 : $lineheight;
3232 }
3233 SDL::Events::enable_key_repeat(0, 0);
3234
3235 if ($ok) {
3236 ${$_->{a}} = $_->{answer} foreach @{$w->{entries}};
3237 print_('menu', $app, $MENUPOS{xpos_panel}, $MENUPOS{ypos_panel} + $imgbin{void_panel}->h - 35, $w->{outro}, $imgbin{void_panel}->w, 'center');
3238 SDL::Video::update_rect($app, 0, 0, 0, 0);
3239 play_sound('menu_selected');
3240 sleep 2;
3241 } else {
3242 play_sound('cancel');
3243 }
3244
3245 exists $w->{erase_background} and erase_image_from($imgbin{void_panel}, $MENUPOS{xpos_panel}, $MENUPOS{ypos_panel}, $w->{erase_background});
3246 SDL::Video::update_rect($app, 0, 0, 0, 0);
3247 SDL::Events::pump_events() while SDL::Events::poll_event($event) != 0;
3248
3249 return $ok;
3250 }
3251
3252 sub new_game() {
3253
3254 my $ticks = SDL::get_ticks();
3255 $display_on_app_disabled = 1;
3256
3257 $TIME_APPEARS_NEW_ROOT = 11;
3258 $TIME_HURRY_WARN = 250;
3259 $TIME_HURRY_MAX = 375;
3260
3261 #- reset chat messages from last game, if any
3262 $pdata{current_chat_messages}{$_} = undef foreach @ALL_PLAYERS;
3263
3264 my $backgr;
3265 if (is_mp_game()) {
3266 $pdata{p1}{chatting} and cleanup_chatting();
3267 if (@PLAYERS == 2) { #- in net/lan 2p mode, use bigger graphics and positions
3268 $backgr = $imgbin{back_2p};
3269 %POS = %POS_2P;
3270 } else {
3271 $backgr = $imgbin{back_mp};
3272 %POS = %POS_MP;
3273 }
3274 $pdata{inconsistency} = undef;
3275 } elsif (is_2p_game()) {
3276 $backgr = $imgbin{back_2p};
3277 %POS = %POS_2P;
3278 } elsif (is_1p_game()) {
3279 $backgr = $imgbin{back_1p};
3280 %POS = %POS_1P;
3281 if ($levels{current} eq 'mp_train') {
3282 $pdata{$PLAYERS[0]}{score} = 0;
3283 } else {
3284 if ($levels{current} ne 'random') {
3285 $chainreaction = 0;
3286 }
3287 $TIME_APPEARS_NEW_ROOT = 8;
3288 $TIME_HURRY_WARN = 400;
3289 $TIME_HURRY_MAX = 525;
3290 $pdata{$PLAYERS[0]}{score} = $levels{current};
3291 }
3292 } else {
3293 die "oops";
3294 }
3295
3296 SDL::Video::blit_surface($backgr, $apprects{main}, $background_orig, $apprects{main});
3297 if ($levels{current} eq 'mp_train') {
3298 my $drect = SDL::Rect->new(32, 152, $imgbin{void_mp_training}->w, $imgbin{void_mp_training}->h);
3299 SDL::Video::blit_surface($imgbin{void_mp_training}, $rects{$imgbin{void_mp_training}}, $background_orig, $drect);
3300 }
3301 SDL::Video::blit_surface($background_orig, $apprects{main}, $background, $apprects{main});
3302
3303 iter_players {
3304 $actions{$::p}{$_} = 0 foreach qw(left right fire center);
3305 $angle{$::p} = $PI/2;
3306 @{$sticked_bubbles{$::p}} = ();
3307 @{$malus_bubble{$::p}} = ();
3308 @{$root_bubbles{$::p}} = ();
3309 @{$falling_bubble{$::p}} = ();
3310 @{$exploding_bubble{$::p}} = ();
3311 delete $pdata{$::p}{nextcolors};
3312 @{$chains{$::p}{falling_chained}} = ();
3313 %{$chains{$::p}{chained_bubbles}} = ();
3314 $launched_bubble{$::p} = undef;
3315 $sticking_bubble{$::p} = undef;
3316 $pdata{$::p}{$_} = 0 foreach qw(newroot newroot_prelight oddswap hurry newrootlevel);
3317 @{$pdata{$::p}{malus}} = ();
3318 $pdata{$::p}{state} = 'ingame';
3319 $pdata{$::p}{ping_right}{img} = 0;
3320 $pdata{$::p}{ping_right}{state} = 'normal';
3321 $pdata{$::p}{hurry_save_img} = undef;
3322 $apprects{$::p} = SDL::Rect->new( $POS{$::p}{left_limit}, $POS{$::p}{top_limit},
3323 $POS{$::p}{right_limit}-$POS{$::p}{left_limit}, $POS{$::p}{'initial_bubble_y'}-$POS{$::p}{top_limit});
3324 if (is_distant_player($::p)) {
3325 if (!$pdata{$::p}{left}) {
3326 $pdata{$::p}{still_game_messages} = 1;
3327 $pdata{$::p}{ready4newgame} = 0;
3328 }
3329 }
3330 };
3331
3332 print_scores($background);
3333 if ($levels{current} eq 'mp_train') {
3334 mp_train_print_time();
3335 }
3336
3337 iter_players {
3338 delete $pdata{$::p}{newrootlast};
3339 if ($pdata{$::p}{left}) {
3340 #- already left remote players in mp game
3341 put_image_to_background(mini_graphics($::p) ? $imgbin{"left_".$::p."_mini"} : $imgbin{left_rp1},
3342 $POS{$::p}{left}{x}, $POS{$::p}{left}{y}); #}}
3343 $pdata{$::p}{state} = 'left';
3344 } else {
3345 handle_progress($::p);
3346 }
3347 };
3348
3349 is_1p_game() and print_compressor();
3350
3351 if (!$playdata) {
3352 %recorddata = ();
3353 my $srand = SDL::get_ticks();
3354 srand $srand;
3355 push @{$recorddata{data}}, { srand => $srand }; #- the first record entry is used for pdatas (more keys added later)
3356 }
3357 if ($levels{current} =~ /^\d+$/) {
3358 open_level($levels{current});
3359 } else {
3360 foreach my $cy (0 .. 4) {
3361 foreach my $cx (0 .. (6 + even($cy))) {
3362 my $num = int(rand(@bubbles_images));
3363 if (is_mp_game()) {
3364 if (!$playdata) {
3365 check_mp_connection();
3366 eval { $num = mp_propagate("b|$cx|$cy", $num, \$ticks); };
3367 if ($@) {
3368 $@ =~ /^quit/ and return 0;
3369 die;
3370 }
3371 push @{$recorddata{data}[0]{bubbles}}, $num;
3372 } else {
3373 $num = shift @{$recorddata{pdatas}{bubbles}};
3374 }
3375 }
3376 my $b = create_bubble_given_img_num($num);
3377 real_stick_bubble($b, $cx, $cy, $PLAYERS[0], 0);
3378 if (!is_1p_game()) {
3379 iter_players_but_first {
3380 $pdata{$::p}{left} or real_stick_bubble(create_bubble_given_img($b->{img}), $cx, $cy, $::p, 0);
3381 };
3382 }
3383 }
3384 }
3385 }
3386
3387 my ($next_num, $tobe_num);
3388 do { $next_num = int(rand(@bubbles_images)) } while (!validate_nextcolor($next_num, $PLAYERS[0]));
3389 do { $tobe_num = int(rand(@bubbles_images)) } while (!validate_nextcolor($tobe_num, $PLAYERS[0]));
3390 if (is_mp_game()) {
3391 if (!$playdata) {
3392 check_mp_connection();
3393 eval {
3394 $next_num = mp_propagate("N", $next_num, \$ticks);
3395 $tobe_num = mp_propagate("T", $tobe_num, \$ticks);
3396 };
3397 if ($@) {
3398 $@ =~ /^quit/ and return 0;
3399 die;
3400 }
3401 push @{$recorddata{data}[0]{bubbles}}, $next_num, $tobe_num;
3402 } else {
3403 $next_num = shift @{$recorddata{pdatas}{bubbles}};
3404 $tobe_num = shift @{$recorddata{pdatas}{bubbles}};
3405 }
3406 }
3407 $next_bubble{$PLAYERS[0]} = create_bubble_given_img_num($next_num);
3408 generate_new_bubble($PLAYERS[0], $tobe_num);
3409 if (!is_1p_game()) {
3410 iter_players_but_first {
3411 if (!$pdata{$::p}{left}) {
3412 $next_bubble{$::p} = create_bubble_given_img_num($next_num);
3413 generate_new_bubble($::p, $tobe_num);
3414 }
3415 };
3416 }
3417
3418 if ($graphics_level == 1) {
3419 SDL::Video::blit_surface($background, $apprects{main}, $app, $apprects{main});
3420 SDL::Video::update_rect($app, 0, 0, 0, 0);
3421 } else {
3422 Games::FrozenBubble::CStuff::effect($app, SDL::Video::display_format($background));
3423 }
3424
3425 $display_on_app_disabled = 0;
3426
3427 SDL::Events::pump_events() while SDL::Events::poll_event($event) != 0;
3428 $pdata{state} = 'game';
3429
3430 $direct = undef;
3431
3432 if (is_mp_game() && !$playdata) {
3433 mp_ping_if_needed(\$ticks);
3434
3435 #- 1. first wait on a common barrier with others, so that everyone has finished previous things
3436 dbgnet("send barrier 'n'");
3437 Games::FrozenBubble::Net::gsend('n');
3438 check_mp_connection();
3439 iter_distant_players {
3440 $pdata{$::p}{barrier4newgame} = 0;
3441 };
3442
3443 #- at this point, we can receive first commands of quickies instead of synchro
3444 my @keep_messages;
3445 while (1) {
3446 my $m;
3447 eval { $m = Games::FrozenBubble::Net::grecv_get1msg(); }; #- blocking
3448 if ($@) {
3449 $@ =~ /^quit/ and return 0;
3450 die;
3451 }
3452 mp_ping_if_needed(\$ticks);
3453 if ($m->{msg} eq 'n') {
3454 dbgnet("received barrier 'n' from $pdata{id2p}{$m->{id}}");
3455 $pdata{$pdata{id2p}{$m->{id}}}{barrier4newgame} = 1;
3456 iter_distant_players {
3457 !$pdata{$::p}{left} && $pdata{$::p}{barrier4newgame} == 0 and goto still_waiting;
3458 };
3459 dbgnet("all barriers received, carrying on");
3460 last;
3461 still_waiting:
3462 } else {
3463 push @keep_messages, $m;
3464 }
3465 }
3466
3467 #- 2. now that we're all ready to synchronize, let a unique synchro message be sent, the leader and others will all wait on
3468 is_leader() and Games::FrozenBubble::Net::gsend('!');
3469 check_mp_connection();
3470
3471 while (1) {
3472 my $m;
3473 eval { $m = Games::FrozenBubble::Net::grecv_get1msg(); }; #- blocking
3474 if ($@) {
3475 $@ =~ /^quit/ and return 0;
3476 die;
3477 }
3478 mp_ping_if_needed(\$ticks);
3479 if ($m->{msg} eq '!') {
3480 last;
3481 } else {
3482 push @keep_messages, $m;
3483 }
3484 }
3485
3486 Games::FrozenBubble::Net::gdelay_messages(@keep_messages);
3487
3488 @{$pdata{attackingme}} = ();
3489 }
3490
3491 if ($saveframes) {
3492 $saveframescounter = 0;
3493 $saveframesbase = gettimeofday();
3494 }
3495
3496 $start_time = SDL::get_ticks();
3497 return 1;
3498 }
3499
3500
3501 my $save;
3502
3503 sub choose_1p_game_mode() {
3504
3505 my @ordered_names = qw(play_all_levels pick_start_level play_random_levels mp_train);
3506 my $active_menu = 0;
3507
3508 my $menu_xpos = $MENUPOS{xpos_panel} + ($imgbin{'1p_panel'}->w - $imgbin{txt_1pmenu_over}->w)/2;
3509 my $menu_ypos = $MENUPOS{ypos_panel} + 90;
3510 my $menu_ypos_spacer = $imgbin{txt_1pmenu_over}->h + 4;
3511 my %name2ypos = (play_all_levels => $menu_ypos,
3512 pick_start_level => $menu_ypos + $menu_ypos_spacer,
3513 play_random_levels => $menu_ypos + 2 * $menu_ypos_spacer,
3514 mp_train => $menu_ypos + 3 * $menu_ypos_spacer);
3515
3516 my $overlook_index = 0;
3517 my $overlook = SDL::Surface->new(SDL_SWSURFACE, $imgbin{txt_1pmenu_pick_start_level_text}->w,
3518 $imgbin{txt_1pmenu_pick_start_level_text}->h, 32);
3519 my $redraw = sub {
3520 my $draw_element = sub {
3521 my ($name, $mode) = @_;
3522 put_image($imgbin{"txt_1pmenu_$mode"}, $menu_xpos, $name2ypos{$name});
3523 SDL::Video::blit_surface($imgbin{"txt_1pmenu_${name}_outlined_text"}, SDL::Rect->new(0,0,$imgbin{"txt_1pmenu_${name}_outlined_text"}->w,$imgbin{"txt_1pmenu_${name}_outlined_text"}->h),
3524 $app, SDL::Rect->new($menu_xpos, $name2ypos{$name}, $imgbin{"txt_1pmenu_${name}_outlined_text"}->w,
3525 $imgbin{"txt_1pmenu_${name}_outlined_text"}->h));
3526 };
3527
3528 my $img = $imgbin{'1p_panel'};
3529 my $drect = SDL::Rect->new($MENUPOS{xpos_panel}, $MENUPOS{ypos_panel}, $img->w, $img->h);
3530 if ($save) {
3531 SDL::Video::blit_surface($save, $rects{img}, $app, $drect);
3532 } else {
3533 $save = SDL::Surface->new(SDL_SWSURFACE, $img->w, $img->h, 32);
3534 SDL::Video::blit_surface($app, $drect, $save, $rects{$img});
3535 }
3536 put_image($img, $MENUPOS{xpos_panel}, $MENUPOS{ypos_panel});
3537
3538 my $ypos = $MENUPOS{ypos_panel} + 16;
3539 print_('menu', $app, $MENUPOS{xpos_panel}, $ypos, loc("Start 1-player game menu"), $imgbin{'1p_panel'}->w, 'center');
3540
3541 foreach (@ordered_names) {
3542 $_ ne $ordered_names[$active_menu] and $draw_element->($_, 'off');
3543 }
3544
3545 $draw_element->($ordered_names[$active_menu], 'over');
3546
3547 Games::FrozenBubble::CStuff::overlook_init($overlook);
3548 $overlook_index = 0;
3549
3550 SDL::Video::update_rect($app, 0, 0, 0, 0);
3551 };
3552
3553 my $draw_overlook = sub {
3554 my %name2pivot = (play_all_levels => 90, pick_start_level => 135, play_random_levels => 82, mp_train => 105);
3555 my $name = $ordered_names[$active_menu];
3556 put_image($imgbin{txt_1pmenu_over}, $menu_xpos, $name2ypos{$name});
3557 Games::FrozenBubble::CStuff::overlook($overlook, $imgbin{"txt_1pmenu_${name}_text"}, $overlook_index, $name2pivot{$name});
3558 SDL::Video::blit_surface($overlook, SDL::Rect->new(0,0,$overlook->w,$overlook->h), $app, SDL::Rect->new($menu_xpos, $name2ypos{$name}, $overlook->w, $overlook->h));
3559 $overlook_index++;
3560 if ($overlook_index == 70) {
3561 $overlook_index = 0;
3562 }
3563 SDL::Video::blit_surface($imgbin{"txt_1pmenu_${name}_outlined_text"}, SDL::Rect->new(0,0,$imgbin{"txt_1pmenu_${name}_outlined_text"}->w,$imgbin{"txt_1pmenu_${name}_outlined_text"}->h), $app, SDL::Rect->new($menu_xpos, $name2ypos{$name}, $imgbin{"txt_1pmenu_${name}_outlined_text"}->w, $imgbin{"txt_1pmenu_${name}_outlined_text"}->h));
3564 };
3565
3566 $redraw->();
3567
3568 while (1) {
3569 my $synchro_ticks = SDL::get_ticks();
3570 # commented out because otherwise we see only a white box instead of highlighted background image
3571 if ($graphics_level > 1) {
3572 $draw_overlook->();
3573 SDL::Video::update_rects($app, @update_rects);
3574 @update_rects = ();
3575 }
3576 SDL::Events::pump_events();
3577 while (SDL::Events::poll_event($event) != 0) {
3578 if ($event->type == SDL_KEYDOWN) {
3579 my $k = $event->key_sym;
3580 if ($k == SDLK_RETURN() || $k == SDLK_KP_ENTER()) {
3581 my $cancel;
3582 if ($ordered_names[$active_menu] eq 'pick_start_level') {
3583 if ($levels{current}) {
3584 choose_levelset(1) or $cancel = 1;
3585 }
3586 } elsif ($ordered_names[$active_menu] eq 'play_random_levels') {
3587 $levels{current} = 'random';
3588 my $answ;
3589 ask_from({ intro => [ loc("Random level"), '', '', loc("Enable chain-reaction?"), '' ],
3590 entries => [ { 'q' => loc("%s or %s?", 'Y', 'N'), 'a' => \$answ, f => 'ONE_CHAR' } ],
3591 outro => loc("Enjoy the game!") }) or return;
3592 $chainreaction = $answ == SDLK_y; #;;
3593 } elsif ($ordered_names[$active_menu] eq 'mp_train') {
3594 $levels{current} = 'mp_train';
3595 my $answ;
3596 ask_from({ intro => [ loc("Multiplayer training"), '', '', loc("Enable chain-reaction?"), '' ],
3597 entries => [ { 'q' => loc("%s or %s?", 'Y', 'N'), 'a' => \$answ, f => 'ONE_CHAR' } ],
3598 outro => loc("Enjoy the game!") }) or return;
3599 $chainreaction = $answ == SDLK_y; #;;
3600 }
3601 $cancel or return 1;
3602 } elsif ($event->key_sym == SDLK_ESCAPE) {
3603 $levels{current} = undef;
3604 return;
3605 } elsif ($k == SDLK_DOWN()) {
3606 if ($active_menu < @ordered_names - 1) {
3607 $active_menu++;
3608 } else {
3609 $active_menu = 0;
3610 }
3611 play_sound('menu_change');
3612 } elsif ($k == SDLK_UP()) {
3613 if ($active_menu > 0) {
3614 $active_menu--;
3615 } else {
3616 $active_menu = @ordered_names - 1;
3617 }
3618 play_sound('menu_change');
3619 }
3620 $redraw->();
3621 }
3622 }
3623 my $to_wait = $TARGET_ANIM_SPEED - (SDL::get_ticks() - $synchro_ticks);
3624 $to_wait > 0 and Games::FrozenBubble::CStuff::fbdelay($to_wait);
3625 }
3626 }
3627
3628
3629 our $smg_startx = 78;
3630 our $smg_starty = 30;
3631 our $smg_starty_chat = 320;
3632 our $smg_starty_players = $smg_starty_chat + $smg_lineheight;
3633 our $smg_max_messages = 5;
3634 our $smg_statusx = 10;
3635 our $smg_statusy = 435;
3636
3637 sub erase_line($$;$$) {
3638 my ($pos, $background, $xpos, $width) = @_;
3639 my $drect = SDL::Rect->new($xpos || 0, $pos, $width || 640, $smg_lineheight + 6);
3640 SDL::Video::blit_surface($background, $drect, $app, $drect);
3641 }
3642
3643 our @smg_status_messages;
3644 our $smg_status_message_offsetpage = 1;
3645
3646 sub smg_printstatus {
3647 my $drect = SDL::Rect->new(0, $smg_statusy - $smg_max_messages * $smg_lineheight, 640, 480);
3648 SDL::Video::blit_surface($imgbin{back_netgame}, $drect, $app, $drect);
3649 my $y = $smg_statusy;
3650 my $i = $smg_status_message_offsetpage;
3651 while ($i < $smg_max_messages + $smg_status_message_offsetpage && @smg_status_messages >= $i) {
3652 if ($smg_status_messages[-$i]) {
3653 my $kind = $smg_status_messages[-$i] =~ /^\*\*\*/ ? 'netdialogs_servermsg' : 'netdialogs';
3654 if ($smg_status_messages[-$i] =~ /^\p{BidiClass:R}/) { #see bi directional regex in perlunicode works from 5.8.8 and above
3655 #- if text begins with unicode RTL direction, we also need to tell pango to align on the right
3656 #- (is there another unicode special character which does both?) Yes there is! But we can leave that for later
3657 print_($kind, $app, $smg_statusx, $y, $smg_status_messages[-$i], 620, 'right');
3658 } else {
3659 print_($kind, $app, $smg_statusx, $y, $smg_status_messages[-$i], 620, 'left');
3660 }
3661 }
3662 $y -= $smg_lineheight;
3663 $i++;
3664 }
3665 SDL::Video::update_rect($app, 0, 0, 0, 0);
3666 }
3667
3668 sub smg_add_status_msg {
3669 push @smg_status_messages, @_;
3670 $smg_status_message_offsetpage = 1;
3671 smg_printstatus();
3672 }
3673
3674 sub clean_server {
3675 if ($pdata{serverpid}) {
3676 kill 15, $pdata{serverpid};
3677 waitpid $pdata{serverpid}, 0;
3678 $pdata{serverpid} = undef;
3679 }
3680 }
3681
3682 END { clean_server(); }
3683
3684 sub sanitize_nick {
3685 my ($nick) = @_;
•3686 $nick = substr($nick, 0, 8);
3687 $nick =~ s/[^a-zA-Z0-9_-]//g;
3688 return $nick;
3689 }
3690
3691 sub smg_servers() {
3692
3693 if ($pdata{gametype} eq 'lan') {
3694 smg_add_status_msg(loc("*** Please wait, probing for available servers on local network..."));
3695 my $ret = Games::FrozenBubble::Net::discover_lan_servers();
3696 if ($ret->{failure}) {
3697 smg_add_status_msg(loc("*** Unable to probe for available servers on local network!"),
3698 "*** " . $ret->{failure},
3699 loc("*** Verify your network setup"));
3700 grab_key();
3701 return;
3702 } else {
3703 my @servers = @{$ret->{servers}};
3704 if (!@servers) {
3705 my $fb_server = "$FLPATH";
3706 if (!-x $fb_server) {
3707 print STDERR "$fb_server is missing or not executable!\n";
3708 smg_add_status_msg(loc("*** No server found, and could not start server"),
3709 loc("*** Verify your installation or contact your vendor"));
3710 grab_key();
3711 return;
3712 } else {
3713 if (my $pid = fork()) {
3714 $pdata{autochooseserver} = 1;
3715 $pdata{serverpid} = $pid;
3716 smg_add_status_msg(loc("*** No server found, created server for local network game"));
3717 sleep 1;
3718 return [ { host => 'localhost', port => 1511 } ];
3719 } else {
3720 unless (exec $fb_server, '-L', '-d', '-n', substr("lan-$mynick", 0, 12), '-z') {
•3721 die "Could not create server limited to lan game: $!\n";
3722 }
3723 }
3724 }
3725 } else {
3726 return \@servers;
3727 }
3728 }
3729
3730 } else {
3731 smg_add_status_msg(loc("*** Contacting master server..."));
3732 my $serverlist = Games::FrozenBubble::Net::get_server_list();
3733 my @servers;
3734 if (defined $serverlist) {
3735 foreach my $line (split /\n/, $serverlist) {
3736 if ($line =~ /^(\S+) (\S+)$/) {
3737 push @servers, { host => $1, port => $2 };
3738 } else {
3739 print STDERR "Unrecognized line in serverlist:\n\t$line\n";
3740 }
3741 }
3742 smg_add_status_msg(loc("*** Server list received properly"));
3743 } else {
3744 smg_add_status_msg(loc("*** Unable to download server list from master server!"),
3745 loc("*** Verify your network setup or retry later"));
3746 grab_key();
3747 return;
3748 }
3749 return \@servers;
3750 }
3751 }
3752
3753 our $forget_because_kicked;
3754 sub smg_choose_server(@) {
3755 my (@servers) = @_;
3756 my $max_lines = 18;
3757 erase_line($smg_starty_chat, $imgbin{back_netgame}); #- if we return from choose_game
3758 erase_line($smg_starty_players, $imgbin{back_netgame}); #-
3759
3760 if ($pdata{autochooseserver}) {
3761 $pdata{autochooseserver} = 0;
3762 Games::FrozenBubble::Net::connect($servers[0]{host}, $servers[0]{port});
3763 return Games::FrozenBubble::Net::isconnected();
3764 }
3765
3766 my @sorted_servers;
3767 my $offset = 0;
3768 my $redraw = sub {
3769 my $drect = SDL::Rect->new(0, 0, 640, $smg_statusy-$smg_lineheight*5);
3770 SDL::Video::blit_surface($imgbin{back_netgame}, $drect, $app, $drect);
3771
3772 my %parts = (flag => { xpos => $smg_startx, width => 30 },
3773 name => { xpos => $smg_startx + 30 + 4, width => 120 },
3774 details => { xpos => $smg_startx + 30 + 4 + 120 + 4, width => 344 });
3775 if ($is_rtl) {
3776 $parts{$_}{xpos} = 640 - $parts{$_}{xpos} - $parts{$_}{width} foreach keys %parts;
3777 }
3778 my $y = $smg_starty;
3779 my @show_servers = @sorted_servers;
3780 my $ofs = @show_servers - $max_lines;
3781 $ofs = 0 if $ofs < 0;
3782 $offset = $ofs if $offset > $ofs;
3783 splice(@show_servers, 0, $offset) if $offset;
3784 splice(@show_servers, 18) if $ofs-$offset;
3785 foreach my $server (@show_servers) {
3786 if ($server->{selected}) {
3787 put_image($imgbin{highlight_server}, 6, $y - 1);
3788 }
3789 exists $imgbin{flag}{$server->{language}} and put_image($imgbin{flag}{$server->{language}}, $parts{flag}{xpos}, $y);
3790 print_('netdialogs', $app, $parts{name}{xpos}, $y, $server->{name}, $parts{name}{width}, $is_rtl ? 'right' : 'left'); #- ASCII
3791 my $details = loc("Available players: %s (playing: %s) Ping: %sms", i18n_number($server->{free}), i18n_number($server->{playing}), i18n_number($server->{ping}));
3792 print_('netdialogs', $app, $parts{details}{xpos}, $y, $details, $parts{details}{width});
3793 my $pingimg = $server->{ping} < 80 ? "ping_low" : $server->{ping} < 200 ? "ping_mid" : "ping_high";
3794 put_image($imgbin{$pingimg}, $is_rtl ? $parts{details}{xpos} + $parts{details}{width} - width('netdialogs', $details) - 17
3795 : $parts{details}{xpos} + width('netdialogs', $details), $y);
3796
3797 $y += $smg_lineheight + 2;
3798 }
3799 SDL::Video::update_rect($app, 0, 0, 0, 0);
3800 };
3801
3802 my @potential_servers;
3803 foreach my $server (@servers) {
3804 if (!$server->{disabled}) {
3805 push @potential_servers, $server;
3806 }
3807 }
3808 my $discover = Games::FrozenBubble::NetDiscover->new(@potential_servers);
3809 my $looped = 0;
3810 my $init = 0;
3811 while (1) {
3812 if ($discover->pending) {
3813 $discover->work(0.1); #- do networking stuff for 100ms
3814 $looped++;
3815 my @found_servers = $discover->found;
3816 my $weightfunc = sub { my $base = $_[0]->{free} - $_[0]->{ping}/50; $_[0]->{playing} < 100 ? $base + $_[0]->{playing}/3 : $base - $_[0]->{playing}/3; };
3817 @sorted_servers = sort { $weightfunc->($b) <=> $weightfunc->($a) } @found_servers;
3818 $redraw->();
3819 #- wait a bit or user confusion will be large (jumping cursor)
3820 if ($looped >= 10 && @sorted_servers && !$init) {
3821 $init = 1;
3822 $sorted_servers[0]->{selected} = 1;
3823 smg_add_status_msg(loc("*** Please choose a server"));
3824 $redraw->();
3825 }
3826 } elsif (!$init) {
3827 $init = 1;
3828 if (@sorted_servers) {
3829 $sorted_servers[0]->{selected} = 1;
3830 smg_add_status_msg(loc("*** Please choose a server"));
3831 $redraw->();
3832 } else {
3833 #- no server discovered. empty servers list so that below code will properly report no servers found.
3834 @servers = ();
3835 last;
3836 }
3837 }
3838 SDL::Events::pump_events();
3839 while (SDL::Events::poll_event($event) != 0) {
3840 if ($event->type == SDL_QUIT) {
3841 cleanup_and_exit();
3842 } elsif ($init) {
3843 my $k = extended_keypress($event);
3844 if ($k) {
3845 if ($k eq SDLK_ESCAPE()) {
3846 return 0;
3847
3848 } elsif ($k eq SDLK_DOWN()) {
3849 if (@sorted_servers) {
3850 each_index {
3851 if ($sorted_servers[$::i]->{selected}
3852 && $::i < @sorted_servers - 1
3853 && !$sorted_servers[$::i+1]->{disabled}) {
3854 $sorted_servers[$::i]->{selected} = 0;
3855 $sorted_servers[$::i+1]->{selected} = 1;
3856 $offset++ if $::i + 1 >= $offset + $max_lines;
3857 play_sound('menu_change');
3858 goto done;
3859 }
3860 } @sorted_servers;
3861 done:
3862 }
3863
3864 } elsif ($k eq SDLK_UP()) {
3865 if (@sorted_servers && !$sorted_servers[0]->{selected}) {
3866 each_index {
3867 if ($sorted_servers[$::i]->{selected}) {
3868 $sorted_servers[$::i]->{selected} = 0;
3869 $sorted_servers[$::i-1]->{selected} = 1;
3870 $offset = $::i - 1 if $::i - 1 < $offset;
3871 play_sound('menu_change');
3872 }
3873 } @sorted_servers;
3874 }
3875
3876 } elsif ($k eq SDLK_RETURN() || $k eq SDLK_KP_ENTER()) {
3877 play_sound('menu_selected');
3878 goto ok_smg_choose_server;
3879
3880 } else {
3881 handle_whenever_events($k);
3882 }
3883 }
3884 $redraw->();
3885 }
3886 }
3887 Games::FrozenBubble::CStuff::fbdelay($TARGET_ANIM_SPEED) if $init;
3888 }
3889
3890 if (@servers == 0 || every { $_->{disabled} } @servers) {
3891 smg_add_status_msg(loc("*** No available game server"),
3892 loc("*** Please retry later or try a local network game (lan game)"));
3893 grab_key();
3894 return 0;
3895 }
3896
3897 ok_smg_choose_server:
3898 foreach my $server (@servers) {
3899 if ($server->{selected}) {
3900 Games::FrozenBubble::Net::connect($server);
3901 if (!Games::FrozenBubble::Net::isconnected()) {
3902 smg_add_status_msg(loc("*** Impossible to connect to specified server, going back to server list"));
3903 $server->{selected} = 0;
3904 return smg_choose_server(@servers);
3905 }
3906 smg_add_status_msg(loc("*** Connected to server '%s'", $server->{name}));
3907 print "Notice! next time you start Frozen-Bubble, you may add the commandline parameter\n".
3908 " -gs $server->{host}:$server->{port} to automatically select this game server\n".
3909 " and save time not listing all available servers\n";
3910 last;
3911 }
3912 }
3913
3914 my $y = $smg_starty;
3915 foreach (@servers) {
3916 erase_line($y, $imgbin{back_netgame});
3917 $y += $smg_lineheight + 2;
3918 }
3919
3920 return 1;
3921 }
3922
3923 sub smg_verify_command($;$) {
3924 my ($command, $rest) = @_;
3925 my $answer;
3926 eval {
3927 $answer = Games::FrozenBubble::Net::send_and_receive($command, $rest);
3928 };
3929 if ($@) {
3930 smg_add_status_msg(loc("*** Sorry, your computer or the network is too slow, giving up - press any key"));
3931 SDL::Video::update_rect($app, 0, 0, 0, 0);
3932 SDL::Events::pump_events() while SDL::Events::poll_event($event) != 0;
3933 grab_key();
3934 die 'quit';
3935 }
3936 if ($answer ne 'OK') {
3937 return $answer;
3938 } else {
3939 return;
3940 }
3941 }
3942
3943 our (@entry_typed, $entry_position, $entry_echo_blink_counter);
3944 sub callback_entry {
3945 my ($action, $params, @rest) = @_;
3946 if ($action eq 'reset') {
3947 @entry_typed = ();
3948 $entry_position = 0;
3949 $entry_echo_blink_counter = 51;
3950 }
3951 if ($action eq 'moved') {
3952 $entry_echo_blink_counter = 75;
3953 }
3954 if ($action eq 'keypressed') {
3955 if ($params->{event}->key_sym == SDLK_BACKSPACE()) {
3956 if ($entry_position >= 1) {
3957 splice @entry_typed, $entry_position - 1, 1;
3958 $entry_position--;
3959 $no_echo or play_sound('typewriter');
3960 } else {
3961 play_sound('stick');
3962 }
3963 } elsif ($params->{event}->key_sym == SDLK_DELETE()) {
3964 if ($entry_position < $#entry_typed + 1) {
3965 splice @entry_typed, $entry_position, 1;
3966 $no_echo or play_sound('typewriter');
3967 } else {
3968 play_sound('stick');
3969 }
3970 } elsif ($params->{event}->key_sym == SDLK_LEFT()) {
3971 if ($entry_position >= 1) {
3972 $entry_position--;
3973 $no_echo or play_sound('typewriter');
3974 } else {
3975 play_sound('stick');
3976 }
3977 } elsif ($params->{event}->key_sym == SDLK_RIGHT()) {
3978 if ($entry_position <= $#entry_typed) {
3979 $entry_position++;
3980 $no_echo or play_sound('typewriter');
3981 } else {
3982 play_sound('stick');
3983 }
3984 } elsif ($params->{event}->key_sym == SDLK_HOME()) {
3985 $entry_position = 0;
3986 $no_echo or play_sound('typewriter');
3987 } elsif ($params->{event}->key_sym == SDLK_END()) {
3988 $entry_position = $#entry_typed + 1;
3989 $no_echo or play_sound('typewriter');
3990 } elsif ($params->{event}->key_sym == SDLK_TAB()) {
3991 if (my $completion = $params->{completion}) {
3992 @entry_typed = $completion->(@entry_typed);
3993 $entry_position = $#entry_typed + 1;
3994 }
3995 } else {
3996 my $utf8char = Games::FrozenBubble::CStuff::utf8key($params->{event});
3997 if ($utf8char ne '' && $utf8char ne "\n" && $utf8char ne "\r") {
3998 splice @entry_typed, $entry_position, 0, $utf8char;
3999 if (width($params->{font}, $params->{prefix} . join('', @entry_typed)) >= $params->{maxlen}) {
4000 splice @entry_typed, $entry_position, 1;
4001 play_sound('stick');
4002 } else {
4003 $entry_position++;
4004 $no_echo or play_sound('typewriter');
4005 }
4006 } else {
4007 handle_whenever_events($params->{event}->key_sym);
4008 }
4009 }
4010 }
4011 if ($action eq 'gettext') {
4012 return @entry_typed;
4013 }
4014 if ($action eq 'settext') {
4015 @entry_typed = ($params, @rest);
4016 $entry_position = $#entry_typed + 1;
4017 $entry_echo_blink_counter = 51;
4018 $no_echo or play_sound('typewriter');
4019 }
4020 if ($action eq 'print') {
4021 $params->{maxlen} or die("need maxlen\n".backtrace());
4022 print_($params->{font}, $app, $params->{xpos}, $params->{ypos}, $params->{prefix} . join('', @entry_typed), $params->{maxlen});
4023 if ($entry_echo_blink_counter > 25) {
4024 my @before_echo = @entry_typed;
4025 splice @before_echo, $entry_position;
4026 my $width = width($params->{font}, $params->{prefix} . join('', @before_echo)) + ( $is_rtl ? 3 : -3 );
4027 if ($is_rtl) {
4028 print_($params->{font}, $app, $params->{xpos} + $params->{maxlen} - $width, $params->{ypos}, '|');
4029 } else {
4030 print_($params->{font}, $app, $params->{xpos} + $width, $params->{ypos}, '|');
4031 }
4032 }
4033 }
4034 if ($action eq 'ping') {
4035 $entry_echo_blink_counter--;
4036 $entry_echo_blink_counter or $entry_echo_blink_counter = 50;
4037 return $entry_echo_blink_counter == 50 || $entry_echo_blink_counter == 25;
4038 }
4039 }
4040
4041 sub get_spot_location {
4042 my ($latitude, $longitude) = @_;
4043 my $x0 = 309;
4044 my $y0 = 231;
4045 my $longitude_factor = 1.424;
4046 my $latitude_factor = -145;
4047 return ($x0 + $longitude*$longitude_factor,
4048 $y0 + asinh(tan($latitude*1.4*$PI/360))*$latitude_factor); #- map seems not to really be mercator but.. approximation is kinda ok
4049 }
4050
4051 sub save_back_spot {
4052 my ($latitude, $longitude, $surface, $back_ref) = @_;
4053 my ($x, $y) = get_spot_location($latitude, $longitude);
4054 $x -= $surface->w/2;
4055 $y -= $surface->h/2;
4056 $$back_ref = SDL::Surface->new(20, 20, 32);
4057 SDL::Video::blit_surface($app, SDL::Rect->new($x, $y, 20, 20), $$back_ref, SDL::Rect->new(0,0,$$back_ref->w,$$back_ref->h));
4058 add_default_rect($$back_ref);
4059 }
4060 sub print_spot {
4061 my ($latitude, $longitude, $kind, $surface, $back) = @_;
4062 $surface ||= $imgbin{"netspot_$kind"};
4063 my ($x, $y) = get_spot_location($latitude, $longitude);
4064 $x -= $surface->w/2;
4065 $y -= $surface->h/2;
4066 if ($back) {
4067 put_image($$back, $x, $y);
4068 pop @update_rects;
4069 }
4070 put_image($surface, $x, $y);
4071 }
4072
4073 sub is_only_ascii {
4074 my ($text) = @_;
4075 foreach (unpack("C*", $text)) {
4076 $_ > 127 and return 0;
4077 }
4078 return 1;
4079 }
4080
4081 sub smg_choose_game() {
4082 my @actions = ({ name => loc("Chat"), action => 'CHAT', selected => 1 },
4083 { name => loc("Create new game"), action => 'CREATE' });
4084 my $max_actions = 18;
4085
4086 my $curaction = sub {
4087 my $cur;
4088 each_index {
4089 if ($actions[$::i]->{selected}) {
4090 $cur = $::i;
4091 goto curaction_done;
4092 }
4093 } @actions;
4094 curaction_done:
4095 return $actions[$cur];
4096 };
4097
4098 my $state = 'game_select';
4099
4100 my $erase = sub {
4101 my $drect = SDL::Rect->new(0, 0, 640, $smg_starty_players);
4102 SDL::Video::blit_surface($imgbin{back_netgame}, $drect, $app, $drect);
4103 };
4104 callback_entry('reset');
4105 my @wholist;
4106 my (@free_geolocs, @playing_geolocs);
4107 my $index_selfspot = 0;
4108 my $back_selfspot;
4109 my $free_players;
4110 my $ingame = 0;
4111 my $players_in_game = '';
4112 my $label_outer_color = SDL::Video::map_RGB( $app->format, 0x7b, 0x2f, 0x03); #Map the color to app format
4113 my $label_background_color = SDL::Video::map_RGB( $app->format, 0x5b, 0x1f, 0x09); #Map the color to app format
4114 my $label_line_color = SDL::Color->new( 0x9b, 0x3f, 0x03); #this is sent to line color in CStuff.xs SDL::Color expected
4115 my $redraw = sub {
4116 $erase->();
4117
4118 #- geoloc spots - playing: spots only
4119 my @rectangles = ();
4120 foreach (@playing_geolocs) {
4121 my ($x, $y) = get_spot_location($_->[0], $_->[1]);
4122 print_spot($_->[0], $_->[1], 'playing');
4123 push @rectangles, SDL::Rect->new($x - $imgbin{"netspot_free"}->w/2,
4124 $y - $imgbin{"netspot_free"}->h/2,
4125 $imgbin{"netspot_free"}->w,
4126 $imgbin{"netspot_free"}->h);
4127 }
4128
4129 #- geoloc spots - free: spots and labels (nicks)
4130 #- first show spots, we don't want to move them (but we will want to move labels)
4131 foreach (@free_geolocs) {
4132 @$_ or next;
4133 my ($x, $y) = get_spot_location($_->[0], $_->[1]);
4134 print_spot($_->[0], $_->[1], $ingame ? 'insamegame' : 'free');
4135 push @rectangles, SDL::Rect->new($x - $imgbin{"netspot_free"}->w/2,
4136 $y - $imgbin{"netspot_free"}->h/2,
4137 $imgbin{"netspot_free"}->w,
4138 $imgbin{"netspot_free"}->h);
4139 }
4140 #- second show labels, managing overlap
4141 my @labels = ();
4142 my $linecolor = SDL::Color->new( 0x7b, 0x2f, 0x03);
4143 mapn {
4144 if (@{$_[1]}) {
4145 my ($xspot, $yspot) = get_spot_location($_[1][0], $_[1][1]);
4146 my ($xc, $yc, $sizing, $wb, $hb, $xoffset, $yoffset, $yoffset_retry);
4147 my $text = $_[0];
4148 my $index_positions = 0;
4149 #- set $x/$y as the next position to try; try positions around, then grow circle of 8 pixels
4150 my $set_next_position = sub {
4151 my $positions = 16;
4152 my $grows = int($index_positions / $positions);
4153 my $angle = ($index_positions - $grows*$positions) * 2 * $PI / $positions;
4154 $xc = $xspot + cos($angle) * ($wb/2 + 4 + ($grows + 1) * 8);
4155 $yc = $yspot + sin($angle) * ($hb/2 + 4 + ($grows + 1) * 8);
4156 $index_positions++;
4157 };
4158 #- find sizing of text
4159 print_('netdialogs_servermsg', $app, 0, 0, $text, undef, undef, #- coordinates are unimportant, we'll cancel this printing
4160 sub {
4161 my ($action, $textsurface) = @_;
4162 $sizing = Games::FrozenBubble::CStuff::autopseudocrop($textsurface);
4163 $wb = $sizing->[2] + 6;
4164 $hb = $sizing->[3] + 6;
4165 return 0;
4166 });
4167 my $xb;
4168 my $yb;
4169 my $r;
4170 $set_next_position->();
4171 find_ok_position:
4172 while (1) {
4173 $xb = $xc - $wb/2;
4174 $yb = $yc - $hb/2;
4175 #- check that background rectangle does not overlap any existing rectangle (spots or other labels)
4176 $r = SDL::Rect->new($xb, $yb, $wb, $hb);
4177 foreach my $rect (@rectangles) {
4178 if ($rect->x >= $xb && $wb > $rect->x - $xb
4179 || $xb >= $rect->x && $rect->w > $xb - $rect->x) {
4180 #- x overlap
4181 if ($rect->y >= $yb && $hb > $rect->y - $yb
4182 || $yb >= $rect->y && $rect->h > $yb - $rect->y) {
4183 $set_next_position->();
4184 while ($xb < 20 || $xb + $wb > 620 || $yb < 20 || $yb + $hb > 320) {
4185 $set_next_position->();
4186 if ($index_positions > 100) {
4187 #- abandon, map is crowded
4188 return;
4189 }
4190 }
4191 if ($index_positions > 100) {
4192 #- abandon, map is crowded
4193 return;
4194 }
4195 next find_ok_position;
4196 }
4197 }
4198 }
4199 last;
4200 }
4201 #- draw a line between the spot and the center of the label
4202 Games::FrozenBubble::CStuff::draw_line($app, $xspot, $yspot, $xc, $yc, $label_line_color);
4203 #- draw the label background and the label in another pass to handle overwriting of labels over lines
4204 push @labels, { x => $xc - $sizing->[2]/2 - $sizing->[0], y => $yc - $sizing->[3]/2 - $sizing->[1], text => $text, backrect1 => $r,
4205 backrect2 => SDL::Rect->new($xb + 1, $yb + 1, $wb - 2, $hb - 2) };
4206 push @rectangles, $r;
4207 }
4208 } \@wholist, \@free_geolocs;
4209
4210 foreach (@labels) {
4211 SDL::Video::fill_rect($app, $_->{backrect1}, $label_outer_color);
4212 SDL::Video::fill_rect($app, $_->{backrect2}, $label_background_color);
4213 print_('netdialogs_servermsg', $app, $_->{x}, $_->{y}, $_->{text});
4214 }
4215
4216 #- actions (chat, joins, create)
4217 my $y = $smg_starty;
4218 foreach my $action (@actions) {
4219 if ($action->{selected}) {
4220 put_image($imgbin{highlight_server}, 6, $y-1);
4221 }
4222 print_($action->{readonly} ? 'netdialogs_servermsg' : 'netdialogs', $app, $smg_startx, $y, $action->{name}, 520);
4223 $y += $smg_lineheight;
4224 }
4225
4226 #- selfspot will need to properly erase selection overlay
4227 if ($mylatitude && !$private) {
4228 save_back_spot($mylatitude, $mylongitude, $imgbin{netspot_self}[0], \$back_selfspot);
4229 if ($index_selfspot >= 0) {
4230 print_spot($mylatitude, $mylongitude, 'free', $imgbin{netspot_self}[$index_selfspot], \$back_selfspot);
4231 }
4232 }
4233
4234 #- chat entry
4235 erase_line($smg_starty_chat, $imgbin{back_netgame});
4236 if ($curaction->() && $curaction->()->{action} eq 'CHAT') {
4237 callback_entry('print', { xpos => $smg_startx, ypos => $smg_starty_chat, maxlen => 520, prefix => loc("Say: "), font => 'netdialogs' });
4238 }
4239
4240 #- available players in server, or list of players in game
4241 erase_line($smg_starty_players, $imgbin{back_netgame});
4242 if ($ingame) {
4243 print_('netdialogs', $app, $smg_startx, $smg_starty_players, loc("Players in game: %s", $players_in_game), 520);
4244 } else {
4245 print_('netdialogs', $app, $smg_startx, $smg_starty_players, loc("Available Players: %s", i18n_number($free_players)), 520);
4246 }
4247
4248 #- status messages
4249 smg_printstatus();
4250 };
4251 my $print_selfspot = sub {
4252 if ($mylatitude && !$private) {
4253 $index_selfspot >= 0 and print_spot($mylatitude, $mylongitude, 'free', $imgbin{netspot_self}[$index_selfspot], \$back_selfspot);
4254 $index_selfspot++;
4255 if ($index_selfspot == @{$imgbin{netspot_self}}) {
4256 my ($x, $y) = get_spot_location($mylatitude, $mylongitude);
4257 put_image($back_selfspot, $x - 10, $y - 10);
4258 $index_selfspot = -15;
4259 }
4260 }
4261 };
4262
4263 my $myoldnick;
4264 my $list = sub {
4265 my ($firsttime) = @_;
4266 $state eq 'game_select' or return;
4267 my @games;
4268 my @old_wholist = @wholist;
4269 eval {
4270 ($free_players, undef, my $freenicks, undef, my $playing_geolocs, @games) = Games::FrozenBubble::Net::list();
4271 @wholist = ();
4272 @free_geolocs = ();
4273 @playing_geolocs = ();
4274 foreach (split ',', $freenicks) {
4275 my ($nick, undef, $latitude, $longitude) = $_ =~ /([^:]+)(:([^:]+):([^:]+))?/;
4276 push @wholist, $nick;
4277 if (defined($latitude) && $latitude =~ /^-?\d+\.?\d*$/ && $longitude =~ /^-?\d+\.?\d*$/) {
4278 push @free_geolocs, [ $latitude, $longitude ];
4279 } else {
4280 push @free_geolocs, [];
4281 }
4282 }
4283 foreach (split ',', $playing_geolocs) {
4284 my ($latitude, $longitude) = $_ =~ /([^:]+):([^:]+)/;
4285 $latitude =~ /^-?\d+\.?\d*$/ && $longitude =~ /^-?\d+\.?\d*$/ and push @playing_geolocs, [ $latitude, $longitude ];
4286 }
4287 };
4288 $@ and return;
4289
4290 if (!$firsttime) {
4291 my @joined = difference2([ sort(difference2(\@wholist, \@old_wholist)) ], [ $mynick ]);
4292 my @left = difference2([ sort(difference2(\@old_wholist, \@wholist)) ], [ $myoldnick ]);
4293 if (@left == 1) {
4294 smg_add_status_msg(loc("*** %s has left the chat room", @left));
4295 } else {
4296 my $send = loc("*** Several players left this chat room: ");
4297 while (@left) {
4298 $send .= shift @left;
4299 if (!@left || width('netdialogs', $send) >= 520) {
4300 smg_add_status_msg($send);
4301 $send = '*** ';
4302 } else {
4303 $send .= ',';
4304 }
4305 }
4306 }
4307 if (@joined == 1) {
4308 smg_add_status_msg(loc("*** %s has joined the chat room", @joined));
4309 } else {
4310 my $send = loc("*** Several players joined this chat room: ");
4311 while (@joined) {
4312 $send .= shift @joined;
4313 if (!@joined || width('netdialogs', $send) >= 520) {
4314 smg_add_status_msg($send);
4315 $send = '*** ';
4316 } else {
4317 $send .= ',';
4318 }
4319 }
4320 }
4321 }
4322
4323 my ($join, $rest) = partition { $_->{action} eq 'JOIN' } @actions;
4324 $_->{ok} = 0 foreach @$join;
4325 listgames:
4326 foreach my $players (@games) {
4327 if (@$players < 5 && $players->[0] ne $forget_because_kicked) {
4328 my $name = loc("Join game: %s", join(', ', @$players));
4329 foreach my $line (@$join) {
4330 if ($line->{name} eq $name) {
4331 $line->{ok} = 1;
4332 next listgames;
4333 }
4334 }
4335 push @$join, { name => $name, action => 'JOIN', join => $players->[0], ok => 1 };
4336 }
4337 }
4338 @actions = (@$rest, grep { $_->{ok} } @$join);
4339 if (!any { $_->{selected} } @actions) {
4340 $actions[0]{selected} = 1;
4341 }
4342 $redraw->();
4343 };
4344
4345 my $list_players = sub {
4346 if (@wholist > 1) {
4347 my @list = sort @wholist;
4348 my $send = loc("*** Players listening: ");
4349 while (@list) {
4350 $send .= shift @list;
4351 if (!@list || width('netdialogs', $send) >= 520) {
4352 smg_add_status_msg($send);
4353 $send = '*** ';
4354 } else {
4355 $send .= ',';
4356 }
4357 }
4358 } else {
4359 smg_add_status_msg(loc("*** Notice: no one's listening here"));
4360 }
4361 };
4362
4363 Games::FrozenBubble::Net::send_and_receive('NICK', $mynick);
4364
4365 my $geolocate = sub {
4366 smg_add_status_msg(loc("*** Please wait, retrieving your geographical location from http://hostip.info/..."));
4367 eval {
4368 local $SIG{ALRM} = sub { die "alarm\n" };
4369 alarm 5;
4370 my $data = Games::FrozenBubble::Net::http_download('http://api.hostip.info/get_html.php?position=true');
4371 ($mylatitude) = $data =~ /Latitude: (-?\S{1,5})/;
4372 ($mylongitude) = $data =~ /Longitude: (-?\S{1,5})/;
4373 if (defined($mylatitude)) {
4374 smg_add_status_msg(loc("*** Done, you are positioned as the flashing red dot!"));
4375 } else {
4376 smg_add_status_msg(loc("*** hostip.info doesn't know the geographical location of your IP address"));
4377 smg_add_status_msg(loc("*** If you want that your location appears on the map, fix your entry at http://hostip.info/"));
4378 smg_add_status_msg(loc("*** Then type /geolocate to see yourself on the map"));
4379 $mylatitude = '';
4380 }
4381 alarm 0;
4382 };
4383 if ($@) {
4384 if ($@ =~ /^alarm/) {
4385 smg_add_status_msg(loc("*** hostip.info didn't reply within 5 seconds, giving up"));
4386 }
4387 $mylatitude = '';
4388 }
4389 if ($mylatitude) {
4390 Games::FrozenBubble::Net::send_and_receive('GEOLOC', "$mylatitude:$mylongitude");
4391 } else {
4392 Games::FrozenBubble::Net::send_and_receive('GEOLOC', "");
4393 }
4394 };
4395
4396 if ($pdata{gametype} eq 'net' && !$private) {
4397 if (!defined($mylatitude)) {
4398 $geolocate->();
4399 } else {
4400 Games::FrozenBubble::Net::send_and_receive('GEOLOC', "$mylatitude:$mylongitude");
4401 }
4402 }
4403 smg_add_status_msg(loc("*** You may now create or join a game"));
4404
4405 my $need4update;
4406 my $relist;
4407 my $can_start = 0;
4408 my $joined_leader;
4409 my $chain_reaction_state = loc("enabled");
4410 my $continue_game_when_players_leave_state = loc("enabled");
4411 my $single_player_targetting_state = loc("enabled");
4412 my @victories_limits = ({ value => undef,
4413 text => loc("none (unlimited)") },
4414 map { { value => $_,
4415 text => i18n_number($_) } } (1..12, 15, 20, 30, 50, 100));
4416 my $victories_limit_index = 5;
4417 my @history;
4418 my $history_position;
4419 $list->('first time');
4420 $list_players->();
4421
4422 my $setoptions = sub {
4423 my $level = Games::FrozenBubble::Net::send_and_receive('PROTOCOL_LEVEL');
4424 if ($level < 2) { #- continue game when players leave available from minor level 2 onwards
4425 smg_verify_command('SETOPTIONS', 'CHAINREACTION:' . to_bool($chain_reaction_state eq loc("enabled")) . ','
4426 . "VICTORIESLIMIT:$victories_limits[$victories_limit_index]{value}");
4427 } else {
4428 smg_verify_command('SETOPTIONS', 'CHAINREACTION:' . to_bool($chain_reaction_state eq loc("enabled")) . ','
4429 . 'CONTINUEGAMEWHENPLAYERSLEAVE:' . to_bool($continue_game_when_players_leave_state eq loc("enabled")) . ','
4430 . 'SINGLEPLAYERTARGETTING:' . to_bool($single_player_targetting_state eq loc("enabled")) . ','
4431 . "VICTORIESLIMIT:$victories_limits[$victories_limit_index]{value}");
4432 }
4433 };
4434
4435 my $toggle_chain_reaction = sub {
4436 if ($chain_reaction_state eq loc("disabled")) {
4437 my $level = Games::FrozenBubble::Net::send_and_receive('PROTOCOL_LEVEL');
4438 if ($level < 1) { #- available from minor level 1 onwards
4439 smg_add_status_msg(loc("*** Cannot modify this option, as a player is using a too old version of Frozen-Bubble"));
4440 play_sound('cancel');
4441 } else {
4442 $chain_reaction_state = loc("enabled");
4443 $actions[1]{name} = loc("Chain-reaction: %s", $chain_reaction_state);
4444 $redraw->();
4445 $setoptions->();
4446 }
4447 } else {
4448 $chain_reaction_state = loc("disabled");
4449 $actions[1]{name} = loc("Chain-reaction: %s", $chain_reaction_state);
4450 $redraw->();
4451 $setoptions->();
4452 }
4453 };
4454
4455 my $toggle_continue_game_when_players_leave = sub {
4456 if ($continue_game_when_players_leave_state eq loc("disabled")) {
4457 my $level = Games::FrozenBubble::Net::send_and_receive('PROTOCOL_LEVEL');
4458 if ($level < 2) { #- available from minor level 2 onwards
4459 smg_add_status_msg(loc("*** Cannot modify this option, as a player is using a too old version of Frozen-Bubble"));
4460 play_sound('cancel');
4461 } else {
4462 $continue_game_when_players_leave_state = loc("enabled");
4463 $actions[2]{name} = loc("Continue game when players leave: %s", $continue_game_when_players_leave_state);
4464 $redraw->();
4465 $setoptions->();
4466 }
4467 } else {
4468 $continue_game_when_players_leave_state = loc("disabled");
4469 $actions[2]{name} = loc("Continue game when players leave: %s", $continue_game_when_players_leave_state);
4470 $redraw->();
4471 $setoptions->();
4472 }
4473 };
4474
4475 my $toggle_single_player_targetting = sub {
4476 if ($single_player_targetting_state eq loc("enabled")) {
4477 my $level = Games::FrozenBubble::Net::send_and_receive('PROTOCOL_LEVEL');
4478 if ($level < 2) { #- available from minor level 2 onwards
4479 smg_add_status_msg(loc("*** Cannot modify this option, as a player is using a too old version of Frozen-Bubble"));
4480 play_sound('cancel');
4481 } else {
4482 $single_player_targetting_state = loc("disabled");
4483 $actions[3]{name} = loc("Single player targetting: %s", $single_player_targetting_state);
4484 $redraw->();
4485 $setoptions->();
4486 }
4487 } else {
4488 $single_player_targetting_state = loc("enabled");
4489 $actions[3]{name} = loc("Single player targetting: %s", $single_player_targetting_state);
4490 $redraw->();
4491 $setoptions->();
4492 }
4493 };
4494
4495 my $change_victories_limit = sub {
4496 my ($action) = @_;
4497 my $level = Games::FrozenBubble::Net::send_and_receive('PROTOCOL_LEVEL');
4498 if ($level < 1) { #- available from minor level 1 onwards
4499 smg_add_status_msg(loc("*** Cannot modify this option, as a player is using a too old version of Frozen-Bubble"));
4500 play_sound('cancel');
4501 } else {
4502 if ($action eq 'inc') {
4503 $victories_limit_index++;
4504 $victories_limit_index == @victories_limits and $victories_limit_index = 0;
4505 } elsif ($action eq 'dec') {
4506 $victories_limit_index--;
4507 $victories_limit_index == -1 and $victories_limit_index = @victories_limits - 1;
4508 } else {
4509 for (my $i = 0; $i < @victories_limits; $i++) {
4510 if ((!$action && !$victories_limits[$i]{value})
4511 || ($action && $victories_limits[$i]{value} && $victories_limits[$i]{value} eq $action)) {
4512 $victories_limit_index = $i;
4513 }
4514 }
4515 }
4516 $actions[4]{name} = loc("Victories limit: %s", $victories_limits[$victories_limit_index]{text});
4517 $redraw->();
4518 $setoptions->();
4519 }
4520 };
4521
4522 my $kick = sub {
4523 my ($kicked) = @_;
4524 my $answer = smg_verify_command('KICK', $kicked);
4525 if ($answer eq 'NO_SUCH_PLAYER') {
4526 smg_add_status_msg(loc("*** Can't kick %s: no such player in game", $kicked));
4527 } elsif ($answer) {
4528 smg_add_status_msg(loc("*** Can't kick %s: '%s'", $kicked, $answer));
4529 }
4530 };
4531
4532 while (1) {
4533 $relist++;
4534 $relist % (5*(1000/$TARGET_ANIM_SPEED)) == 0 and $list->();
4535 if (callback_entry('ping')) {
4536 $redraw->();
4537 } else {
4538 if ($relist % 3 == 0) {
4539 $print_selfspot->();
4540 SDL::Video::update_rects($app, @update_rects);
4541 @update_rects = ();
4542 }
4543 }
4544
4545 my $need_redraw;
4546 SDL::Events::pump_events();
4547 while (SDL::Events::poll_event($event) != 0) {
4548 if ($event->type == SDL_QUIT) {
4549 cleanup_and_exit();
4550 }
4551 my $k;
4552 if ($event->type == SDL_KEYDOWN) {
4553 $k = $event->key_sym;
4554 } elsif ($curaction->()->{action} ne 'CHAT' && ($event->type == SDL_JOYAXISMOTION || $event->type() == SDL_JOYBUTTONDOWN)) {
4555 $k = translate_joystick_tokey($event);
4556 }
4557 if ($k) {
4558 if ($k eq SDLK_ESCAPE()) {
4559 if ($ingame) {
4560 smg_add_status_msg(loc("*** Leaving game..."));
4561 Games::FrozenBubble::Net::reconnect();
4562 return smg_choose_game();
4563 } else {
4564 Games::FrozenBubble::Net::disconnect();
4565 $erase->();
4566 return 0;
4567 }
4568
4569 } elsif ($k eq SDLK_PAGEUP()) {
4570 $smg_status_message_offsetpage += 4;
4571 $smg_status_message_offsetpage >= @smg_status_messages - $smg_max_messages and $smg_status_message_offsetpage = @smg_status_messages - $smg_max_messages + 1;
4572 $smg_status_message_offsetpage < 1 and $smg_status_message_offsetpage = 1;
4573 $redraw->();
4574
4575 } elsif ($k eq SDLK_PAGEDOWN()) {
4576 $smg_status_message_offsetpage -= 4;
4577 $smg_status_message_offsetpage < 1 and $smg_status_message_offsetpage = 1;
4578 $redraw->();
4579
4580 } elsif ($k eq SDLK_DOWN()) {
4581 if ($curaction->()->{action} eq 'CHAT' && $history_position <= $#history) {
4582 $history_position++;
4583 if ($history_position > $#history) {
4584 callback_entry('reset');
4585 } else {
4586 callback_entry('settext', @{$history[$history_position]});
4587 }
4588 } else {
4589 each_index {
4590 if ($actions[$::i]{selected}
4591 && $::i < @actions - 1
4592 && ! $actions[$::i+1]{readonly}) {
4593 $actions[$::i]{selected} = 0;
4594 $actions[$::i+1]{selected} = 1;
4595 play_sound('menu_change');
4596 goto done2;
4597 }
4598 } @actions;
4599 done2:
4600 }
4601
4602 } elsif ($k eq SDLK_UP()) {
4603 if ($curaction->()->{action} eq 'CHAT') {
4604 $history_position--;
4605 if ($history_position == -1) {
4606 $history_position = 0;
4607 } else {
4608 callback_entry('settext', @{$history[$history_position]});
4609 }
4610 } else {
4611 if (!$actions[0]->{selected}) {
4612 each_index {
4613 if ($actions[$::i]->{selected}) {
4614 $actions[$::i]->{selected} = 0;
4615 $actions[$::i-1]->{selected} = 1;
4616 play_sound('menu_change');
4617 }
4618 } @actions;
4619 }
4620 }
4621
4622 } elsif ($k eq SDLK_RETURN() || $k eq SDLK_KP_ENTER()) {
4623 if ($curaction->()->{action} eq 'CHAT' && callback_entry('gettext') > 0) {
4624 play_sound('menu_selected');
4625 my $text = join('', callback_entry('gettext'));
4626 push @history, [ callback_entry('gettext') ];
4627 $history_position = $#history + 1;
4628 if ($text =~ m|^/me (.*)| || $text =~ m|^/action (.*)|) {
4629 $text = "* $mynick $1";
4630 } elsif ($text =~ m|^/nick (.*)| && !$ingame) {
4631 my $save_mynick = $mynick;
4632 $mynick = sanitize_nick($1);
4633 if ($mynick) {
4634 smg_add_status_msg(loc("*** You are now known as %s", $mynick));
4635 Games::FrozenBubble::Net::send_and_receive('NICK', $mynick);
4636 $myoldnick = $save_mynick;
4637 } else {
4638 smg_add_status_msg(loc("*** Erroneous nickname"));
4639 $mynick = $save_mynick;
4640 }
4641 $text = undef;
4642 } elsif ($text =~ m|^/list| && !$ingame) {
4643 $list_players->();
4644 $text = undef;
4645 } elsif ($text =~ m|^/server|) {
4646 my $servername = Games::FrozenBubble::Net::current_server_name();
4647 $servername or $servername = Games::FrozenBubble::Net::current_server_hostport();
4648 smg_add_status_msg(loc("*** You're connected to server '%s'", $servername));
4649 $text = undef;
4650 } elsif ($text =~ m|^/fs|) {
4651 $fullscreen = !$fullscreen;
4652 SDL::Video::wm_toggle_fullscreen($app);
4653 $text = undef;
4654 } elsif ($text =~ m|^/geolocate|) {
4655 $geolocate->();
4656 $text = undef;
4657 } elsif ($text =~ m|^/kick (\S+)(?: (.+))?| && $can_start) {
4658 my $kicked = $1;
4659 $2 and Games::FrozenBubble::Net::send_("TALK $kicked <-- $2");
4660 if ($kicked eq $mynick) {
4661 my $rand = int(rand(3));
4662 $rand == 0 and smg_add_status_msg(loc("*** Sado-masochist, hmm?"));
4663 $rand == 1 and smg_add_status_msg(loc("*** You like when it hurts, don't you?"));
4664 $rand == 2 and smg_add_status_msg(loc("*** Your butt already hurts enough! Stop that!"));
4665 } else {
4666 $kick->($kicked);
4667 }
4668 $text = undef;
4669 } elsif ($text =~ m|^/autokick (\S+)(?: (.+))?|) {
4670 my $kicked = $1;
4671 my $message = $2;
4672 if ($kicked eq $mynick) {
4673 my $rand = int(rand(3));
4674 $rand == 0 and smg_add_status_msg(loc("*** Sado-masochist, hmm?"));
4675 $rand == 1 and smg_add_status_msg(loc("*** You like when it hurts, don't you?"));
4676 $rand == 2 and smg_add_status_msg(loc("*** Your butt already hurts enough! Stop that!"));
4677 } else {
4678 my $found = 0;
4679 if (!$message && exists $autokick{$kicked}) {
4680 delete($autokick{$kicked});
4681 smg_add_status_msg(loc("*** Removing %s from autokick list.", $kicked));
4682 } else {
4683 smg_add_status_msg(loc("*** Adding %s to autokick list.", $kicked));
4684 $autokick{$kicked} = $message;
4685 if ($can_start && any { $_ eq $kicked } @wholist) {
4686 $message and Games::FrozenBubble::Net::send_("TALK $kicked <-- $message");
4687 $kick->($kicked);
4688 }
4689 }
4690 }
4691 $text = undef;
4692 } elsif ($text =~ m|^/autokick$|) {
4693 if (!%autokick) {
4694 smg_add_status_msg(loc("*** Nobody in autokick list."));
4695 } else {
4696 smg_add_status_msg(loc("*** Autokick list members: %s", join(", ", sort keys %autokick)));
4697 }
4698 $text = undef;
4699 } elsif ($text =~ m|^/help|) {
4700 smg_add_status_msg(loc("*** Available commands: %s",
4701 join(', ', loc("%s <action>", '/me'), loc("%s <nick> [<text>]", '/autokick'), '/server')),
4702 '*** ' . join(', ', '/fs', '/geolocate',
4703 if_(!$ingame, loc("%s <new_nick>", '/nick'), '/list'),
4704 if_($can_start, loc("%s <nick> [<text>]", '/kick'))));
4705 $text = undef;
4706 } elsif ($text =~ m|^/|) {
4707 smg_add_status_msg(loc("*** Unknown command. Try %s for help.", '/help'));
4708 $text = undef;
4709 } else {
4710 #- for RTL language, force beginning on the right, but non RTL content will appear wrongly so at least don't do for pure ASCII
4711 if ($is_rtl && !is_only_ascii($text)) {
4712 $text = "\x{202b}<$mynick> $text";
4713 } else {
4714 $text = "<$mynick> $text";
4715 }
4716 }
4717 if ($text) {
4718 Games::FrozenBubble::Net::send_("TALK $text");
4719 @wholist == 1 and smg_add_status_msg(loc("*** Notice: no one's listening here"));
4720 }
4721 callback_entry('reset');
4722 }
4723
4724 if (member($curaction->()->{action}, 'CREATE', 'JOIN')) {
4725 my $suffix = 1;
4726 my $answer;
4727 while (1) {
4728 my $message = $curaction->()->{action} eq 'CREATE' ? $mynick
4729 : $curaction->()->{join}." $mynick";
4730 $answer = smg_verify_command($curaction->()->{action}, $message);
4731 if ($answer eq 'NICK_IN_USE') {
4732 if ($suffix < 9) {
4733 $suffix++;
4734 $suffix > 2 and $mynick =~ s/.$//; #- remove suffix added last loop
4735 $mynick = substr($mynick, 0, 9) . $suffix;
4736 } else {
4737 #- try to find something that will be accepted, even if it sux
4738 $mynick = substr($mynick, 0, 7);
4739 my @chars = ('a' .. 'z', 'A' .. 'Z');
4740 $mynick .= $chars[rand(@chars)] foreach 1..3;
4741 $suffix = 1;
4742 }
4743 } elsif ($answer eq 'ALREADY_MAX_OPEN_GAMES') {
4744 smg_add_status_msg(loc("*** Open games already full. Join an existing game, or select a different server."));
4745 goto not_in_game;
4746 } elsif ($curaction->()->{action} eq 'JOIN' && $answer eq 'NO_SUCH_GAME') {
4747 smg_add_status_msg(loc("*** Cannot join game, game was just started or aborted"));
4748 $list->();
4749 goto not_in_game;
4750 } elsif ($answer) {
4751 smg_add_status_msg(loc("*** Failure: '%s'", $answer));
4752 goto not_in_game;
4753 } else {
4754 if ($curaction->()->{action} eq 'CREATE') {
4755 $can_start = 1;
4756 @wholist = $mynick;
4757 smg_add_status_msg(loc("*** Game created - now you need to wait for players to join"));
4758 } else {
4759 $joined_leader = $curaction->()->{join};
4760 smg_add_status_msg(loc("*** Joined game"));
4761 }
4762 $ingame = 1;
4763 last;
4764 }
4765 }
4766 $state = 'wait_for_start';
4767 $need4update = 1;
4768 }
4769 not_in_game:
4770
4771 if ($curaction->()->{action} eq 'TOGGLE_CHAIN_REACTION') {
4772 $toggle_chain_reaction->();
4773 }
4774
4775 if ($curaction->()->{action} eq 'TOGGLE_CONTINUE_GAME_WHEN_PLAYERS_LEAVE') {
4776 $toggle_continue_game_when_players_leave->();
4777 }
4778
4779 if ($curaction->()->{action} eq 'TOGGLE_SINGLE_PLAYER_TARGETTING') {
4780 $toggle_single_player_targetting->();
4781 }
4782
4783 if ($curaction->()->{action} eq 'SWITCH_VICTORIES_LIMIT') {
4784 $change_victories_limit->('inc');
4785 }
4786
4787 if ($curaction->()->{action} eq 'START') {
4788 my $close = smg_verify_command('CLOSE');
4789 if ($close) {
4790 smg_add_status_msg(loc("*** Can't start game: '%s'", $close));
4791 Games::FrozenBubble::CStuff::fbdelay(2000);
4792 return;
4793 }
4794 #- game is closed, need to check one last time if options are really possible
4795 if ($chain_reaction_state eq loc("enabled")
4796 || $victories_limit_index > 0
4797 || $continue_game_when_players_leave_state eq loc("enabled")
4798 || $single_player_targetting_state eq loc("disabled")) {
4799 my $level = Games::FrozenBubble::Net::send_and_receive('PROTOCOL_LEVEL');
4800 my $isdelay = 0;
4801 if ($level < 1) { #- chain reaction available from minor level 1 onwards
4802 if ($chain_reaction_state eq loc("enabled")) {
4803 smg_add_status_msg(loc("*** Must disable chain-reaction, as a player is using a too old version of Frozen-Bubble"));
4804 $chain_reaction_state = loc("disabled");
4805 $isdelay = 1;
4806 }
4807 if ($victories_limit_index > 0) {
4808 smg_add_status_msg(loc("*** Must reset victories limit as a player is using a too old version of Frozen-Bubble"));
4809 $victories_limit_index = 0;
4810 $isdelay = 1;
4811 }
4812 }
4813 if ($level < 2) { #- continue game when players leave available from minor level 1 onwards
4814 if ($continue_game_when_players_leave_state eq loc("enabled")) {
4815 smg_add_status_msg(loc("*** Cannot enable continue game when players leave, as a player is using an old version"));
4816 $continue_game_when_players_leave_state = loc("disabled");
4817 $isdelay = 1;
4818 }
4819 if ($single_player_targetting_state eq loc("disabled")) {
4820 smg_add_status_msg(loc("*** Cannot disable single player targetting, as a player is using an old version"));
4821 $single_player_targetting_state = loc("enabled");
4822 $isdelay = 1;
4823 }
4824 }
4825 $isdelay and Games::FrozenBubble::CStuff::fbdelay(2000);
4826 }
4827 if ($setoptions->()) {
4828 smg_add_status_msg(loc("*** Can't start game: '%s'", $setoptions));
4829 Games::FrozenBubble::CStuff::fbdelay(2000);
4830 return;
4831 }
4832 my $start = smg_verify_command('START');
4833 if ($start) {
4834 smg_add_status_msg(loc("*** Can't start game: '%s'", $start));
4835 Games::FrozenBubble::CStuff::fbdelay(2000);
4836 return;
4837 }
4838 }
4839
4840
4841 } elsif ($k eq SDLK_RIGHT() && $curaction->()->{action} ne 'CHAT') {
4842 if ($curaction->()->{action} eq 'TOGGLE_CHAIN_REACTION') {
4843 $toggle_chain_reaction->();
4844 }
4845 if ($curaction->()->{action} eq 'TOGGLE_CONTINUE_GAME_WHEN_PLAYERS_LEAVE') {
4846 $toggle_continue_game_when_players_leave->();
4847 }
4848 if ($curaction->()->{action} eq 'TOGGLE_SINGLE_PLAYER_TARGETTING') {
4849 $toggle_single_player_targetting->();
4850 }
4851 if ($curaction->()->{action} eq 'SWITCH_VICTORIES_LIMIT') {
4852 $change_victories_limit->('inc');
4853 }
4854
4855 } elsif ($k eq SDLK_LEFT() && $curaction->()->{action} ne 'CHAT') {
4856 if ($curaction->()->{action} eq 'TOGGLE_CHAIN_REACTION') {
4857 $toggle_chain_reaction->();
4858 }
4859 if ($curaction->()->{action} eq 'TOGGLE_CONTINUE_GAME_WHEN_PLAYERS_LEAVE') {
4860 $toggle_continue_game_when_players_leave->();
4861 }
4862 if ($curaction->()->{action} eq 'TOGGLE_SINGLE_PLAYER_TARGETTING') {
4863 $toggle_single_player_targetting->();
4864 }
4865 if ($curaction->()->{action} eq 'SWITCH_VICTORIES_LIMIT') {
4866 $change_victories_limit->('dec');
4867 }
4868
4869 } else {
4870 if ($curaction->()->{action} eq 'CHAT') {
4871 callback_entry('keypressed', { event => $event, maxlen => 480, font => 'netdialogs',
4872 completion => sub {
4873 my @typed = @_;
4874 my $end;
4875 while (1) {
4876 last if !@typed;
4877 my $c = pop @typed;
4878 if ($c eq ' ') {
4879 $end or return @_;
4880 push @typed, $c;
4881 last;
4882 }
4883 $end = "$c$end";
4884 }
4885 my @matches = grep { lc(substr($_, 0, length($end))) eq lc($end) } @wholist;
4886 if (@matches == 0) {
4887 return @_;
4888 } else {
4889 my $colon = !@typed ? ': ' : ' ';
4890 if (@matches == 1) {
4891 return @typed, split '', "$matches[0]$colon";
4892 } else {
4893 my @chars = stringchars($matches[0]);
4894 my $counter = 0;
4895 while ($counter < @chars
4896 && every { (stringchars($_))[$counter] eq $chars[$counter] } @matches) {
4897 $counter++;
4898 }
4899 play_sound('stick');
4900 return @typed, split '', substr($matches[0], 0, $counter);
4901 }
4902 }
4903 } });
4904
4905 } else {
4906 if ($curaction->()->{action} eq 'SWITCH_VICTORIES_LIMIT') {
4907 my $utf8char = Games::FrozenBubble::CStuff::utf8key($event);
4908 $change_victories_limit->($utf8char) if defined $utf8char && $utf8char eq int($utf8char);
4909 }
4910
4911 handle_whenever_events($k);
4912 }
4913 }
4914
4915 $need_redraw = 1;
4916 }
4917 }
4918 if ($need_redraw) {
4919 callback_entry('moved');
4920 $redraw->();
4921 }
4922 Games::FrozenBubble::CStuff::fbdelay($TARGET_ANIM_SPEED);
4923
4924 while (my $msg = Games::FrozenBubble::Net::readline_ifdata()) {
4925 my ($command, $message) = Games::FrozenBubble::Net::decode_msg($msg);
4926 if ($command eq 'PUSH') {
4927 if ($message =~ /^TALK: (.*)/) {
4928 my $message = $1;
4929 my (undef, $min, $hour) = localtime();
4930 smg_add_status_msg(sprintf("%02d:%02d ", $hour, $min) . $message);
4931 play_sound('typewriter');
4932 } elsif ($message =~ /^JOINED: (.+)/) {
4933 my $joined = $1;
4934 smg_add_status_msg(loc("*** %s joined the game!", $joined));
4935 if ($can_start && exists $autokick{$joined}) {
4936 $autokick{$joined} and Games::FrozenBubble::Net::send_("TALK $joined <-- $autokick{$joined}");
4937 $kick->($joined);
4938 } else {
4939 push @wholist, $joined;
4940 play_sound('newroot_solo');
4941 if ($can_start
4942 && ($chain_reaction_state eq loc("enabled")
4943 || $victories_limit_index > 0
4944 || $continue_game_when_players_leave_state eq loc("enabled")
4945 || $single_player_targetting_state eq loc("disabled"))) {
4946 my $level = Games::FrozenBubble::Net::send_and_receive('PROTOCOL_LEVEL');
4947 if ($level < 1) { #- available from minor level 1 onwards
4948 if ($chain_reaction_state eq loc("enabled")) {
4949 smg_add_status_msg(loc("*** Chain-reaction disabled, %s is using a too old version of Frozen-Bubble", $joined));
4950 $chain_reaction_state = loc("disabled");
4951 }
4952 if ($victories_limit_index > 0) {
4953 smg_add_status_msg(loc("*** Victories limit reset, %s is using a too old version of Frozen-Bubble", $joined));
4954 $victories_limit_index = 0;
4955 }
4956 }
4957 if ($level < 2) { #- available from minor level 2 onwards
4958 if ($continue_game_when_players_leave_state eq loc("enabled")) {
4959 smg_add_status_msg(loc("*** Continue game when players leave disabled, %s has a too old version", $joined));
4960 $continue_game_when_players_leave_state = loc("disabled");
4961 }
4962 if ($single_player_targetting_state eq loc("disabled")) {
4963 smg_add_status_msg(loc("*** Single player targetting enabled, %s has a too old version", $joined));
4964 $single_player_targetting_state = loc("disabled");
4965 }
4966 }
4967 }
4968 $can_start and $setoptions->(); #- new joiner needs to get parameters anyway
4969 }
4970 } elsif ($message =~ /^PARTED: (.+)/) {
4971 if ($1 eq $joined_leader) {
4972 smg_add_status_msg(loc("*** Game creator left the game..."));
4973 play_sound('cancel');
4974 Games::FrozenBubble::Net::reconnect();
4975 return smg_choose_game();
4976 } else {
4977 smg_add_status_msg(loc("*** %s left the game...", $1));
4978 @wholist = difference2(\@wholist, [ $1 ]);
4979 play_sound('newroot_solo');
4980 }
4981 } elsif ($message =~ /^KICKED: (.+)/) {
4982 smg_add_status_msg(loc("*** %s was kicked out of the game...", $1));
4983 @wholist = difference2(\@wholist, [ $1 ]);
4984 play_sound('newroot_solo');
4985 } elsif ($message eq 'KICKED') {
4986 $forget_because_kicked = $joined_leader;
4987 smg_add_status_msg(loc("*** You were kicked out of the game..."));
4988 play_sound('cancel');
4989 Games::FrozenBubble::Net::reconnect();
4990 return smg_choose_game();
4991 } elsif ($message eq 'NO_ACTIVITY_WITHIN_GRACETIME') {
4992 smg_add_status_msg(loc("*** You were disconnected because of too long inactivity"));
4993 play_sound('cancel');
4994 Games::FrozenBubble::Net::reconnect();
4995 return smg_choose_game();
4996 } elsif ($message =~ /^OPTIONS: (.*)/) {
4997 my $options = $1;
4998 while ($options =~ /([^,]+),?/g) {
4999 my $option = $1;
5000 if ($option =~ /^CHAINREACTION:(.)/) {
5001 $chainreaction = $1;
5002 } elsif ($option =~ /^CONTINUEGAMEWHENPLAYERSLEAVE:(.)/) {
5003 $continuegamewhenplayersleave = $1;
5004 } elsif ($option =~ /^SINGLEPLAYERTARGETTING:(.)/) {
5005 $singleplayertargetting = $1;
5006 } elsif ($option =~ /^VICTORIESLIMIT:(\d*)/) {
5007 $pdata{scorelimit} = $1;
5008 } elsif ($option =~ /^PROTOCOLLEVEL:(\d+)/) {
5009 $pdata{protocollevel} = $1;
5010 if ($pdata{protocollevel} < 2) {
5011 $continuegamewhenplayersleave = 0;
5012 $singleplayertargetting = 1;
5013 }
5014 } else {
5015 print "Unrecognized option: $option\n";
5016 }
5017 }
5018 play_sound('menu_selected');
5019 } elsif ($message =~ /^GAME_CAN_START: (.+)/) {
5020 @PLAYERS = qw(p1);
5021 my $msg = $1;
5022 my @mappings;
5023 while ($msg) {
5024 my $id = substr($msg, 0, 1);
5025 $msg = substr($msg, 1);
5026 my ($nick, undef, $rest) = $msg =~ /([^,]+)(,(.*))?/;
5027 $msg = $rest;
5028 push @mappings, { id => $id, nick => $nick };
5029 }
5030 foreach (@ALL_PLAYERS) {
5031 delete $pdata{$_}{id};
5032 delete $pdata{$_}{nick};
5033 }
5034 %{$pdata{id2p}} = ();
5035 foreach my $m (@mappings) {
5036 my $player;
5037 if ($m->{nick} eq $mynick) {
5038 $player = 'p1';
5039 } else {
5040 foreach (@ALL_PLAYERS) {
5041 /rp/ or next;
5042 exists $pdata{$_}{id} or $player ||= $_;
5043 }
5044 push @PLAYERS, $player;
5045 }
5046 $pdata{$player}{id} = $m->{id};
5047 $pdata{$player}{nick} = $m->{nick};
5048 $pdata{id2p}{$m->{id}} = $player;
5049 }
5050 Games::FrozenBubble::Net::setmyid($pdata{p1}{id});
5051 $pdata{$_}{score} = 0 foreach @PLAYERS;
5052 #- leader must wait for all others being in prio mode before sending a prio message,
5053 #- else first messages might not get properly received on the other end and startup fails.
5054 if (is_leader()) {
5055 leader_check_game_start:
5056 my $can_start = smg_verify_command('LEADER_CHECK_GAME_START');
5057 if ($can_start eq 'OTHERS_NOT_READY') {
5058 Games::FrozenBubble::Net::sleep_reasonably();
5059 goto leader_check_game_start;
5060 } elsif ($can_start) {
5061 smg_add_status_msg(loc("*** Failure: '%s'", $can_start));
5062 play_sound('cancel');
5063 Games::FrozenBubble::Net::reconnect();
5064 return smg_choose_game();
5065 }
5066 }
5067 smg_verify_command('OK_GAME_START');
5068 return 1;
5069 } else {
5070 print "unrecognized message received: $msg\n";
5071 }
5072 $need4update = 1;
5073 } else {
5074 print "non-push received!? $msg\n";
5075 }
5076 }
5077
5078 if (!Games::FrozenBubble::Net::isconnected()) {
5079 smg_add_status_msg(loc("*** Lost connection to server, abandoning - press any key"));
5080 @actions = ();
5081 $redraw->();
5082 play_sound('cancel');
5083 SDL::Events::pump_events() while SDL::Events::poll_event($event) != 0;
5084 grab_key();
5085 $erase->();
5086 return 0;
5087 }
5088
5089 if ($need4update) {
5090 if ($state ne 'game_select') {
5091 my $status = Games::FrozenBubble::Net::send_and_receive('STATUSGEO');
5092 @wholist = ();
5093 @free_geolocs = ();
5094 foreach (split ',', $status) {
5095 my ($nick, undef, $latitude, $longitude) = $_ =~ /([^:]+)(:([^:]+):([^:]+))?/;
5096 push @wholist, $nick;
5097 if ($latitude && $latitude =~ /^-?\d+\.?\d*$/ && $longitude =~ /^-?\d+\.?\d*$/) {
5098 push @free_geolocs, [ $latitude, $longitude ];
5099 } else {
5100 push @free_geolocs, [];
5101 }
5102 }
5103 $players_in_game = join ', ', @wholist;
5104 my $selected;
5105 each_index { $actions[$::i]{selected} and $selected = $::i; } @actions;
5106 @actions = { name => loc("Chat"), action => 'CHAT' };
5107 if ($can_start) {
5108 #- creator
5109 push @actions, { name => loc("Chain-reaction: %s", $chain_reaction_state), action => 'TOGGLE_CHAIN_REACTION' };
5110 push @actions, { name => loc("Continue game when players leave: %s", $continue_game_when_players_leave_state), action => 'TOGGLE_CONTINUE_GAME_WHEN_PLAYERS_LEAVE' };
5111 push @actions, { name => loc("Single player targetting: %s", $single_player_targetting_state), action => 'TOGGLE_SINGLE_PLAYER_TARGETTING' };
5112 push @actions, { name => loc("Victories limit: %s", $victories_limits[$victories_limit_index]{text}), action => 'SWITCH_VICTORIES_LIMIT' };
5113 @wholist > 1 and push @actions, { name => loc("Start game!"), action => 'START' };
5114 } else {
5115 #- joiner
5116 push @actions, { name => loc("Chain-reaction: %s", $chainreaction ? loc("enabled") : loc("disabled")), readonly => 1};
5117 push @actions, { name => loc("Continue game when players leave: %s", $continuegamewhenplayersleave ? loc("enabled") : loc("disabled")), readonly => 1 };
5118 push @actions, { name => loc("Single player targetting: %s", $singleplayertargetting ? loc("enabled") : loc("disabled")), readonly => 1 };
5119 push @actions, { name => loc("Victories limit: %s", $pdata{scorelimit} ? i18n_number($pdata{scorelimit}) : loc("none (unlimited)")), readonly => 1 };
5120 }
5121 $selected-- while $selected > $#actions || $actions[$selected]{readonly};
5122 $actions[$selected]{selected} = 1;
5123 }
5124 $redraw->();
5125 $need4update = 0;
5126 }
5127 }
5128 }
5129
5130 sub show_mp_scores() {
5131 SDL::Video::blit_surface($imgbin{back_netgame}, $apprects{main}, $app, $apprects{main});
5132
5133 if ($pdata{inconsistency}) {
5134 smg_add_status_msg(loc("*** Game finished, because an inconsistency in game state was detected - sorry!"));
5135 } elsif ($pdata{scorelimit} && any { $pdata{$_}{score} == $pdata{scorelimit} } @PLAYERS) {
5136 smg_add_status_msg(loc("*** Game finished, because victories limit of %s was reached.", i18n_number($pdata{scorelimit})));
5137 } else {
5138 if (!$continuegamewhenplayersleave && any { $pdata{$_}{left} } @PLAYERS) {
5139 smg_add_status_msg(loc("*** Game finished, because the following player(s) left: %s", join(', ', map { if_($pdata{$_}{left}, $pdata{$_}{nick}) } @PLAYERS)));
5140 }
5141 }
5142 smg_add_status_msg(loc("*** Addicted for: %s", format_addiction((SDL::get_ticks() - $time_netgame)/1000, 1)));
5143 @PLAYERS = reverse ssort { $pdata{$_}{score} } @PLAYERS;
5144 if ($pdata{$PLAYERS[0]}{score} > $pdata{$PLAYERS[1]}{score}) {
5145 smg_add_status_msg(loc("*** Winner: %s", $pdata{$PLAYERS[0]}{nick}));
5146 } else {
5147 smg_add_status_msg(loc("*** Draw game!"));
5148 }
5149 smg_add_status_msg(loc("*** Scores: %s", join(', ', map { sprintf("%s: %s", $pdata{$_}{nick}, i18n_number($pdata{$_}{score})) } @PLAYERS)));
5150 }
5151
5152 sub setup_mp_game() {
5153
5154 SDL::Video::blit_surface($imgbin{back_netgame}, $apprects{main}, $app, $apprects{main});
5155
5156 if (!Games::FrozenBubble::Net::isconnected()) {
5157 @smg_status_messages = ();
5158 $smg_status_message_offsetpage = 1;
5159 if ($gameserver) {
5160 my ($host, $port) = $gameserver =~ /(\S+):(\S+)/;
5161 if (!$host) {
5162 $host = $gameserver;
5163 $port = 1511;
5164 }
5165 Games::FrozenBubble::Net::connect($host, $port);
5166 if (!Games::FrozenBubble::Net::isconnected()) {
5167 smg_add_status_msg(loc("*** Cannot connect to specified gameserver, fallbacking to contacting master server"));
5168 print STDERR "Cannot connect to specified gameserver, fallbacking to contacting master server\n";
5169 goto choose_server;
5170 }
5171 } else {
5172 choose_server:
5173 #- 1. get list of servers
5174 my $servers = smg_servers();
5175 defined $servers or return;
5176
5177 #- 2. let user choose server
5178 smg_choose_server(@$servers) or return;
5179 }
5180
5181 } else {
5182 show_mp_scores();
5183 }
5184
5185 #- 3. let user choose/create game
5186 $forget_because_kicked = undef;
5187 smg_choose_game() or return;
5188
5189 save_config();
5190
5191 $time_netgame = SDL::get_ticks();
5192 return 1;
5193 }
5194
5195 sub new_game_once {
5196
5197 if ($direct_levelset) {
5198 load_levelset("$FBLEVELS/$direct_levelset");
5199 $direct_levelset = '';
5200 }
5201 if (!$direct) {
5202 if (is_1p_game()) {
5203 choose_1p_game_mode() or return;
5204 }
5205 if (is_2p_game() && $graphics_level > 1) {
5206 my $answ;
5207 ask_from({ intro => [ loc("2-player game"), '', '', loc("Enable chain-reaction?"), '' ],
5208 entries => [ { 'q' => loc("%s or %s?", 'Y', 'N'), 'a' => \$answ, f => 'ONE_CHAR' } ],
5209 outro => loc("Enjoy the game!") }) or return;
5210 $chainreaction = $answ == SDLK_y; #;;
5211 }
5212 }
5213 $pdata{$_}{left} = 0 foreach @ALL_PLAYERS;
5214 if (is_mp_game() && !$playdata) {
5215 SDL::Events::enable_key_repeat(200, 50);
5216 my $ok_game;
5217 eval {
5218 $ok_game = setup_mp_game();
5219 };
5220 my $failure = $@;
5221 SDL::Events::enable_key_repeat(0, 0);
5222 if ($failure && $failure ne 'quit') {
5223 die $failure;
5224 }
5225 $failure || !$ok_game and return;
5226 }
5227 play_music(is_1p_game() ? 'main1p' : 'main2p');
5228 return 1;
5229 }
5230
5231 sub lvl_cmp($$) { $_[0] eq 'WON' ? ($_[1] eq 'WON' ? 0 : 1) : ($_[1] eq 'WON' ? -1 : $_[0] <=> $_[1]) }
5232
5233 sub ordered_highscores { return sort { lvl_cmp($b->{level}, $a->{level}) || $a->{time} <=> $b->{time} } @$HISCORES }
5234 sub ordered_mptrain_highscores { return sort { $b->{score} <=> $a->{score} } @$HISCORES_MPTRAIN }
5235 sub ordered_mptrain_highscores_chainreaction { return sort { $b->{score} <=> $a->{score} } @$HISCORES_MPTRAIN_CHAINREACTION }
5236
5237 sub handle_new_hiscores() {
5238 is_1p_game() && $levels{current} && $levels{current} ne 'random' && !$playdata or return;
5239
5240 if ($levels{current} ne 'mp_train') {
5241 #- levels hiscores
5242 my @ordered = ordered_highscores();
5243 my $worst = pop @ordered;
5244 my $total_seconds = (SDL::get_ticks() - $time_1pgame)/1000;
5245 if (@$HISCORES == 10 && (lvl_cmp($levels{current}, $worst->{level}) == -1
5246 || lvl_cmp($levels{current}, $worst->{level}) == 0 && $total_seconds > $worst->{time})) {
5247 return;
5248 }
5249 play_sound('applause');
5250 append_highscore_level();
5251
5252 my %new_entry;
5253 $new_entry{level} = $levels{current};
5254 $new_entry{time} = $total_seconds;
5255 $new_entry{piclevel} = count_highscorehistory_levels();
5256 ask_from({ intro => [ loc("Congratulations!"), loc("You have a highscore!"), '' ],
5257 entries => [ { 'q' => loc("Your name?"), 'a' => \$new_entry{name} } ],
5258 outro => loc("Great game!"),
5259 erase_background => $background,
5260 });
5261 return if $new_entry{name} eq '';
5262
5263 push @$HISCORES, \%new_entry;
5264 if (@$HISCORES == 11) {
5265 my @high = ordered_highscores();
5266 pop @high;
5267 $HISCORES = \@high;
5268 }
5269 output($hiscorefiles{levels}, Data::Dumper->Dump([$HISCORES], [qw(HISCORES)]));
5270 display_highscores('levels', \%new_entry);
5271
5272 } else {
5273 #- mp training hiscores
5274 my @ordered;
5275 if ($chainreaction) {
5276 @ordered = ordered_mptrain_highscores_chainreaction();
5277 } else {
5278 @ordered = ordered_mptrain_highscores();
5279 }
5280 my $scores = $chainreaction ? $HISCORES_MPTRAIN_CHAINREACTION : $HISCORES_MPTRAIN;
5281 my $worst = pop @ordered;
5282 if (@$scores == 20 && $pdata{p1}{score} < $worst->{score}) {
5283 return;
5284 }
5285 play_sound('applause');
5286
5287 my %new_entry;
5288 $new_entry{score} = $pdata{p1}{score};
5289 ask_from({ intro => [ loc("Congratulations!"), loc("You have a highscore!"), '' ],
5290 entries => [ { 'q' => loc("Your name?"), 'a' => \$new_entry{name} } ],
5291 outro => loc("Great game!"),
5292 erase_background => $background,
5293 });
5294 return if $new_entry{name} eq '';
5295
5296 push @$scores, \%new_entry;
5297 if (@$scores == 21) {
5298 my @high = sort { $b->{score} <=> $a->{score} } @$scores;
5299 pop @high;
5300 if ($chainreaction) {
5301 $HISCORES_MPTRAIN_CHAINREACTION = \@high;
5302 } else {
5303 $HISCORES_MPTRAIN = \@high;
5304 }
5305 }
5306 output($hiscorefiles{mptrain}, Data::Dumper->Dump([$HISCORES_MPTRAIN], [qw(HISCORES_MPTRAIN)]) . ' ' .
5307 Data::Dumper->Dump([$HISCORES_MPTRAIN_CHAINREACTION], [qw(HISCORES_MPTRAIN_CHAINREACTION)]));
5308 display_highscores('mptrain', \%new_entry);
5309 }
5310 }
5311
5312 # append the new highscore to the $FBHOME/highlevelshistory
5313 sub append_highscore_level() {
5314
5315 my $row_numb = 0;
5316 my $lvl = 1;
5317
5318 my @contents;
5319
5320 foreach my $line (cat_($loaded_levelset)) {
5321 if ($line !~ /\S/) {
5322 if ($row_numb) {
5323 $lvl++;
5324 $row_numb = 0;
5325 }
5326 } else {
5327 $row_numb++;
5328 $lvl == ($levels{current} eq 'WON' ? (keys %levels)-1 : $levels{current})
5329 and push @contents, $line;
5330 }
5331 }
5332
5333 append_to_file("$FBHOME/highlevelshistory", @contents, "\n\n");
5334 }
5335
5336 sub count_highscorehistory_levels() {
5337 my $cnt = 0;
5338 my $row_numb = 0;
5339 foreach my $line (cat_("$FBHOME/highlevelshistory")) {
5340 if ($line !~ /\S/) {
5341 if ($row_numb) {
5342 $cnt++;
5343 $row_numb = 0;
5344 }
5345 } else {
5346 $row_numb++;
5347 }
5348 }
5349 return $cnt;
5350 }
5351
5352 sub save_frame() {
5353 $replayparam and $app->save_bmp(sprintf("$saveframes/frame_\%d_%08d.bmp", $saveframesbase, $saveframescounter++));
5354 }
5355
5356 #- ----------- mainloop ---------------------------------------------------
5357
5358 sub maingame() {
5359 my $synchro_ticks = SDL::get_ticks();
5360
5361 handle_graphics(\&erase_image);
5362 update_game();
5363 handle_graphics(\&put_image);
5364 $frame++;
5365
5366 # print "rects:\n";
5367 # printf "\t%d:%d %d:%d %s\n", $_->x, $_->y, $_->w, $_->h, $_->{from} foreach @update_rects;
5368 SDL::Video::update_rects($app, @update_rects);
5369 @update_rects = ();
5370
5371 my $to_wait = $TARGET_ANIM_SPEED - (SDL::get_ticks() - $synchro_ticks);
5372 # print "$to_wait\n";
5373 $to_wait > 0 and Games::FrozenBubble::CStuff::fbdelay($to_wait);
5374 $saveframes and save_frame();
5375 }
5376
5377 sub cleanup_and_exit {
5378 save_config();
5379 exit 0;
5380 }
5381
5382 #- ----------- menu stuff -------------------------------------------------
5383
5384 our $logo_candy_index = 0;
5385 our $logo_candy_method = int(rand(8));
5386 if ("@ARGV" =~ /winter.season/) {
5387 $logo_candy_method = 8;
5388 } else {
5389 my (undef, undef, undef, $day, $month) = localtime(time());
5390 if ($day == 25 && $month == 11) {
5391 $logo_candy_method = 8;
5392 } else {
5393 if (!defined($mylatitude) || $mylatitude > 0) {
5394 if ($day >= 21 && $month == 11
5395 || $month == 0
5396 || $day <= 21 && $month == 1) {
5397 rand() < 0.3 and $logo_candy_method = 8;
5398 }
5399 } else {
5400 if ($day >= 21 && $month == 4
5401 || $month == 5
5402 || $day <= 24 && $month == 6) {
5403 rand() < 0.3 and $logo_candy_method = 8;
5404 }
5405 }
5406 }
5407 }
5408 our ($logox, $logoy);
5409 our $candy;
5410 our ($blink_green, $blink_purple);
5411 our %cursor_save_bg;
5412 our $cursor_tmp;
5413 our %broken_cursors;
5414
5415 sub save_config {
5416 #- for $KEYS, try hard to keep SDLK_<key> instead of integer value in rcfile
5417 my $KEYS_;
5418 foreach my $p (keys %$KEYS) {
5419 foreach my $k (keys %{$KEYS->{$p}}) {
5420 if ($KEYS->{$p}{$k} =~ /^\d+$/) {
5421 foreach (@fbsyms::syms) {
5422 if (eval("$KEYS->{$p}{$k} eq SDLK_$_")) {
5423 $KEYS_->{$p}{$k} = "SDLK_$_";
5424 goto nextkey;
5425 }
5426 }
5427 }
5428 $KEYS_->{$p}{$k} = $KEYS->{$p}{$k}; #- fallback to numeric
5429 nextkey:
5430 }
5431 }
5432 #- special hook for $mylatitude as we don't want to save an empty value
5433 my $dump = Data::Dumper->Dump([$fullscreen, $graphics_level, $mynick, $music_disabled,
5434 $mixer_enabled, $mylatitude || undef, $mylongitude, $KEYS_],
5435 [qw(fullscreen graphics_level mynick music_disabled mixer_enabled
5436 mylatitude mylongitude KEYS)]);
5437 $dump =~ s/'SDLK_(\w+)'/SDLK_$1/g;
5438 output($rcfile, $dump);
5439 }
5440 my $banner_pos;
5441 my $current_pos;
5442 sub menu {
5443 my ($firsttime) = @_;
5444
5445 if (is_1p_game() && $levels{current} ne 'mp_train') {
5446 handle_new_hiscores();
5447 }
5448
5449 play_music('intro');
5450 clean_server();
5451
5452 my $back_start = $imgbin{back_menu};;
5453 my $display_menu = sub {
5454 SDL::Video::blit_surface($back_start, $apprects{main}, $app, $apprects{main});
5455
5456 # stamp is the "frozen bubble since 2002"-logo underneath the (animated) logo
5457 SDL::Video::blit_surface($imgbin{stamp},SDL::Rect->new(0,0,$imgbin{stamp}->w,$imgbin{stamp}->h), $app, SDL::Rect->new( 490, 142, $imgbin{stamp}->w, $imgbin{stamp}->h));
5458 };
5459
5460 $display_menu->();
5461
5462 my $invalidate_all;
5463
5464 my $menu_display_highscores = sub {
5465 display_highscores();
5466 $display_menu->();
5467 SDL::Video::update_rect($app, 0, 0, 0, 0);
5468 $invalidate_all->();
5469 };
5470
5471 # Q&A for changing keys
5472 my $change_keys = sub {
5473 ask_from({
5474 intro => [ loc("Please enter new keys:") ],
5475 entries => [
5476 { 'q' => loc("Player 1; turn left?"), 'a' => \$KEYS->{p1}{left}, f => 'ONE_CHAR' },
5477 { 'q' => loc("Player 1; turn right?"), 'a' => \$KEYS->{p1}{right}, f => 'ONE_CHAR' },
5478 { 'q' => loc("Player 1; fire?"), 'a' => \$KEYS->{p1}{fire}, f => 'ONE_CHAR' },
5479 { 'q' => loc("Player 1; center?"), 'a' => \$KEYS->{p1}{center}, f => 'ONE_CHAR' },
5480 { f => 'SPACE' },
5481 { 'q' => loc("Player 2; turn left?"), 'a' => \$KEYS->{p2}{left}, f => 'ONE_CHAR' },
5482 { 'q' => loc("Player 2; turn right?"), 'a' => \$KEYS->{p2}{right}, f => 'ONE_CHAR' },
5483 { 'q' => loc("Player 2; fire?"), 'a' => \$KEYS->{p2}{fire}, f => 'ONE_CHAR' },
5484 { 'q' => loc("Player 2; center?"), 'a' => \$KEYS->{p2}{center}, f => 'ONE_CHAR' },
5485 { f => 'SPACE' },
5486 { 'q' => loc("Toggle fullscreen?"), 'a' => \$KEYS->{misc}{fs}, f => 'ONE_CHAR' },
5487 { 'q' => loc("Chat (net/lan game)?"), 'a' => \$KEYS->{misc}{chat}, f => 'ONE_CHAR' },
5488 ],
5489 outro => loc("Thanks!"),
5490 erase_background => $back_start
5491 });
5492 $invalidate_all->();
5493 # print Data::Dumper->Dump([$KEYS], [qw(KEYS)]), "\n";
5494 # die;
5495 };
5496
5497 my $launch_editor = sub {
5498 SDL::Mouse::show_cursor(1);
5499 Games::FrozenBubble::LevelEditor::init_setup('embedded', $app);
5500 Games::FrozenBubble::LevelEditor::handle_events();
5501 SDL::Mouse::show_cursor(0);
5502 $display_menu->();
5503 SDL::Video::update_rect($app, 0, 0, 0, 0);
5504 $invalidate_all->();
5505 };
5506
5507 my $speed_ok = 4;
5508
5509 my $candy_init = sub {
5510 # calculating positions and creating new surfaces for logo animations
5511 if (defined($candy)) {
5512 erase_image_from($imgbin{menu_logo}, $logox, $logoy, $back_start);
5513 $candy = undef;
5514 $imgbin{menu_logo} = add_image('menu/fblogo.png');
5515 }
5516
5517 ($logox, $logoy) = (400, 15);
5518 if ($logo_candy_method == 3) {
5519 #- stretch needs a bit more room
5520 my $newlogosurface = SDL::Surface->new(SDL_SWSURFACE, $imgbin{menu_logo}->w * 1.1, $imgbin{menu_logo}->h * 1.1, 32, 0xFF000000, 0xFF0000, 0xFF00, 0xFF);
5521 SDL::Video::set_alpha($imgbin{menu_logo}, 0, 0); #- for RGBA->RGBA blits, SDL_SRCALPHA must be removed or destination alpha is preserved
5522 SDL::Video::blit_surface($imgbin{menu_logo}, SDL::Rect->new(0,0,$imgbin{menu_logo}->w,$imgbin{menu_logo}->h), $newlogosurface, SDL::Rect->new( $imgbin{menu_logo}->w * 0.05, $imgbin{menu_logo}->h * 0.05, $imgbin{menu_logo}->w, $imgbin{menu_logo}->h));
5523 $logox -= $imgbin{menu_logo}->w * 0.05;
5524 $logoy -= $imgbin{menu_logo}->h * 0.05;
5525 $imgbin{menu_logo} = $newlogosurface;
5526 add_default_rect($imgbin{menu_logo});
5527 $logo_candy_method = 3.1; #- avoid doing it again at next menu run
5528 }
5529 if ($logo_candy_method == 4) {
5530 #- tilt needs a bit more horizontal room
5531 my $newlogosurface = SDL::Surface->new(SDL_SWSURFACE, $imgbin{menu_logo}->w * 1.1, $imgbin{menu_logo}->h * 1.05, 32, 0xFF000000, 0xFF0000, 0xFF00, 0xFF);
5532 SDL::Video::set_alpha($imgbin{menu_logo}, 0, 0); #- for RGBA->RGBA blits, SDL_SRCALPHA must be removed or destination alpha is preserved
5533 SDL::Video::blit_surface($imgbin{menu_logo}, SDL::Rect->new(0,0,$imgbin{menu_logo}->w,$imgbin{menu_logo}->h), $newlogosurface, SDL::Rect->new( $imgbin{menu_logo}->w * 0.05, $imgbin{menu_logo}->h * 0.025, $imgbin{menu_logo}->w, $imgbin{menu_logo}->h));
5534 $logox -= $imgbin{menu_logo}->w * 0.05;
5535 $logoy -= $imgbin{menu_logo}->h * 0.025;
5536 $imgbin{menu_logo} = $newlogosurface;
5537 add_default_rect($imgbin{menu_logo});
5538 $logo_candy_method = 4.1; #- avoid doing it again at next menu run
5539 }
5540 if ($logo_candy_method == 8) {
5541 #- snow needs to extend top, and a little more wideness
5542 my $newlogosurface = SDL::Surface->new( SDL_SWSURFACE, $imgbin{menu_logo}->w * 1.1, $imgbin{menu_logo}->h + $logoy, 32, 0xFF000000, 0xFF0000, 0xFF00, 0xFF);
5543 SDL::Video::set_alpha( $imgbin{menu_logo}, 0, 0); #- for RGBA->RGBA blits, SDL_SRCALPHA must be removed or destination alpha is preserved
5544 SDL::Video::blit_surface( $imgbin{menu_logo}, SDL::Rect->new(0,0,$imgbin{menu_logo}->w,$imgbin{menu_logo}->h), $newlogosurface, SDL::Rect->new($imgbin{menu_logo}->w * 0.05, $logoy, $imgbin{menu_logo}->w, $imgbin{menu_logo}->h));
5545 $logox -= $imgbin{menu_logo}->w * 0.05;
5546 $logoy = 0;
5547 $imgbin{menu_logo} = $newlogosurface;
5548 add_default_rect($imgbin{menu_logo});
5549 $logo_candy_method = 8.1; #- avoid doing it again at next menu run
5550 }
5551 $candy = SDL::Surface->new(SDL_SWSURFACE, $imgbin{menu_logo}->w, $imgbin{menu_logo}->h, 32, 0xFF000000, 0xFF0000, 0xFF00, 0xFF);
5552 };
5553 defined($candy) or $candy_init->();
5554 my $draw_logo = sub {
5555 my ($no_update) = @_;
5556 erase_image_from($imgbin{menu_logo}, $logox, $logoy, $back_start);
5557
5558 if ($graphics_level < 3 || !$speed_ok) {
5559 # logo is blittet as it is, without animations
5560 put_image($imgbin{menu_logo}, $logox, $logoy);
5561 }
5562 else { # logo animation
5563 # logo effects (snow, water, ...)
5564 Games::FrozenBubble::CStuff::rotate_bilinear($candy, $imgbin{menu_logo}, sin($logo_candy_index/40)/20) if $logo_candy_method == 0;
5565 Games::FrozenBubble::CStuff::flipflop($candy, $imgbin{menu_logo}, $logo_candy_index) if $logo_candy_method == 1;
5566 Games::FrozenBubble::CStuff::enlighten($candy, $imgbin{menu_logo}, $logo_candy_index) if $logo_candy_method == 2;
5567 Games::FrozenBubble::CStuff::stretch($candy, $imgbin{menu_logo}, $logo_candy_index) if $logo_candy_method == 3.1;
5568 Games::FrozenBubble::CStuff::tilt($candy, $imgbin{menu_logo}, $logo_candy_index) if $logo_candy_method == 4.1;
5569 Games::FrozenBubble::CStuff::points($candy, $imgbin{menu_logo}, $imgbin{menu_logo_mask}) if $logo_candy_method == 5;
5570 Games::FrozenBubble::CStuff::waterize($candy, $imgbin{menu_logo}, $logo_candy_index) if $logo_candy_method == 6;
5571 Games::FrozenBubble::CStuff::brokentv($candy, $imgbin{menu_logo}, $logo_candy_index) if $logo_candy_method == 7;
5572 Games::FrozenBubble::CStuff::snow($candy, $imgbin{menu_logo}) if $logo_candy_method == 8.1;
5573
5574 SDL::Video::blit_surface($candy, SDL::Rect->new(0,0,$candy->w,$candy->h), $app, SDL::Rect->new($logox, $logoy, $candy->w, $candy->h));
5575
5576 # next step for the animation
5577 $logo_candy_index++;
5578 }
5579
5580 if (!$no_update) {
5581 SDL::Video::update_rects($app, @update_rects);
5582 @update_rects = ();
5583 }
5584 };
5585
5586 $imgbin{menu_cursor}{graphics} = $imgbin{menu_cursor}{"graphics$graphics_level"};
5587 $imgbin{menu_cursor}{graphicsalpha} = $imgbin{menu_cursor}{"graphics${graphics_level}alpha"};
5588 my ($MENU_XPOS, $MENU_FIRSTY, $SPACING) = (89, 14, 56);
5589 # screen y-position of main menu elements
5590 my %menu_ypos = (
5591 '1pgame' => $MENU_FIRSTY,
5592 '2pgame' => $MENU_FIRSTY + $SPACING,
5593 'langame' => $MENU_FIRSTY + 2 * $SPACING,
5594 'netgame' => $MENU_FIRSTY + 3 * $SPACING,
5595 'editor' => $MENU_FIRSTY + 4 * $SPACING,
5596 'graphics' => $MENU_FIRSTY + 5 * $SPACING,
5597 'keys' => $MENU_FIRSTY + 6 * $SPACING,
5598 'highscores' => $MENU_FIRSTY + 7 * $SPACING,
5599 );
5600
5601 # menu indexes, and functions that are called before the function behind 'type' is called
5602 my %menu_entries = (
5603 '1pgame' => {
5604 pos => 1,
5605 type => 'rungame',
5606 run => sub { @PLAYERS = ('p1'); $levels{current} = 1; $time_1pgame = SDL::get_ticks() }
5607 },
5608 '2pgame' => {
5609 pos => 2,
5610 type => 'rungame',
5611 run => sub { @PLAYERS = qw(p1 p2); $levels{current} = undef; }
5612 },
5613 'langame'=> {
5614 pos => 3,
5615 type => 'rungame',
5616 run => sub { @PLAYERS = qw(p1 rp1); $pdata{gametype} = 'lan'; $levels{current} = undef; }
5617 },
5618 'netgame'=> {
5619 pos => 4,
5620 type => 'rungame',
5621 run => sub { @PLAYERS = qw(p1 rp1); $pdata{gametype} = 'net'; $levels{current} = undef; }
5622 },
5623 'editor' => {
5624 pos => 5,
5625 type => 'run',
5626 run => sub { $launch_editor->(); }
5627 },
5628 'graphics' => {
5629 pos => 6,
5630 type => 'range',
5631 valuemin => 1,
5632 valuemax => 3,
5633 change => sub {
5634 $graphics_level = $_[0];
5635 if ($graphics_level < 3) { $draw_logo->() } else { $speed_ok = 4; }
5636 $imgbin{menu_cursor}{graphics} = $imgbin{menu_cursor}{"graphics$graphics_level"};
5637 $imgbin{menu_cursor}{graphicsalpha} = $imgbin{menu_cursor}{"graphics${graphics_level}alpha"};
5638 $pdata{cursor_img}{graphics} = 0 if $pdata{cursor_img}{graphics} >= @{$imgbin{menu_cursor}{graphics}};
5639 },
5640 value => $graphics_level
5641 },
5642 'keys' => {
5643 pos => 7,
5644 type => 'run',
5645 run => sub { $change_keys->() }
5646 },
5647 'highscores' => {
5648 pos => 8,
5649 type => 'run',
5650 run => sub { $menu_display_highscores->() }
5651 },
5652 );
5653 $current_pos = 1; # selected menu entry (1..8) # THIS IS DEPRECEATED
5654 my @menu_invalids = (); # list of menu item's positions
5655 $invalidate_all = sub { push @menu_invalids, $menu_entries{$_}->{pos} foreach keys %menu_entries };
5656
5657 my $display_cursor = sub {
5658 my ($m, $alpha, $pixelize) = @_;
5659 my $cursor_rect = SDL::Rect->new( 248, $menu_ypos{$m} + 8,
5660 $imgbin{menu_cursor}{$m}[$pdata{cursor_img}{$m}]->w,
5661 $imgbin{menu_cursor}{$m}[$pdata{cursor_img}{$m}]->h);
5662 if (!defined($cursor_save_bg{$m})) {
5663 $cursor_save_bg{$m} = SDL::Surface->new(SDL_SWSURFACE, $imgbin{menu_cursor}{$m}[0]->w, $imgbin{menu_cursor}{$m}[0]->h, 32, 0,0,0,0);
5664 SDL::Video::blit_surface($app, $cursor_rect, $cursor_save_bg{$m}, SDL::Rect->new( 0, 0, $imgbin{menu_cursor}{$m}[0]->w, $imgbin{menu_cursor}{$m}[0]->h));
5665 }
5666 SDL::Video::blit_surface($cursor_save_bg{$m}, SDL::Rect->new(0,0,$cursor_save_bg{$m}->w,$cursor_save_bg{$m}->h), $app, $cursor_rect);
5667 if ($alpha) {
5668 if ($pixelize) {
5669 if (!defined($cursor_tmp)) {
5670 $cursor_tmp = SDL::Surface->new( SDL_SWSURFACE, $imgbin{menu_cursor}{$m}[0]->w, $imgbin{menu_cursor}{$m}[0]->h, 32, 0xFF000000,0xFF0000,0xFF00,0xFF);
5671 }
5672 # this effect appears randomly on not selected (animated) menu elements
5673 Games::FrozenBubble::CStuff::pixelize($cursor_tmp, $imgbin{menu_cursor}{"${m}alpha"}[$pdata{cursor_img}{$m}]);
5674 SDL::Video::blit_surface( $cursor_tmp, SDL::Rect->new(0,0,$cursor_tmp->w,$cursor_tmp->h), $app, $cursor_rect);
5675 }
5676 else {
5677 # not animated menu item
5678 SDL::Video::blit_surface( $imgbin{menu_cursor}{"${m}alpha"}[$pdata{cursor_img}{$m}], SDL::Rect->new(0,0,$imgbin{menu_cursor}{"${m}alpha"}[$pdata{cursor_img}{$m}]->w,$imgbin{menu_cursor}{"${m}alpha"}[$pdata{cursor_img}{$m}]->h), $app, $cursor_rect);
5679 }
5680 }
5681 else {
5682 # blits the animated icon for the selected menu item
5683 SDL::Video::blit_surface( $imgbin{menu_cursor}{$m}[$pdata{cursor_img}{$m}], SDL::Rect->new(0,0,$imgbin{menu_cursor}{$m}[$pdata{cursor_img}{$m}]->w,$imgbin{menu_cursor}{$m}[$pdata{cursor_img}{$m}]->h), $app, $cursor_rect);
5684 }
5685 return $cursor_rect;
5686 };
5687
5688 my $menu_update = sub {
5689 @update_rects = ();
5690 foreach my $m (keys %menu_entries) {
5691 member($menu_entries{$m}->{pos}, @menu_invalids) or next;
5692 my $txt = "txt_$m";
5693 $txt .= $menu_entries{$m}->{pos} == $current_pos ? '_over' : '_off';
5694 erase_image_from($imgbin{$txt}, $MENU_XPOS, $menu_ypos{$m}, $back_start);
5695 put_image($imgbin{$txt}, $MENU_XPOS, $menu_ypos{$m});
5696 $cursor_save_bg{$m} = undef;
5697 $display_cursor->($m, $menu_entries{$m}->{pos} != $current_pos);
5698 }
5699 @menu_invalids = ();
5700 $draw_logo->('no-update');
5701 SDL::Video::update_rects($app, @update_rects);
5702 @update_rects = ();
5703 };
5704
5705 $invalidate_all->();
5706 $menu_update->();
5707 SDL::Video::update_rect($app, 0, 0, 0, 0);
5708 SDL::Events::pump_events() while SDL::Events::poll_event($event) != 0;
5709
5710 my $start_game = 0;
5711 my ($BANNER_START, $BANNER_SPACING) = (1000, 80);
5712 my %banners = (artwork => $BANNER_START,
5713 soundtrack => $BANNER_START + $imgbin{banner_artwork}->w + $BANNER_SPACING,
5714 cpucontrol => $BANNER_START + $imgbin{banner_artwork}->w + $BANNER_SPACING
5715 + $imgbin{banner_soundtrack}->w + $BANNER_SPACING,
5716 leveleditor => $BANNER_START + $imgbin{banner_artwork}->w + $BANNER_SPACING
5717 + $imgbin{banner_soundtrack}->w + $BANNER_SPACING
5718 + $imgbin{banner_cpucontrol}->w + $BANNER_SPACING);
5719 my ($BANNER_MINX, $BANNER_MAXX, $BANNER_Y) = (304, 596, 243);
5720 my $banners_max = $banners{leveleditor} - (640 - ($BANNER_MAXX - $BANNER_MINX)) + $BANNER_SPACING;
5721 my $banner_rect = SDL::Rect->new( $BANNER_MINX, $BANNER_Y, $BANNER_MAXX-$BANNER_MINX, 30);
5722 my $time_counter;
5723
5724 while (!$start_game) {
5725 my $synchro_ticks = SDL::get_ticks();
5726
5727 $graphics_level > 1 and SDL::Video::blit_surface($back_start, $banner_rect, $app, $banner_rect);
5728
5729 SDL::Events::pump_events();
5730 while (SDL::Events::poll_event($event)) {
5731 my $keypressed = extended_keypress($event);
5732 if ($keypressed) {
5733 if ($keypressed eq SDLK_PAUSE) {
5734 my $time_pause = SDL::get_ticks();
5735 SDL::Events::pump_events() while SDL::Events::poll_event($event);
5736 pause_menu:
5737 while (1) {
5738 SDL::Events::wait_event($event);
5739 if ($event->type == SDL_QUIT) {
5740 cleanup_and_exit();
5741 }
5742 my $keypressed = extended_keypress($event);
5743 if ($keypressed) {
5744 $start_time += SDL::get_ticks() - $time_pause;
5745 last pause_menu;
5746 }
5747 }
5748 }
5749 my $keys_ref = SDL::Events::get_key_state();
5750 if ($keys_ref->[SDLK_LCTRL] == SDL_PRESSED
5751 && $keypressed == SDLK_n) {
5752 $logo_candy_method = (int($logo_candy_method) + 1) % 9;
5753 $candy_init->();
5754 }
5755 if (member($keypressed, (SDLK_DOWN, SDLK_RIGHT))) {
5756 push @menu_invalids, $current_pos;
5757 if ($current_pos < max(map { $menu_entries{$_}->{pos} } keys %menu_entries)) {
5758 $current_pos++;
5759 } else {
5760 $current_pos = 1;
5761 }
5762 push @menu_invalids, $current_pos;
5763 play_sound('menu_change');
5764 $menu_update->();
5765 }
5766 if (member($keypressed, (SDLK_UP, SDLK_LEFT))) {
5767 push @menu_invalids, $current_pos;
5768 if ($current_pos > 1) {
5769 $current_pos--;
5770 } else {
5771 $current_pos = max(map { $menu_entries{$_}->{pos} } keys %menu_entries);
5772 }
5773 push @menu_invalids, $current_pos;
5774 play_sound('menu_change');
5775 $menu_update->();
5776 }
5777 if (member($keypressed, (SDLK_RETURN, SDLK_SPACE, SDLK_KP_ENTER))) {
5778 play_sound('menu_selected');
5779 push @menu_invalids, $current_pos;
5780 foreach my $m (keys %menu_entries) {
5781 if ($menu_entries{$m}->{pos} == $current_pos) {
5782 if ($menu_entries{$m}->{type} =~ /^run/) {
5783 $menu_entries{$m}->{run}->();
5784 $menu_entries{$m}->{type} eq 'rungame' and $start_game = 1;
5785 }
5786 if ($menu_entries{$m}->{type} eq 'range') {
5787 $menu_entries{$m}->{value}++;
5788 $menu_entries{$m}->{value} = $menu_entries{$m}->{valuemin} if $menu_entries{$m}->{value} > $menu_entries{$m}->{valuemax};
5789 $menu_entries{$m}->{change}->($menu_entries{$m}->{value});
5790 }
5791 }
5792 }
5793 $menu_update->();
5794 }
5795 handle_whenever_events($keypressed);
5796
5797 if ($keypressed eq SDLK_ESCAPE) {
5798 cleanup_and_exit();
5799 }
5800 $synchro_ticks = SDL::get_ticks(); #- avoid stopping candy
5801 $time_counter = 0; #- reset counter for demos
5802 }
5803 if ($event->type == SDL_QUIT) {
5804 cleanup_and_exit();
5805 }
5806 }
5807
5808 if ($graphics_level > 1) {
5809
5810 $banner_pos ||= 670;
5811 foreach my $b (keys %banners) {
5812 my $xpos = $banners{$b} - $banner_pos;
5813 my $image = $imgbin{"banner_$b"};
5814
5815 $xpos > $banners_max/2 and $xpos = $banners{$b} - ($banner_pos + $banners_max);
5816
5817 if ($xpos < $BANNER_MAXX && $xpos + $image->w >= 0) {
5818 my $irect = SDL::Rect->new(-$xpos, 0, min($image->w+$xpos, $BANNER_MAXX-$BANNER_MINX),
5819 $image->h);
5820 SDL::Video::blit_surface( $image, $irect, $app, SDL::Rect->new( $BANNER_MINX, $BANNER_Y, $image->w, $image->h) );
5821 }
5822 }
5823 $banner_pos++;
5824 $banner_pos >= $banners_max and $banner_pos = 1;
5825 SDL::Video::update_rects($app, $banner_rect);
5826
5827 #- animate and break cursor
5828 foreach my $m (keys %menu_entries) {
5829 if ($menu_entries{$m}->{pos} == $current_pos) {
5830 $pdata{cursor_img}{$m}++;
5831 $pdata{cursor_img}{$m} >= @{$imgbin{menu_cursor}{$m}} and $pdata{cursor_img}{$m} = 0;
5832 SDL::Video::update_rects($app, $display_cursor->($m, 0));
5833
5834 } else {
5835 if ($broken_cursors{$m}) {
5836 $broken_cursors{$m}--;
5837 if ($broken_cursors{$m}) {
5838 SDL::Video::update_rects($app, $display_cursor->($m, 1, 1));
5839 } else {
5840 SDL::Video::update_rects($app, $display_cursor->($m, 1));
5841 }
5842 } else {
5843 rand() < 0.001 and $broken_cursors{$m} = int(20 + 10 * cos(rand(2*$PI)));
5844 }
5845 }
5846 }
5847
5848 #- blinking handling follows
5849 my $blink_green_left = [ 411, 385 ];
5850 my $blink_green_right = [ 434, 378 ];
5851 my $green_left = SDL::Rect->new( $blink_green_left->[0], $blink_green_left->[1],
5852 $imgbin{menu_closedeye_green_left}->w, $imgbin{menu_closedeye_green_left}->h);
5853 my $green_right = SDL::Rect->new( $blink_green_right->[0], $blink_green_right->[1],
5854 $imgbin{menu_closedeye_green_right}->w, $imgbin{menu_closedeye_green_right}->h);
5855 my $blink_purple_left = [ 522, 356 ];
5856 my $blink_purple_right = [ 535, 356 ];
5857 my $purple_left = SDL::Rect->new($blink_purple_left->[0], $blink_purple_left->[1],
5858 $imgbin{menu_closedeye_purple_left}->w, $imgbin{menu_closedeye_purple_left}->h);
5859 my $purple_right = SDL::Rect->new($blink_purple_right->[0], $blink_purple_right->[1],
5860 $imgbin{menu_closedeye_purple_right}->w, $imgbin{menu_closedeye_purple_right}->h);
5861 if ($blink_green > 0) {
5862 $blink_green--;
5863 if (!$blink_green) {
5864 SDL::Video::blit_surface ( $back_start, $green_left, $app, $green_left);
5865 SDL::Video::blit_surface ( $back_start, $green_right, $app, $green_right);
5866 SDL::Video::update_rects ($app, $green_left, $green_right);
5867 if (rand(3) <= 1) { #- reblink
5868 $blink_green = -5;
5869 }
5870 }
5871 } elsif ($blink_green < 0) {
5872 $blink_green++;
5873 if (!$blink_green) {
5874 $blink_green = 3;
5875 SDL::Video::blit_surface ( $imgbin{menu_closedeye_green_left}, SDL::Rect->new(0,0,$imgbin{menu_closedeye_green_left}->w,$imgbin{menu_closedeye_green_left}->h), $app, $green_left);
5876 SDL::Video::blit_surface ( $imgbin{menu_closedeye_green_right}, SDL::Rect->new(0,0,$imgbin{menu_closedeye_green_right}->w,$imgbin{menu_closedeye_green_right}->h), $app, $green_right);
5877 SDL::Video::update_rects( $app, $green_left, $green_right);
5878 }
5879 } else {
5880 if (rand(200) <= 1) {
5881 $blink_green = 3;
5882 SDL::Video::blit_surface ( $imgbin{menu_closedeye_green_left},SDL::Rect->new(0,0,$imgbin{menu_closedeye_green_left}->w,$imgbin{menu_closedeye_green_left}->h), $app, $green_left);
5883 SDL::Video::blit_surface ( $imgbin{menu_closedeye_green_right},SDL::Rect->new(0,0,$imgbin{menu_closedeye_green_right}->w,$imgbin{menu_closedeye_green_right}->h), $app, $green_right);
5884 SDL::Video::update_rects( $app,$green_left, $green_right);
5885 }
5886 }
5887 if ($blink_purple > 0) {
5888 $blink_purple--;
5889 if (!$blink_purple) {
5890 SDL::Video::blit_surface ( $back_start,$purple_left, $app, $purple_left);
5891 SDL::Video::blit_surface ( $back_start,$purple_right, $app, $purple_right);
5892 SDL::Video::update_rects( $app,$purple_left, $purple_right);
5893 if (rand(3) <= 1) { #- reblink
5894 $blink_purple = -5;
5895 }
5896 }
5897 } elsif ($blink_purple < 0) {
5898 $blink_purple++;
5899 if (!$blink_purple) {
5900 $blink_purple = 3;
5901 SDL::Video::blit_surface ( $imgbin{menu_closedeye_purple_left},SDL::Rect->new(0,0,$imgbin{menu_closedeye_purple_left}->w,$imgbin{menu_closedeye_purple_left}->h), $app, $purple_left);
5902 SDL::Video::blit_surface ( $imgbin{menu_closedeye_purple_right},SDL::Rect->new(0,0,$imgbin{menu_closedeye_purple_right}->w,$imgbin{menu_closedeye_purple_right}->h), $app, $purple_right);
5903 SDL::Video::update_rects( $app,$purple_left, $purple_right);
5904 }
5905 } else {
5906 if (rand(200) <= 1) {
5907 $blink_purple = 3;
5908 SDL::Video::blit_surface ( $imgbin{menu_closedeye_purple_left},SDL::Rect->new(0,0,$imgbin{menu_closedeye_purple_left}->w,$imgbin{menu_closedeye_purple_left}->h), $app, $purple_left);
5909 SDL::Video::blit_surface ( $imgbin{menu_closedeye_purple_right},SDL::Rect->new(0,0,$imgbin{menu_closedeye_purple_right}->w,$imgbin{menu_closedeye_purple_right}->h), $app, $purple_right);
5910 SDL::Video::update_rects( $app,$purple_left, $purple_right);
5911 }
5912 }
5913
5914 }
5915
5916 if ($graphics_level > 2 && $speed_ok) {
5917 $draw_logo->();
5918 }
5919
5920 my $to_wait = $TARGET_ANIM_SPEED - (SDL::get_ticks() - $synchro_ticks);
5921 # print "$to_wait\n";
5922 if ($to_wait > 0) {
5923 Games::FrozenBubble::CStuff::fbdelay($to_wait);
5924 $speed_ok and $speed_ok = 4;
5925 } else {
5926 #- disable nice graphics artwork if computer is too slow
5927 # print "$to_wait\n";
5928 if ($speed_ok) {
5929 $speed_ok--;
5930 if (!$speed_ok) {
5931 print "Eye-candy animation is too slow, disabling ($logo_candy_method).\n";
5932 $draw_logo->();
5933 }
5934 }
5935 }
5936
5937 if (++$time_counter == 1000) { #- 20 seconds
5938 $pdata{demo} = 1;
5939 my @files = glob("$FPATH/data/demo*");
5940 replay($files[int(rand(@files))]);
5941 $pdata{demo} = 0;
5942 blacken:
5943 foreach my $step (1..35) {
5944 my $ticks = SDL::get_ticks();
5945 Games::FrozenBubble::CStuff::blacken($app, $step);
5946 SDL::Video::update_rect($app, 0, 0, 0, 0);
5947 my $to_wait = $TARGET_ANIM_SPEED - (SDL::get_ticks() - $ticks);
5948 $to_wait > 0 and Games::FrozenBubble::CStuff::fbdelay($to_wait);
5949
5950 SDL::Events::pump_events();
5951 while (SDL::Events::poll_event($event) != 0) {
5952 if ($event->type == SDL_QUIT) {
5953 cleanup_and_exit();
5954 }
5955 if (extended_keypress($event)) {
5956 last blacken;
5957 }
5958 }
5959 }
5960 $display_menu->();
5961 $invalidate_all->();
5962 $menu_update->();
5963 SDL::Video::update_rect($app, 0, 0, 0, 0);
5964 $time_counter = 0;
5965 play_music('intro');
5966 }
5967 }
5968
5969 save_config();
5970
5971 iter_players {
5972 !is_1p_game() and $pdata{$::p}{score} = 0;
5973 };
5974 }
5975
5976
5977 #- ----------- editor stuff --------------------------------------------
5978
5979 sub choose_levelset() {
5980 my ($choose_level) = @_;
5981
5982 my @levelsets = sort glob("$FBLEVELS/*");
5983
5984 if (!@levelsets && !$choose_level) {
5985 # no $FBHOME/levels directory or void directory, just return and let the
5986 # game continue (means that the level editor has never been opened)
5987
5988 } else {
5989
5990 if (@levelsets <= 1 && !$choose_level) {
5991 load_levelset($levelsets[0]);
5992 } else {
5993 #if they are choosing the start level, we need to ensure the default
5994 #levelset is in $FBLEVELS or the dialog won't display properly
5995 if ($choose_level) {
5996 -d $FBLEVELS or mkdir $FBLEVELS;
5997 -d $FBLEVELS or die "Can't create $FBLEVELS directory.\n";
5998 -f "$FBLEVELS/default-levelset" or cp_af("$FPATH/data/levels", "$FBLEVELS/default-levelset");
5999 }
6000
6001 Games::FrozenBubble::LevelEditor::init_app('embedded', $app);
6002 Games::FrozenBubble::LevelEditor::create_play_levelset_dialog($choose_level, $levels{current});
6003 SDL::Mouse::show_cursor(1);
6004 my @game_info = Games::FrozenBubble::LevelEditor::handle_events();
6005 @game_info or return;
6006 load_levelset("$FBLEVELS/$game_info[0]");
6007 $levels{current} = $game_info[1];
6008 SDL::Mouse::show_cursor(0);
6009 }
6010 }
6011
6012 return 1;
6013 }
6014
6015 sub replay {
6016 my ($replayfile) = @_;
6017 if ($replayfile =~ /^http/) {
6018 my $filename = $replayfile;
6019 $replayfile = Games::FrozenBubble::Net::http_download($replayfile);
6020 $replayfile or return;
6021 if ($filename =~ /\.bz2$/) {
•6022 my $fh = File::Temp->new();
6023 $filename = $fh->filename;
6024 print $fh $replayfile;
6025 $fh->close;
6026 local *F;
6027 local $/ = undef;
6028
6029 return unless -e $filename;
6030
6031 my $bz = Compress::Bzip2::bzopen($filename, 'r');
6032 $replayfile = '';
6033 my $line = '';
6034 while($bz->bzreadline($line) > 0){ $replayfile .= $line; }
6035
6036 $bz->bzclose();
6037 }
6038 } else {
6039 if ($replayfile =~ /\.bz2$/) {
6040 local *F;
6041 local $/ = undef;
6042 my $filename = $replayfile;
6043
6044 return unless -e $filename;
6045
6046 my $bz = Compress::Bzip2::bzopen($filename, 'r');
6047 $replayfile = '';
6048 my $line = '';
6049 while($bz->bzreadline($line) > 0){ $replayfile .= $line; }
6050
6051 $bz->bzclose();
6052 } else {
6053 $replayfile = cat_($replayfile);
6054 }
6055 }
6056 my $b = before_leaving {
6057 $playdata = undef;
6058 srand SDL::get_ticks();
6059 };
6060 %recorddata = ();
6061 $playdata = [];
6062 my $linenumber = 0;
6063 my $current_frame_num;
6064 my $current_frame_action_data = {};
6065 my $current_frame_mp_messages_data = [];
6066 foreach my $line (split /\n/, $replayfile) {
6067 $linenumber++;
6068 my ($key, $value) = $line =~ /(.*?):(.*)?/ or print("Incorrect line number $linenumber in savegame.\n"), return;
6069 if ($key eq 'record_protocol') {
6070 if ($value > $RECORD_PROTOCOL_LEVEL) {
6071 print("Sorry, a more recent version of Frozen-Bubble is needed to play this record.\n"), return;
6072 } elsif ($value < $RECORD_PROTOCOL_LEVEL) {
6073 print("Sorry, an older version of Frozen-Bubble is needed to play this record.\n"), return;
6074 }
6075 } elsif ($key eq 'players') {
6076 @PLAYERS = split /,/, $value;
6077 } elsif ($key eq 'gametype') {
6078 $pdata{gametype} = $value;
6079 } elsif ($key eq 'current_level') {
6080 $levels{current} = $value;
6081 } elsif ($key eq 'chainreaction') {
6082 $chainreaction = $value;
6083 } elsif ($key eq 'time') {
6084 print 'Game recorded on ' . localtime($value) . ".\n";
6085 } elsif ($key eq 'comment') {
6086 print "Comment specified with record: $value.\n";
6087 } elsif ($key eq 'srand') {
6088 srand $value;
6089 } elsif ($key eq 'bubbles') {
6090 @{$recorddata{pdatas}{bubbles}} = split /,/, $value;
6091 } elsif ($key eq 'mp_result') {
6092 $recorddata{pdatas}{mp_result} = $value;
6093 } elsif ($key eq 'player_id') {
6094 my ($p, $id) = $value =~ /(.*?)\|(.*)/ or print("Incorrect line number $linenumber in savegame.\n"), return;
6095 $pdata{$p}{id} = $id;
6096 } elsif ($key eq 'player_nick') {
6097 my ($p, $nick) = $value =~ /(.*?)\|(.*)/ or print("Incorrect line number $linenumber in savegame.\n"), return;
6098 $pdata{$p}{nick} = $nick;
6099 } elsif ($key eq 'frame_action') {
6100 my ($framenum, $player, $action, $actionvalue) = $value =~ /(\d+)\|(\w+)\|(\w+)\|(\w+)/;
6101 if ($framenum != $current_frame_num && defined($current_frame_num)) {
6102 push @$playdata, [ $current_frame_num, { actions => $current_frame_action_data,
6103 mp_messages => $current_frame_mp_messages_data } ];
6104 $current_frame_action_data = {};
6105 $current_frame_mp_messages_data = [];
6106 }
6107 $current_frame_num = $framenum;
6108 $current_frame_action_data->{$player}{$action} = $actionvalue;
6109 } elsif ($key eq 'frame_mpmessage') {
6110 my ($framenum, $id, $message) = $value =~ /(\d+)\|(.)\|(.+)/;
6111 if ($framenum != $current_frame_num && defined($current_frame_num)) {
6112 push @$playdata, [ $current_frame_num, { actions => $current_frame_action_data,
6113 mp_messages => $current_frame_mp_messages_data } ];
6114 $current_frame_action_data = {};
6115 $current_frame_mp_messages_data = [];
6116 }
6117 $current_frame_num = $framenum;
6118 push @$current_frame_mp_messages_data, { id => $id, msg => $message };
6119 }
6120 }
6121 push @$playdata, [ $current_frame_num, { actions => $current_frame_action_data,
6122 mp_messages => $current_frame_mp_messages_data } ];
6123 $pdata{$_}{score} = 0 foreach @PLAYERS;
6124 if (is_mp_game()) {
6125 foreach my $p (@PLAYERS) {
6126 $pdata{id2p}{$pdata{$p}{id}} = $p;
6127 }
6128 }
6129 local $direct = 1;
6130 #- I'm wondering if the following is really more dirty than adding a $playdata test in the beginning of the three functions..
6131 local *Games::FrozenBubble::Net::gsend = sub {};
6132 local *Games::FrozenBubble::Net::grecv_get1msg_ifdata = sub { return; };
6133 local *check_mp_connection = sub {};
6134 new_game_once();
6135 new_game();
6136 while (1) {
6137 eval { maingame() };
6138 if ($@) {
6139 if ($@ =~ /^quit/ || $@ =~ /^new_game/) {
6140 last;
6141 } else {
6142 die;
6143 }
6144 }
6145 }
6146 }
6147
6148 #- ----------- main -------------------------------------------------------
6149
6150 init_game();
6151
6152 if ($replayparam) {
6153 replay($replayparam);
6154 $replayparam = undef;
6155 }
6156
6157 if (!$direct) {
6158 menu('first time');
6159 }
6160
6161 while (!new_game_once()) { menu() }
6162 new_game() or goto go_to_menu;
6163
6164 while (1) {
6165 eval { maingame() };
6166 if ($@) {
6167 my $died = $@;
6168 my $recorded = save_record_if_needed();
6169 if ($start_time != 0) {
6170 $addicted_time += SDL::get_ticks() - $start_time;
6171 $start_time = 0;
6172 }
6173
6174 if ($died =~ /^new_game/) {
6175 new_game() or goto go_to_menu;
6176
6177 } elsif ($died =~ /^quit/) {
6178 if (is_mp_game()) {
6179 if ($pdata{gametype} eq 'lan') {
6180 Games::FrozenBubble::Net::disconnect();
6181 show_mp_scores();
6182 grab_key();
6183 goto go_to_menu;
6184 } else {
6185 if (Games::FrozenBubble::Net::reconnect() && new_game_once()) {
6186 new_game() or goto go_to_menu;
6187 } else {
6188 goto go_to_menu;
6189 }
6190 }
6191 } else {
6192 go_to_menu:
6193 do { menu() } while (!new_game_once());
6194 new_game();
6195 }
6196
6197 } else {
6198 if (!$recorded) {
6199 print "\n******************************************************************************\n"
6200 . "* Unexpected abort in process! Forcing record: please send the record file to FB authors so that they fix the bug if possible!\n"
6201 . "******************************************************************************\n\n";
6202 $autorecord = 1;
6203 save_record_if_needed();
6204 } else {
6205 print "\n******************************************************************************\n"
6206 . "* Unexpected abort in process! Please send the record file to FB authors so that they fix the bug if possible!\n"
6207 . "******************************************************************************\n\n";
6208 }
6209 die $died;
6210 }
6211 }
6212 }
6213
6214 __END__
6215
6216 =encoding UTF-8
6217
6218 =head1 NAME
6219
6220 frozen-bubble - arcade/reflex game
6221
6222 =head1 SYNOPSIS
6223
6224 frozen-bubble [OPTION]...
6225
6226 =head1 DESCRIPTION
6227
6228 The B<Frozen-Bubble> game is a free software implementation of
6229 a popular arcade/reflex game. The game mainly consists of firing
6230 randomly chosen bubbles across the board. If the shoot ends up
6231 having a clump of at least 3 bubbles of the same color, they all
6232 pop. If some bubbles were sticked only on the popping clump, they
6233 fall. In 1-player mode, the goal is to pop all the bubbles on the
6234 board as quickly as possible. In 2-players or network mode, you
6235 have to get your opponent to "die" before you.
6236
6237 =head1 CONTROL
6238
6239 The default controlling mechanism is through the keyboard, but
6240 you can play with a joystick or a joypad if it is supported by
6241 the system (use the commandline option B<-ji> to make sure
6242 frozen-bubble detected your joysticks). A key (or a joystick
6243 direction or button) is needed for moving the aim to the left,
6244 moving the aim to the right, center, and fire.
6245
6246 =head1 1-PLAYER GAME
6247
6248 In single player mode, as a beginner the best training is to
6249 choose B<Play Default Levelset>, which lets you run through
6250 100 levels of an increasing difficulty. Pop all the bubbles of
6251 each level to advance to the next level.
6252
6253 If you want to train for multiplayer, choose B<Multiplayer
6254 Training> which reproduces the conditions of 2-player or
6255 network mode; the only difference is that created malus bubbles
6256 are counted in your score, and you must get the highest score you
6257 can in 2 minutes.
6258
6259 =head1 2-PLAYERS GAME
6260
6261 In 2-players mode, you can play against a friend (or a foe,
6262 actually) on the same computer. The board is populated with
6263 random bubbles, and your goal is to make big clumps to send malus
6264 bubbles to your opponent.
6265
6266 =head1 NETWORK GAME
6267
6268 If your computer has networking, you can choose LAN GAME to play
6269 games against others on your local network (up to 5 players).
6270 Frozen-Bubble will look for a game server on the local network
6271 with a UDP broadcast, connect to it if found, or start a new game
6272 server if not found.
6273
6274 If your computer is connected to Internet, you can choose NET
6275 GAME to play against others on Earth (or beyond?). Frozen-Bubble
6276 will retrieve the server list from the master server and propose
6277 you to choose between available servers. The flag in front of a
6278 server indicates the preferred language for chatting with others
6279 before the game is started. The ping is the roundtrip when
6280 talking with the server, choose a low ping when possible.
6281
6282 =head1 OPTIONS
6283
6284 =over
6285
6286 =item B<--help>
6287
6288 show command-line options summary
6289
6290 =item B<--fullscreen>
6291
6292 start the game in fullscreen mode
6293
6294 =item B<--no-fullscreen>
6295
6296 don't start the game in fullscreen mode
6297
6298 =item B<--no-sound>
6299
6300 disable music and sound effects
6301
6302 =item B<--no-music>
6303
6304 disable music (but not sound effects)
6305
6306 =item B<--no-sfx>
6307
6308 disable sound effects (but not music)
6309
6310 =item B<--playlist> I<directory>
6311
6312 use all files of the given directory as music files and play them
6313
6314 =item B<--playlist> I<file>
6315
6316 use all files listed in the given file as music files and play them
6317
6318 =item B<--slow-machine>
6319
6320 use this option if B<frozen-bubble>
6321 runs too slowly on your machine (disables a few animations)
6322
6323 =item B<--very-slow-machine>
6324
6325 same as before, if it is not enough (disables all that can be disabled)
6326
6327 =item B<--solo>
6328
6329 directly start solo (1p) game, with random levels
6330
6331 =item B<--direct>
6332
6333 directly start 2p game (don't display menu)
6334
6335 =item B<--gameserver> I<host[:port]>
6336
6337 directly start NET/LAN game connecting to this game server (if
6338 port is omitted, default port is used)
6339
6340 =item B<--chain-reaction>
6341
6342 enable chain-reaction
6343
6344 =item B<--level> I<number>
6345
6346 start directly the game, at level I<number>
6347
6348 =item B<--colour-blind>
6349
6350 use special bubbles for colourblind people
6351
6352 =item B<--no-time-limit>
6353
6354 disable time limit for shooting (e.g. kids mode)
6355
6356 =item B<--player-malus> I<number>
6357
6358 add I<number> malus to the left player (can be negative -
6359 doesn't work in network mode)
6360
6361 =item B<--mp-training-difficulty> I<number>
6362
6363 set the average duration between receiving malus bubbles in 1
6364 player multiplayer training (default 30 (= every 30 seconds on
6365 average), the lower the harder)
6366
6367 =item B<--joysticks-info>
6368
6369 print information about detected joystick(s) on startup (if
6370 Frozen-Bubble doesn't see your joysticks/joypads, try loading
6371 the joydev module with B<modprobe joydev> as root, then
6372 retry)
6373
6374 =item B<--no-echo>
6375
6376 when sound is enabled, disable echoing each typed character with
6377 a typewriter sound (it may get on your nerves)
6378
6379 =item B<--my-nick> I<nick>
6380
6381 for NET/LAN games, use this nick instead of username (max 10
6382 chars, ASCII alphanumeric plus dash and underscore only) - notice
6383 that the /nick command is also available when connected to a
6384 server to set your nick
6385
6386 =item B<--private>
6387
6388 after connecting to a server for a NET game, don't use
6389 http://hostip.info/ to retrieve your geographical position to
6390 send it to other players
6391
6392 =item B<--record> I<directory>
6393
6394 specify the recording directory (normally, records are saved in
6395 the directory '.frozen-bubble/records' down your home directory)
6396
6397 =item B<--auto-record>
6398
6399 automatically record all applicable games (normally, a record is
6400 triggered by hitting the Print Screen key during a game)
6401
6402 =item B<--comment> I<'...'>
6403
6404 add the comment enclosed between simple quotes to records (must
6405 not contain anything else than ASCII), it will be shown on
6406 console when playing back the record later
6407
6408 =item B<--replay> I<record_file|URL>
6409
6410 playback the specified record file
6411
6412 =item B<--save-frames> I<directory>
6413
6414 specify a directory where all (game) frames will be recorded; as the
6415 game is slowed down, can only be used with --replay; warning, output
6416 is huge as 50 frames of each 900 KB are saved per second (e.g. 43 MB
6417 per second); a typical use case is then to build a video out of the
6418 frames with e.g. this kind of command:
6419
6420 mencoder mf:///tmp/fbframes/frame* -mf fps=50 -o /tmp/output.avi -ovc lavc -lavcopts vcodec=mpeg4
6421
6422 =back
6423
6424 =head1 AUTHOR
6425
6426 Written by Guillaume Cottenceau.
6427 This manual page was originally written by Josselin Mouette <josselin.mouette at ens-lyon.org>.
6428
6429 Visit official homepage: L<http://www.frozen-bubble.org/>
6430
6431 =head1 SEE ALSO
6432
6433 frozen-bubble-editor
6434
6435 =head1 COPYRIGHT
6436
6437 Copyright © 2000-2010 The Frozen-Bubble Team.
6438
6439 This is Free Software; this software is licensed under the GPL version 2, as published by the Free Software Foundation.
6440 There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.