Advertisement
KidaCoding

SpyGameApp

Sep 22nd, 2024 (edited)
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 9.41 KB | Source Code | 0 0
  1. import random
  2. import sqlite3
  3. from kivy.app import App
  4. from kivy.uix.boxlayout import BoxLayout
  5. from kivy.uix.button import Button
  6. from kivy.uix.label import Label
  7. from kivy.uix.textinput import TextInput
  8. from kivy.uix.popup import Popup
  9. from kivy.uix.screenmanager import ScreenManager, Screen
  10. from kivy.clock import Clock
  11. from kivy.core.window import Window
  12.  
  13. # color
  14. Window.clearcolor = (0.9, 0.9, 0.9, 1)
  15.  
  16. # Topic
  17. class TopicSelectionScreen(Screen):
  18.     def __init__(self, **kwargs):
  19.         super().__init__(**kwargs)
  20.         layout = BoxLayout(orientation='vertical')
  21.         developer_label = Label(text='Developed by: Mohamed Hussein (Mando)', size_hint_y=None, height=40)
  22.         layout.add_widget(developer_label)
  23.  
  24.         self.topic_input = TextInput(hint_text='Add a custom topic', size_hint_y=None, height=40)
  25.         layout.add_widget(self.topic_input)
  26.  
  27.         self.topic_buttons = {}
  28.         for topic in ["Foods", "Animals"]:
  29.             button = Button(text=topic, on_press=self.select_topic)
  30.             layout.add_widget(button)
  31.             self.topic_buttons[topic] = button
  32.  
  33.         add_topic_button = Button(text='Add Topic', on_press=self.add_custom_topic)
  34.         layout.add_widget(add_topic_button)
  35.  
  36.         self.add_widget(layout)
  37.  
  38.     def select_topic(self, instance):
  39.         app = App.get_running_app()
  40.         app.selected_topic = instance.text
  41.         app.root.current = 'player_selection'
  42.  
  43.     def add_custom_topic(self, instance):
  44.         custom_topic = self.topic_input.text.strip()
  45.         if custom_topic and custom_topic not in self.topic_buttons:
  46.             self.topic_buttons[custom_topic] = Button(text=custom_topic, on_press=self.select_topic)
  47.             self.add_widget(self.topic_buttons[custom_topic])
  48.             self.topic_input.text = ''
  49.         else:
  50.             popup_content = BoxLayout(orientation='vertical')
  51.             popup_content.add_widget(Label(text='Topic already exists or is empty.'))
  52.             popup = Popup(title='Error', content=popup_content, size_hint=(0.5, 0.5))
  53.             popup.open()
  54.  
  55. class PlayerSelectionScreen(Screen):
  56.     def __init__(self, **kwargs):
  57.         super().__init__(**kwargs)
  58.         self.players = []
  59.         layout = BoxLayout(orientation='vertical')
  60.         self.player_input = TextInput(hint_text='Enter player name')
  61.         layout.add_widget(self.player_input)
  62.         self.add_player_button = Button(text='Add Player', on_press=self.add_player)
  63.         layout.add_widget(self.add_player_button)
  64.         self.start_game_button = Button(text='Start Game', on_press=self.start_game, disabled=True)
  65.         layout.add_widget(self.start_game_button)
  66.         self.players_list = BoxLayout(orientation='vertical')
  67.         layout.add_widget(self.players_list)
  68.         self.add_widget(layout)
  69.  
  70.     def add_player(self, instance):
  71.         player_name = self.player_input.text
  72.         if player_name:
  73.             self.players.append(player_name)
  74.             player_label = Label(text=f"Player {len(self.players)}: {player_name}")
  75.             self.players_list.add_widget(player_label)
  76.             self.player_input.text = ''
  77.             app = App.get_running_app()
  78.             app.players = self.players
  79.             self.start_game_button.disabled = len(self.players) < 3
  80.  
  81.     def start_game(self, instance):
  82.         if len(self.players) < 3:
  83.             popup_content = BoxLayout(orientation='vertical')
  84.             popup_content.add_widget(Label(text='You need at least 3 players to start the game.'))
  85.             popup = Popup(title='Error', content=popup_content, size_hint=(0.5, 0.5))
  86.             popup.open()
  87.         else:
  88.             app = App.get_running_app()
  89.             app.root.current = 'game_screen'
  90.             app.start_game()
  91.  
  92. class GameScreen(Screen):
  93.     def __init__(self, **kwargs):
  94.         super().__init__(**kwargs)
  95.         self.layout = BoxLayout(orientation='vertical')
  96.         self.status_label = Label(text='')
  97.  
  98.         # Timer label
  99.         self.timer_label = Label(text='Time left: 30', size_hint_y=None, height=40)
  100.         self.layout.add_widget(self.timer_label)
  101.  
  102.         # Time limit inputs
  103.         self.question_time_input = TextInput(hint_text='Question Time (seconds)', size_hint_y=None, height=40)
  104.         self.vote_time_input = TextInput(hint_text='Vote Time (seconds)', size_hint_y=None, height=40)
  105.         self.layout.add_widget(self.question_time_input)
  106.         self.layout.add_widget(self.vote_time_input)
  107.  
  108.         self.layout.add_widget(self.status_label)
  109.         self.add_widget(self.layout)
  110.  
  111.     def update_status(self, text):
  112.         self.status_label.text = text
  113.  
  114.     def start_timer(self, phase):
  115.         if phase == 'question':
  116.             self.time_left = int(self.question_time_input.text) if self.question_time_input.text else 30
  117.         elif phase == 'vote':
  118.             self.time_left = int(self.vote_time_input.text) if self.vote_time_input.text else 30
  119.         Clock.schedule_interval(self.update_timer, 1)
  120.  
  121.     def update_timer(self, dt):
  122.         if self.time_left > 0:
  123.             self.time_left -= 1
  124.             self.timer_label.text = f'Time left: {self.time_left}'
  125.         else:
  126.             Clock.unschedule(self.update_timer)
  127.             if self.current_phase == 'question':
  128.                 self.vote_spy()
  129.             else:
  130.                 self.calculate_results()
  131.  
  132. # statistics screen
  133. class StatsScreen(Screen):
  134.     def __init__(self, **kwargs):
  135.         super().__init__(**kwargs)
  136.         layout = BoxLayout(orientation='vertical')
  137.         self.stats_labels = {}
  138.  
  139.         title_label = Label(text='Player Statistics', size_hint_y=None, height=40)
  140.         layout.add_widget(title_label)
  141.  
  142.         self.add_widget(layout)
  143.  
  144.     def update_stats(self, stats):
  145.         for player, data in stats.items():
  146.             if player not in self.stats_labels:
  147.                 self.stats_labels[player] = Label()
  148.                 self.add_widget(self.stats_labels[player])
  149.             self.stats_labels[player].text = f"{player}: Rounds Played: {data['rounds']}, Caught as Spy: {data['caught']}"
  150.  
  151. # application
  152. class SpyGameApp(App):
  153.     def __init__(self, **kwargs):
  154.         super().__init__(**kwargs)
  155.         self.topics = {
  156.             "Foods": ["Apple", "Banana", "Orange"],
  157.             "Animals": ["Lion", "Tiger", "Elephant"]
  158.         }
  159.         self.selected_topic = None
  160.         self.players = []
  161.         self.points = {}
  162.         self.player_stats = {}
  163.         self.db = sqlite3.connect('game_data.db')
  164.         self.create_table()
  165.  
  166.     def build(self):
  167.         sm = ScreenManager()
  168.         sm.add_widget(TopicSelectionScreen(name='topic_selection'))
  169.         sm.add_widget(PlayerSelectionScreen(name='player_selection'))
  170.         sm.add_widget(GameScreen(name='game_screen'))
  171.         sm.add_widget(StatsScreen(name='stats_screen'))
  172.         return sm
  173.  
  174.     def create_table(self):
  175.         with self.db:
  176.             self.db.execute('''CREATE TABLE IF NOT EXISTS scores (
  177.                player TEXT PRIMARY KEY,
  178.                points INTEGER,
  179.                game_date TEXT
  180.            )''')
  181.  
  182.     def save_scores(self):
  183.         with self.db:
  184.             for player, points in self.points.items():
  185.                 self.db.execute('''INSERT OR REPLACE INTO scores (player, points)
  186.                VALUES (?, ?)''', (player, points))
  187.  
  188.     def start_game(self):
  189.         self.initialize_stats()
  190.         topic = self.selected_topic
  191.         words = random.sample(self.topics[topic], len(self.players))
  192.         self.spy_index = random.randint(0, len(self.players) - 1)
  193.         self.player_words = {}
  194.         for i, player in enumerate(self.players):
  195.             if i == self.spy_index:
  196.                 popup_content = BoxLayout(orientation='vertical')
  197.                 popup_content.add_widget(Label(text=f"{player}, you are the spy!"))
  198.                 popup = Popup(title='Your Role', content=popup_content, size_hint=(0.5, 0.5))
  199.                 self.player_words[player] = None
  200.             else:
  201.                 word = words[i]
  202.                 popup_content = BoxLayout(orientation='vertical')
  203.                 popup_content.add_widget(Label(text=f"{player}, your word is: {word}"))
  204.                 popup = Popup(title='Your Role', content=popup_content, size_hint=(0.5, 0.5))
  205.                 self.player_words[player] = word
  206.             popup.open()
  207.         game_screen = self.root.get_screen('game_screen')
  208.         game_screen.update_status(f"Topic: {topic}")
  209.         game_screen.start_timer('question')
  210.         self.ask_questions()
  211.  
  212.     def initialize_stats(self):
  213.         for player in self.players:
  214.             if player not in self.player_stats:
  215.                 self.player_stats[player] = {'rounds': 0, 'caught': 0}
  216.  
  217.     def update_player_stats(self, is_spy_caught):
  218.         for player in self.players:
  219.             self.player_stats[player]['rounds'] += 1
  220.             if is_spy_caught and player == self.players[self.spy_index]:
  221.                 self.player_stats[player]['caught'] += 1
  222.  
  223.     def calculate_results(self):
  224.         self.spy_votes = sum(1 for vote in self.votes.values() if vote == self.players[self.spy_index])
  225.         is_spy_caught = self.spy_votes > len(self.players) // 2
  226.         self.update_player_stats(is_spy_caught)
  227.         self.save_scores()
  228.         self.root.current = 'stats_screen'
  229.         stats_screen = self.root.get_screen('stats_screen')
  230.         stats_screen.update_stats(self.player_stats)
  231.  
  232. if __name__ == '__main__':
  233.     SpyGameApp().run()
  234.  
Tags: MS
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement