Archive for the ‘game’ Category

“Guess the film” revisited

Yes, I know I posted the other entry last night, but after that I kept messing around with the code. One of my friend requests was to have a GUI (seriously?). Ok, after thinking about it, and modifying some code here is the version 0.7 of this magnificent and almighty implementation of guess the film.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright (c) 2010 Oscar Carballal Prego <info@oscarcp.com>
#
# Distributed under terms of the MIT license.
 
# TODO:
# - Solve the codification problem in Windows.
# - Improve the films list to have a director and description.
 
# FIXME:
# - _get_film(self) does not print 5 spaces before text in format string
 
# Import python modules
import sys
import random
import datetime
 
 
class Game():
 
    def __init__(self):
        """
        Start everything. Declare dictionaries and lists, open files and get
        all the content ready.
        """
        self.films_file = open('films.txt', 'r')
        self.films = []
        self.players = {}
 
        [self.films.append([line]) for line in self.films_file]
        self.films_file.close()
 
    def _end(self):
        """
        This function terminates the game, after showing a basic statistic of
        the game.
        """
        self.end_time = datetime.datetime.now()
        self.t = str((self.end_time - self.start_time)).split(':')
        self.counter = len(self.players) - 1
        self.p = self.players.items()
        self.fwinner = max(self.players, key = lambda a: self.players.get(a))
        print "\n\n In a game of {0} players, results are:\n".format(len(self.players))
        print " Time: {0} hours, {1} minutes, {2} seconds.\n".format(self.t[0],
                                                                     self.t[1],
                                                                     self.t[2].split('.')[0])
        print " Points\n ------\n"
        while self.counter >= 0:
            print " {0} won {1} points.".format(self.p[self.counter][0],
                                                self.p[self.counter][1])
            self.counter -= 1
        print "\n ******* Winner: {0} *******\n".format(self.fwinner)
        # Clear everything
        del self.films[:]
        self.players.clear()
        sys.exit(0)
 
    def _get_players(self):
        """
        This function asks the number of players and their names. Names are
        stored in a dictionary as a key with a value of zero for every player.
        """
        self.i = 0
        self.check = 0
        while self.check == 0:
            try:
                self.n_players = int(raw_input('* How many players? '))
                self.check = 1
            except ValueError:
                print '* ERROR: Must type a number!'
        if self.n_players == 1:
            print '* Are you kidding? This can\'t be played alone!.'
            sys.exit(0)
        while self.i < self.n_players:
            self.player_name = raw_input('Player {0} name: '.format(self.i))
            self.players[self.player_name] = 0
            self.i += 1
 
    def _get_points(self):
        """
        This function stores the points earned by a player. It simply increases
        the number of the value by one in the pair [key,value].
        """
        try:
            self.winner = raw_input('* Who guessed? (player name, case sensitive): ')
            self.players[self.winner] += 1
        except:
            self._get_points()
 
    def _get_film(self):
        """
        This function gets a random film from the film list.
        """
        print '\n {0:>5}'.format(random.choice(self.films)[0])
 
    def start(self):
        """
        This function starts the game. It gets the time when the game is
        started and enters a loop asking to generate a new film. If the player
        does not want a new film _end() is executed.
        """
        self._get_players()
        self.start_time = datetime.datetime.now()
        while True:
            self.generate = raw_input('* Generate film? (s/n) ')
            if self.generate == 'n' or self.generate == 'no':
                self._end()
            else:
                self._get_film()
                self._get_points()
 
if __name__ == '__main__':
    game = Game()
    game.start()

“Guess the film” python game

UPDATE: The original strings were in spanish, so I translated them to english for a better understanding.

I didn’t mean to post this, but the code of this mini game has grown (in 2 hours) so much that I thought someone would be interested. It is a “Guess the film” game that a friend asked me to do (while finishing the petition with: I’m not gonna pay you! hehe).

It’s a very basic version that works on terminal/windows command line. You must provide it with a file with film names which must be interpreted (mute) by the person who guessed the last film, and the program does the rest. It has a player system with points, and a very basic stats system with a list of player points and game time. Hope you’ll find it useful!.

And one more thing, I know the code can be improved, but what the hell, I wont get paid for this! :-)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# Copyright (c) 2010 Oscar Carballal Prego <info@oscarcp.com>
# Distributed under MIT license
# -*- coding: utf-8 -*-
 
# TODO:
# - Replace lists for dictionaries.
# - Solve the codification problem in Windows.
# - Improve the films list to have a director and description.
 
# Import python modules
import sys
import random
import datetime
 
# Open files and create empty lists
films_file = open('films.txt', 'r')
films = []
players = []
points = []
n_players = 0
 
 
def generate_random():
    """
    This function picks a random film from the films list.
    """
    print '\n    %s' % (random.choice(films)[0])
 
 
def get_players():
    """
    This function asks how many players and their names to store them and
    make the stats after the game.
    """
    i = 0
    global n_players
    try:
        n_players = int(raw_input('* How many players? '))
    except:
        print 'ERROR: You must provide a number. Exiting...'
        sys.exit(1)
    if n_players == 1:
        print '* Are you kidding? You can\'t play this alone!'
        sys.exit(0)
    else:
        fake_players = n_players - 1
        while fake_players >= 0:
            points.append(0)
            fake_players -= 1
    while i < n_players:
        player_name = raw_input('Player %s name: ' % (i))
        players.append(player_name)
        i += 1
 
 
def get_points():
    winner = int(raw_input('* Who guessed? (player number): '))
    points[winner] += 1
 
 
def endgame():
    global n_players
    films_file.close()
    end = datetime.datetime.now()
    game_time = str((end - start)).split(':')
    print " "
    print " "
    print " In a game with %s players, the statistics are:" % (n_players)
    print " "
    print " Game time: %s hours, %s minutes, %s seconds." % (game_time[0],
                                                             game_time[1],
                                               game_time[2].split('.')[0])
    print " "
    print " Points"
    print " ----------"
    print " "
    players_counter = n_players - 1
    while players_counter >= 0:
        print " %s won %s points." % (players[players_counter],
                                        points[players_counter])
        players_counter -= 1
    print " "
    pos_winner = points.index(max(points))
    print " ******* Winner: %s *******" % (players[pos_winner])
    print " "
    sys.exit(0)
 
# Set start time (due to the speed of execution we can put this here instead
# of calling it in the first game call, it just makes some microseconds more)
start = datetime.datetime.now()
 
# Fill the films list with film names
[films.append([line]) for line in films_file]
 
get_players()
 
while True:
    generate = raw_input('* Generate film? (y/n) ')
    [endgame() if generate == 'n' or generate == 'no' else generate_random()]
    get_points()