I am making a beginner online multiplayer Tic Tac Toe game which runs on local server. I am having 2 issues with my code.I have divided my game folder into 6 python files:
Client1.py:- This file is the Output file which the client will have.I am having some issues in this file. when the player is waiting for other players move which is in while loop if this client has played it will send PLAYED to the server and if the server is waiting for the other players move it will send W to this client else it will send The player move number.While this .py file is waiting for reply the msg its getting from the server is W and then the window shows Not Responding. Both the Clients take reference from Clientsupport.py and Network.py. These both files are just for support of clients
import pygame
from Network import network
from clientSupport import GameHelp
n=network()
pt=n.getpos()
g=GameHelp()
g.Display_Start_Up(pt)
if pt==0:
run1=True
run2=False
elif pt==1:
run1 = False
run2 = True
while True:
while run1:
num = None
num=g.Input()
out=n.send(num)
print(out,"hrl")
if out =='Y':
print(num,pt,'hey')
g.Placing(num,pt)
run2=True
break
else:
pass
while run2:
opp=n.send('PLAYED')
print(opp,'loop2')
if opp=='W':
pygame.time.delay(500)
else:
print('here is',opp)
if pt==0:
op=1
elif pt==1:
op=0
g.Placing(opp, op)
print(opp,op,'hello')
run1=True
break
Client2.py:-This file is the exact copy of Client1.py.But these both files are having same problem. This is second problem when Both the clients connect the X and O images gets blit only on the 1st client which joins server. for the second client its blank window with just board but the input and every thing else works fine.
Server.py:- This takes the reference from the other file Game.py. This file is used by the server to check who won whats score and other parameters. Pt variable in server is basically playertag send 0 and 1.the player who joins first gets 0 and is X player otherwise player is O player.
import socket
from _thread import *
import sys
import pickle
import game
server = "192.168.1.107"
port = 34262
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((server,port))
except socket.error as e:
print(str(e),'hey')
brain=game.Brain()
setup=game.Setup()
s.listen(2)
print("waiting for connection,Server connected")
p=0
setup.p2played=True
lastplayed=[0,0]
def thread_client(conn,playertag):
conn.send(pickle.dumps(playertag))
reply = ""
Run=True
while Run:
try:
try:
data = pickle.loads(conn.recv(2048))
except EOFError as e:
print(e)
pass
if not data:
print('disconnect')
break
elif data=='PLAYED':
if playertag==0:
if lastplayed[1]==0:
reply='W'
else:
reply=lastplayed[1]
lastplayed[1]=0
elif playertag==1:
if lastplayed[0]==0:
reply='W'
else:
reply=lastplayed[0]
lastplayed[0]=0
else:
if playertag==0 and setup.p2played==True:
if brain.Player_move(playertag,data):
reply='Y'
lastplayed[0]=int(data)
setup.p2played = False
setup.p1played = True
else:
reply='N'
if brain.Board_full_check():
reply='T'
Run=False
if brain.Winner_check(1):
reply='X'
Run=False
elif brain.Winner_check(-1):
reply='O'
Run=False
print(f'Recieved: {data}')
print(f'Sending {reply}')
elif playertag==1 and setup.p1played==True:
if brain.Player_move(playertag, data):
reply = 'y'
lastplayed[1] = int(data)
setup.p2played = True
setup.p1played = False
else:
reply = 'N'
if brain.Board_full_check():
reply = 'T'
Run = False
if brain.Winner_check(1):
reply = 'X'
Run = False
elif brain.Winner_check(-1):
reply = 'O'
Run = False
print(f'Recieved: {data}')
print(f'Sending {reply}')
else:
reply='W'
conn.sendall(pickle.dumps(reply))
except socket.error as e:
print(e,'ji')
break
print(f'Disconnected from {addr}')
while True:
print(game.BoardList)
conn, addr= s.accept()
print('connected to ', addr)
start_new_thread(thread_client ,(conn,p,))
p+=1
Clientsupport.py:-So this file does all the client support like pygame displays and blitting X and O.
import pygame
class GameHelp():
def __init__(self):
self.screen=pygame.display.set_mode((600, 600))
xplayer=pygame.image.load('x.png')
self.xplayer = pygame.transform.scale(xplayer, (50, 50))
oplayer = pygame.image.load('o.png')
self.oplayer = pygame.transform.scale(oplayer, (50, 50))
def Display_Start_Up(self,playertag):
caption='Tic Tac Toe '+str(playertag)
pygame.display.set_caption(caption)
self.BOARD(self.screen)
pygame.display.update()
def BOARD(self,sc):
sc.fill((225, 200, 225))
board = pygame.image.load('TransparentImage.png')
board = pygame.transform.scale(board, (375, 375))
sc.blit(board, (100, 200))
def Input(self,):
run=True
while run:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
print('1')
run=False
return 1
elif event.key == pygame.K_2:
print('2')
run=False
return 2
elif event.key == pygame.K_3:
print('3')
run=False
return 3
elif event.key == pygame.K_4:
print('4')
run=False
return 4
elif event.key == pygame.K_5:
print('5')
run=False
return 5
elif event.key == pygame.K_6:
print('6')
run=False
return 6
elif event.key == pygame.K_7:
print('7')
run=False
return 7
elif event.key == pygame.K_8:
print('8')
run=False
return 8
elif event.key == pygame.K_9:
print('9')
run=False
return 9
elif event.key == pygame.K_ESCAPE or event.type==pygame.QUIT:
pygame.quit()
def Placing(self,pos,playertag):
if playertag==0:
if pos == 1:
self.screen.blit(self.xplayer, (108, 215))
elif pos == 2:
self.screen.blit(self.xplayer, (249, 222))
elif pos == 3:
self.screen.blit(self.xplayer, (376, 213))
elif pos == 4:
self.screen.blit(self.xplayer, (122, 360))
elif pos == 5:
self.screen.blit(self.xplayer, (253, 346))
elif pos == 6:
self.screen.blit(self.xplayer, (379, 346))
elif pos == 7:
self.screen.blit(self.xplayer, (118, 486))
elif pos == 8:
self.screen.blit(self.xplayer, (261, 492))
elif pos == 9:
self.screen.blit(self.xplayer, (375, 476))
elif playertag==1:
if pos == 1:
self.screen.blit(self.oplayer, (108, 215))
elif pos == 2:
self.screen.blit(self.oplayer, (249, 222))
elif pos == 3:
self.screen.blit(self.oplayer, (376, 213))
elif pos == 4:
self.screen.blit(self.oplayer, (122, 360))
elif pos == 5:
self.screen.blit(self.oplayer, (253, 346))
elif pos == 6:
self.screen.blit(self.oplayer, (379, 346))
elif pos == 7:
self.screen.blit(self.oplayer, (118, 486))
elif pos == 8:
self.screen.blit(self.oplayer, (261, 492))
elif pos == 9:
self.screen.blit(self.oplayer, (375, 476))
pygame.display.update()
Network.py:-Nothing much to say about this fil this file only connects and sends msg to server and works perfectly fine.
Final Debug Help:- There are 2 problems:
When waiting for opponent move the Windows show Not Responding
Always the Client who is player O doesn't get the images blit thought it takes input and sends it
to server.
A Pygame window expects that its event queue is always being processed. A typical PyGame program looks like:
### Do some initialisation
[...]
### Main Loop
while not exiting:
### handle every event in the queue
for event in pygame.event.get():
if ( event.type == pygame.QUIT ):
exiting = True
elif ( event.type == [ ... ] ):
### Update all the game logic, sprites, network comms, whatever
if ( networkDataArrived( server_socket, server_rx_buffer ) ):
handleNetworkData( server_rx_buffer )
game_sprites.update()
### paint the screen
window.fill( WHITE )
paintGameBoard( window )
game_sprites.draw( window )
### Hopefully do nothing for the rest of the frame-time
clock.tick( FPS )
It's not OK to just be stopped for more than a split-second. If you're waiting for socket data to arrive, you need to check to see if any data has arrived, if not continue immediately. If you're waiting for keyboard entry, you can't call just input()... it breaks the event-model.
To handle network comms, you must do non-blocking reads. One way to do this is with the select.select() function. This allows you to "peek" at the socket buffer to see if anything has arrived. If data has arrived, you can read the exact amount held without blocking. Otherwise you just drop back to your main loop. Note that there are other ways to do this, but select() is available on all operating systems (at least for sockets), and is in most programming languages, so it's a good function to know.
Please consider this quasi~pseudo-code for networkDataArrived():
def networkDataArrived( server_socket, socket_buffer ):
""" Read from the socket, stuffing data into the buffer.
Returns True when a full packet has been read into the buffer """
result = False
socks = [ server_socket ]
input,output,excep = select.select( socks, [], [], 0.01 ) # tiny read-timeout
### has any data arrived?
if ( input.count( server_socket ) > 0 ):
socket_buffer.append( server_socket.recv( MAX_PACKET_SIZE ) )
### do we have a full packet?
if ( len( socket_buffer ) >= MAX_PACKET_SIZE ):
result = True
return result
Related
This program is an etchasketch program that uses turtle and I'm trying to figure out how to keep the turtle going without holding down the keys for the direction of the turtle.
from turtle import *
import sys
import keyboard
PIXEL_MOVE = 20
def main():
running = True
pen_down = False
keep_moving = True
print("This is lab 7")
screen_width = int(sys.argv[1])
screen_height = int(sys.argv[2])
#setting the size and color of the backround and turtle
screensize(screen_width, screen_height)
tobject = Turtle("turtle")
tobject.up()
while running:
tobject.forward(PIXEL_MOVE)
event = keyboard.read_event()
if event.event_type == keyboard.KEY_DOWN:
if event.name == 'q':
running = False
elif event.name == "p":
if pen_down == False:
pen_down = True
tobject.down()
else:
pen_down == False
tobject.up()
elif event.name == 'w':
tobject.setheading(90)
elif event.name == 'a':
tobject.setheading(180)
elif event.name == 's':
tobject.setheading(270)
elif event.name == 'd':
tobject.setheading(0)
main()
I got it to keep going in the direction if the key is being held down and pressed. But I want it to be able to move with just a keystroke and keep moving in that direction.
One way to do this is to store the last pressed key or last moved direction in a variable.
lastPressed = None
while running:
# Code before reading event
if event.event_type == keyboard.KEY_DOWN:
lastPressed = event.name
if lastPressed:
# Check if "w", "a", "s", "d", etc. and move
Hope this helps in some way :)
I'm trying to get input from a joystick I have (specifically the Logitech Extreme 3D Pro) with a Python program. Unfortunately, I do not know how to do this well.
I currently have a working prototype using PyGame, but I do not want to use PyGame because I already want another Tkinter window open at the same time.
I've tried the inputs library, but I keep getting an inputs.UnpluggedError every time I plug the joystick in.
Are there any other methods of getting joystick input, other than PyGame?
I am using an MacBook Air running Big Sur.
Working code:
import os
import pprint
import pygame
import threading
class PS4Controller(object):
"""Class representing the PS4 controller. Pretty straightforward functionality."""
controller = None
axis_data = None
button_data = None
hat_data = None
def init(self):
"""Initialize the joystick components"""
pygame.init()
pygame.joystick.init()
self.controller = pygame.joystick.Joystick(0)
self.controller.init()
def listen(self):
"""Listen for events to happen"""
if not self.axis_data:
self.axis_data = {}
if not self.button_data:
self.button_data = {}
for i in range(self.controller.get_numbuttons()):
self.button_data[i] = False
if not self.hat_data:
self.hat_data = {}
for i in range(self.controller.get_numhats()):
self.hat_data[i] = (0, 0)
while True:
for event in pygame.event.get():
if event.type == pygame.JOYAXISMOTION:
self.axis_data[event.axis] = round(event.value,2)
elif event.type == pygame.JOYBUTTONDOWN:
self.button_data[event.button] = True
elif event.type == pygame.JOYBUTTONUP:
self.button_data[event.button] = False
elif event.type == pygame.JOYHATMOTION:
self.hat_data[event.hat] = event.value
# Insert your code on what you would like to happen for each event here!
# In the current setup, I have the state simply printing out to the screen.
os.system('clear')
pprint.pprint(self.button_data)
pprint.pprint(self.axis_data)
pprint.pprint(self.hat_data)
def controller_main():
ps4 = PS4Controller()
ps4.init()
ps4.listen()
controller_main()
Try this py-joystick module:
https://pypi.org/project/pyjoystick/
Hope it helps!😊
from pyjoystick.sdl2 import Key, Joystick, run_event_loop
def print_add(joy):
print('Added', joy)
def print_remove(joy):
print('Removed', joy)
def key_received(key):
print('received', key)
if key.value == Key.HAT_UP:
#do something
elif key.value == Key.HAT_DOWN:
#do something
if key.value == Key.HAT_LEFT:
#do something
elif key.value == Key.HAT_UPLEFT:
#do something
elif key.value == Key.HAT_DOWNLEFT:
#do something
elif key.value == Key.HAT_RIGHT:
#do something
elif key.value == Key.HAT_UPRIGHT:
#do something
elif key.value == Key.HAT_DOWNRIGHT:
#do something
run_event_loop(print_add, print_remove, key_received)
I'm trying to separate my input loop from my game logic in my simple snake game that I've made with pygame, but, I'm really struggling to figure out why nothing is happening when I run the program.
I've tried importing pygame in the subprocess, I checked for errors on the subprocess, and got nowhere. I looked on google, but I wasn't able to find any usable examples, or similar issues. Has anybody ever figured any of this stuff out?
Okay, here's the code:
import pygame
import time
import multiprocessing as mp
import random as rnd
pygame.init()
def event_to_dict(event: pygame.event) -> dict:
return {
'type': event.type,
'key': event.key if event.type == pygame.KEYDOWN else None,
}
class SnakeBoard:
def __init__(self, rows: int, columns: int):
self.rows = rows
self.columns = columns
self.vertices = []
self.odd_column = False
self.buff = []
for _ in range(self.rows):
self.buff.append([' ' for _ in range(self.columns)])
def initialize(self):
for r in range(self.rows):
for c in range(self.columns):
self.buff[r][c] = ' '
self.odd_column = (self.columns >> 1) % 2 == 1
self.buff[self.rows >> 1][self.columns >> 1] = '\u25cb'
self.vertices = [(self.rows >> 1, self.columns >> 1)]
def place_food(self):
while True:
r = rnd.randint(0, self.rows - 1)
c = rnd.randint(0, self.columns - 1)
codd = c % 2 == 1
if (codd and self.odd_column or not codd and not self.odd_column) and self.buff[r][c] != '\u25cb':
self.buff[r][c] = '\u25c9'
break
def tick(self, direction: int) -> bool:
nr, nc = self.vertices[-1]
if direction == 0:
nr -= 1
elif direction == 1:
nc += 1
elif direction == 2:
nr += 1
elif direction == 3:
nc -= 1
else:
print("Invalid direction for snake")
exit(1)
if nr >= self.rows or nc >= self.columns or nr < 0 or nc < 0 or self.buff[nr][nc] == '\u25cb':
return False
self.vertices.append((nr, nc))
self.vertices.pop(0)
return True
class SnakeGame(SnakeBoard):
def __init__(self, rows: int, columns: int):
super().__init__(rows, columns)
self.score = 0
self.direction = 0
self.initialize()
self.place_food()
def tick(self, direction: int = -1) -> bool:
v = super().tick(self.direction if direction < 0 else direction)
if self.buff[self.vertices[-1][0]][self.vertices[-1][1]] == '\u25c9':
self.score += 1
self.vertices.append(self.vertices[-1])
self.place_food()
for r in range(self.rows):
for c in range(self.columns):
if (r, c) in self.vertices:
self.buff[r][c] = '\u25cb'
elif self.buff[r][c] != '\u25c9' and self.buff[r][c] != ' ':
self.buff[r][c] = ' '
return v
class GameLoop(mp.Process):
def __init__(self, q: object, size: list):
super().__init__()
self.q = q
self.size = size
self.g = SnakeGame(size[1] // 10, size[0] // 10)
self.g.initialize()
self.g.place_food()
self.screen = None
self.game_surf = None
self.font = None
def run(self) -> None:
try:
import pygame
pygame.init()
self.screen = pygame.display.set_mode(self.size)
self.game_surf = pygame.Surface(self.size)
self.font = pygame.font.SysFont('roboto', 16)
is_running = True
while is_running:
if self.q.poll(0):
d = self.q.recv()
if d is not None:
if d['type'] == pygame.KEYDOWN:
if d['key'] == pygame.K_a:
self.g.direction = 3
elif d['key'] == pygame.K_s:
self.g.direction = 2
elif d['key'] == pygame.K_d:
self.g.direction = 1
elif d['key'] == pygame.K_w:
self.g.direction = 0
elif d['key'] == pygame.K_ESCAPE:
is_running = False
else:
is_running = False
self.game_surf.fill((255, 255, 255))
for ri, r in enumerate(self.g.buff):
for ci, c in enumerate(r):
if c == '\u25cb':
# print("Drawing a snake at {}, {}".format(ri * 10, ci * 10))
pygame.draw.circle(self.game_surf,
(0, 0, 255),
((ci * 10) + 5, (ri * 10) + 5),
5)
elif c == '\u25c9':
# wprint("Placing food at {}, {}".format(ci, ri))
pygame.draw.circle(self.game_surf,
(0, 127, 255),
((ci * 10) + 5, (ri * 10) + 5),
5)
timg = self.font.render("Score: {}, Level: {}".format(self.g.score, self.g.score // 10 + 1),
True,
(0, 0, 0))
self.screen.blit(self.game_surf, (0, 0))
self.screen.blit(timg, (0, 0))
pygame.display.flip()
if self.g.tick():
time.sleep(1 / ((int(self.g.score / 10 + 1)) * 10))
else:
timg = self.font.render("Game Over! Would you like to try again?", True, (0, 0, 0))
self.screen.blit(timg, ((self.size[0] >> 1) - 150, self.size[1] >> 1))
timg = self.font.render("Yes", True, (0, 0, 0))
btn_pos = ((self.size[0] >> 1) - 25, (self.size[1] >> 1) + 20)
self.screen.blit(timg, btn_pos)
pygame.display.flip()
while True:
event = pygame.event.wait()
if event.type == pygame.QUIT:
is_running = False
break
elif event.type == pygame.MOUSEBUTTONUP:
mx, my = pygame.mouse.get_pos()
if btn_pos[0] - 5 <= mx <= btn_pos[0] + 30 and btn_pos[1] - 5 <= my <= btn_pos[1] + 20:
self.g.initialize()
self.g.place_food()
self.g.score = 0
break
self.q.close()
except Exception as e:
print(e)
if __name__ == '__main__':
size = [800, 600]
parent, child = mp.Pipe()
p = GameLoop(child, size)
p.start()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
ed = event_to_dict(event)
parent.send(ed)
parent.close()
p.join()
pygame.quit()
Sorry, it's kinda strange, this was migrated from the console to pygame, so some of the logic is still using the unicode symbols.
Generally in GUI applications it's common to want to separate the GUI from the logic.
There are benefits to doing this as it means your GUI remains responsive even if your logic
is busy. However, in order to run things concurrently there are many drawbacks, including
overheads. It's also important to know that python is not 'thread safe', so you can break
things (see race conditions) if you're not careful.
Simplified example with no concurrency
Your example is quite complex so lets start with a simple example: A simple pygame setup with
a moving dot
import pygame
import numpy as np
# Initialise parameters
#######################
size = np.array([800, 600])
position = size / 2
direction = np.array([0, 1]) # [x, y] vector
speed = 2
running = True
pygame.init()
window = pygame.display.set_mode(size)
pygame.display.update()
# Game loop
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
direction = np.array([0, -1])
elif event.key == pygame.K_a:
direction = np.array([-1, 0])
elif event.key == pygame.K_s:
direction = np.array([0, 1])
elif event.key == pygame.K_d:
direction = np.array([1, 0])
position += direction * speed
if position[0] < 0 or position[0] > size[0] or position[1] < 0 or position[1] > size[1]:
running = False
pygame.time.wait(10) # Limit the speed of the loop
window.fill((0, 0, 0))
pygame.draw.circle(window, (0, 0, 255), position, 10)
pygame.display.update()
pygame.quit()
quit()
We're going to split off the game logic from the gui
Mutliprocessing and other options:
So multiprocessing in python allows you to utilise multiple cores at the same time, through multiple interpreters.
While this sounds good, as far as I/O goes: it comes with higher overheads and doesn't help at all (it will likely
hurt your performance). Threading and asyncio both run on a single core i.e. they aren't 'parrallel' computing. But
what they allow is to complete code while waiting for other code to finish. In other words you can input commands
while your logic is running happily elsewhere.
TLDR: as a general rule:
CPU Bound (100% of the core) program: use multiprocessing,
I/O bound program: use threading or asyncio
Threaded version
import pygame
import numpy as np
import threading
import time
class Logic:
# This will run in another thread
def __init__(self, size, speed=2):
# Private fields -> Only to be edited locally
self._size = size
self._direction = np.array([0, 1]) # [x, y] vector, underscored because we want this to be private
self._speed = speed
# Threaded fields -> Those accessible from other threads
self.position = np.array(size) / 2
self.input_list = [] # A list of commands to queue up for execution
# A lock ensures that nothing else can edit the variable while we're changing it
self.lock = threading.Lock()
def _loop(self):
time.sleep(0.5) # Wait a bit to let things load
# We're just going to kill this thread with the main one so it's fine to just loop forever
while True:
# Check for commands
time.sleep(0.01) # Limit the logic loop running to every 10ms
if len(self.input_list) > 0:
with self.lock: # The lock is released when we're done
# If there is a command we pop it off the list
key = self.input_list.pop(0).key
if key == pygame.K_w:
self._direction = np.array([0, -1])
elif key == pygame.K_a:
self._direction = np.array([-1, 0])
elif key == pygame.K_s:
self._direction = np.array([0, 1])
elif key == pygame.K_d:
self._direction = np.array([1, 0])
with self.lock: # Again we call the lock because we're editing
self.position += self._direction * self._speed
if self.position[0] < 0 \
or self.position[0] > self._size[0] \
or self.position[1] < 0 \
or self.position[1] > self._size[1]:
break # Stop updating
def start_loop(self):
# We spawn a new thread using our _loop method, the loop has no additional arguments,
# We call daemon=True so that the thread dies when main dies
threading.Thread(target=self._loop,
args=(),
daemon=True).start()
class Game:
# This will run in the main thread and read data from the Logic
def __init__(self, size, speed=2):
self.size = size
pygame.init()
self.window = pygame.display.set_mode(size)
self.logic = Logic(np.array(size), speed)
self.running = True
def start(self):
pygame.display.update()
self.logic.start_loop()
# any calls made to the other thread should be read only
while self.running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running = False
elif event.type == pygame.KEYDOWN:
# Here we call the lock because we're updating the input list
with self.logic.lock:
self.logic.input_list.append(event)
# Another lock call to access the position
with self.logic.lock:
self.window.fill((0, 0, 0))
pygame.draw.circle(self.window, (0, 0, 255), self.logic.position, 10)
pygame.display.update()
pygame.time.wait(10)
pygame.quit()
quit()
if __name__ == '__main__':
game = Game([800, 600])
game.start()
So what was achieved?
Something light like this doesn't really need any performance upgrades. What this does allow though, is that
the pygame GUI will remain reactive, even if the logic behind it hangs. To see this in action we can put the logic
loop to sleep and see that we can still move the GUI around, click stuff, input commands etc.
change:
# Change this under _loop(self) [line 21]
time.sleep(0.01)
# to this
time.sleep(2)
# if we tried this in the original loop the program becomes glitchy
I have been working on making a Pygame for my Social Studies class and I want to add new elements to this existing game. The problem is, when I load the old game, without making any significant changes, I get an error. It seems to have a couple of warnings as well that I have looked up but most of the threads are from years ago. My error is as follows:
Jordans-MacBook-Air:SS-Game Jordanxxi$ python ocean_cleaner.py
2017-05-26 12:23:15.729 Python[61184:1392206] Warning once: This application, or a library it uses, is using NSQuickDrawView, which has been deprecated. Apps should cease use of QuickDraw and move to Quartz.
May 26 12:23:15 Python[61184] <Error>: The function ‘SLSFlushWindow’ is obsolete and will be removed in an upcoming update. Unfortunately, this application, or a library it uses, is using this obsolete function, and is thereby contributing to an overall degradation of system performance. Please use `SLSFlushWindowContentRegion' instead.
Traceback (most recent call last):
File "ocean_cleaner.py", line 30, in <module>
hit = pygame.mixer.Sound("resources/audio/pop.wav")
pygame.error: mixer system not initialized
My code, as of now, is as follows:
#Import statements
import pygame, sys
import pygame.mixer
import time
from pygame.locals import *
#Pygame function to load the game and screen size
pygame.init()
screen = pygame.display.set_mode((700,500))
#Images needed in game
background = pygame.image.load("resources/images/background.png")
slick = pygame.image.load("resources/images/slick.png")
slick_med = pygame.image.load("resources/images/slick_med.png")
slick_sml = pygame.image.load("resources/images/slick_sml.png")
diver = pygame.image.load("resources/images/diver_gun.png")
diver1 = pygame.image.load("resources/images/diver_gun1.png")
spray_right = pygame.image.load("resources/images/spray_right.png")
spray_left = pygame.image.load("resources/images/spray_left.png")
win_screen = pygame.image.load("resources/images/win_screen.png")
lose_screen = pygame.image.load("resources/images/lose_screen.png")
red_bar = pygame.image.load("resources/images/red_bar.png")
green_bar2 = pygame.image.load("resources/images/green_bar2.png")
green_bar4 = pygame.image.load("resources/images/green_bar4.png")
air_bar = pygame.image.load("resources/images/air_bar.png")
spray_bar = pygame.image.load("resources/images/spray_bar.png")
#Sounds
hit = pygame.mixer.Sound("resources/audio/pop.wav")
hit.set_volume(0.5)
wash = pygame.mixer.Sound("resources/audio/spray.wav")
wash.set_volume(0.4)
pygame.mixer.music.load('resources/audio/tune_1.wav')
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)
#The Variables
player = diver
spray = spray_right
spray_off_set = 0
pop=False
pop_index=0
player_x = 250
player_y = 100
background_x = 0
background_y = 0
move_x = 0
move_y = 0
keys=[False,False,False,False,False]
slick_large=[[slick,300,250],[slick,1000,650],[slick,1400,1050]]
slick_medium =[]
slick_small = []
clean_up = 12
life = True
sprays = 30
main_loop = 1
while main_loop:
pygame.display.set_caption('Greek Mythology Quiz')
#How the charater moves when certain keys are clicked
#---------------------------------------------------#
#Move Right
if keys[0]==True and move_x <5:
move_x+= 1
player = diver1
spray = spray_left
spray_off_set = -200
#Move Left
if keys[1]==True and move_x >-1310:
move_x-= 1
player = diver
spray = spray_right
spray_off_set = 0
#Move Up
if keys[2]==True and move_y <10:
move_y+= 1
#Move Down
if keys[3]==True and move_y >-1010:
move_y-= 1
#Check for collisions
spray_rect=pygame.Rect(spray.get_rect())
spray_rect.left=(350+spray_off_set)
spray_rect.top=100
player_rect=pygame.Rect(player.get_rect())
player_rect.left= player_x
player_rect.top= player_y
for i in range(len(slick_large)):
slick_rect=pygame.Rect(slick.get_rect())
slick_rect.left=((slick_large[i][1])+move_x)
slick_rect.top=(slick_large[i][2]+move_y)
if spray_rect.colliderect(slick_rect) and keys[4] == True:
pop=True
pop_index=i
if player_rect.colliderect(slick_rect):
life = False
#When pop sound is called, volume depends on object size
if pop==True:
hit.play()
slick_medium.append([slick_med,(slick_large[pop_index][1]+75),(slick_large[pop_index][2]-50)])
slick_medium.append([slick_med,(slick_large[pop_index][1]+150),(slick_large[pop_index][2]+50)])
slick_large.pop(pop_index)
pop=False
#Collision redirect physics
for i in range(len(slick_medium)):
slick_rect=pygame.Rect(slick_med.get_rect())
slick_rect.left=((slick_medium[i][1])+move_x)
slick_rect.top=(slick_medium[i][2]+move_y)
if spray_rect.colliderect(slick_rect) and keys[4] == True:
pop=True
pop_index=i
if player_rect.colliderect(slick_rect):
life = False
if pop==True:
hit.play()
slick_small.append([slick_sml,(slick_medium[pop_index][1]-75),(slick_medium[pop_index][2]-75)])
slick_small.append([slick_sml,(slick_medium[pop_index][1]-150),(slick_medium[pop_index][2]-50)])
slick_medium.pop(pop_index)
pop=False
for i in range(len(slick_small)):
slick_rect=pygame.Rect(slick_sml.get_rect())
slick_rect.left=((slick_small[i][1])+move_x)
slick_rect.top=(slick_small[i][2]+move_y)
if spray_rect.colliderect(slick_rect) and keys[4] == True:
pop=True
pop_index=i
if player_rect.colliderect(slick_rect):
life = False
if pop==True:
hit.play()
slick_small.pop(pop_index)
clean_up -=1
pop=False
#Background scrolling
screen.fill(0)
screen.blit(background,((background_x+move_x),(background_y+move_y)))
screen.blit(player,(player_x,player_y))
if keys[4]==True:
wash.play()
screen.blit(spray,((350+spray_off_set),100))
else:
wash.stop()
for i in range( len(slick_large)):
screen.blit(slick_large[i][0],((slick_large[i][1]+move_x),(slick_large[i][2]+move_y)))
for i in range( len(slick_medium)):
screen.blit(slick_medium[i][0],((slick_medium[i][1]+move_x),(slick_medium[i][2]+move_y)))
for i in range( len(slick_small)):
screen.blit(slick_small[i][0],((slick_small[i][1]+move_x),(slick_small[i][2]+move_y)))
time_remaining = int((60-(pygame.time.get_ticks()/1000)))
screen.blit(air_bar,(8,8))
screen.blit(red_bar,(10,10))
for i in range(time_remaining):
screen.blit(green_bar2,(10+(i*2),10))
screen.blit(spray_bar,(570,8))
screen.blit(red_bar,(572,10))
for i in range(sprays):
screen.blit(green_bar4,(572+(i*4),10))
if clean_up == 0:
screen.blit(win_screen,(0,0))
main_loop = 0
if life == False or sprays == 0 or time_remaining == 0:
screen.blit(lose_screen,(0,0))
main_loop = 0
pygame.display.flip()
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
exit(0)
#Event checkers - Check to see if certain keys are pressed
if event.type == pygame.KEYDOWN:
if event.key==K_LEFT:
keys[0]=True
elif event.key==K_RIGHT:
keys[1]=True
elif event.key==K_UP:
keys[2]=True
elif event.key==K_DOWN:
keys[3]=True
elif event.key==K_SPACE:
keys[4]=True
#Check to see when certain keys are released
if event.type == pygame.KEYUP:
if event.key==K_LEFT:
keys[0]=False
elif event.key==K_RIGHT:
keys[1]=False
elif event.key==K_UP:
keys[2]=False
elif event.key==K_DOWN:
keys[3]=False
elif event.key==K_SPACE:
keys[4]=False
sprays -= 1
end = 1
while end:
#Exit function
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
exit(0)
Any help? Thanks in advance.
Update - I was running the game through terminal instead of Idle. I still get an error but it is a little bit different. Anyone know how to fix this?
Traceback (most recent call last):
File "/Users/Jordanxxi/Desktop/Game/ocean_cleaner.py", line 29, in <module>
hit = pygame.mixer.Sound("resources/audio/pop.wav")
error: mixer system not initialized
I believe you have to do:
pygame.mixer.init()
Check the documentation for mixer (this is always a good idea to do first when you have a problem!): http://www.pygame.org/docs/ref/mixer.html
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm building a game using PyGame and Python 3.4. I am having an issue with what appears to be the module itself and not the actual code I have because the full error is:
Traceback (most recent call last):
File "C:\Users\----\Desktop\Python\Game.py", line 115, in <module>
playerhit = pygame.sprite.spritecollide(ebullet, psprite, True)
File "C:\Python34\lib\site-packages\pygame\sprite.py", line 1514, in spritecollide
for s in group.sprites():
AttributeError: 'Player' object has no attribute 'sprites'
I dashed out my name but kept the length, though I don't think it matters.
I've looked around the web for different parts of the error and nothing has come up, so I came here. Here's the full code (it's kinda messy and long):
import pygame, time, sys, random, Sprites, os
from pygame.locals import *
BLACK = (0, 0, 0)
MAPX = 10
MAPY = 20
TXY = 32
gameover = False
score = 0
lives = 2
playerXY = [MAPX*TXY//2, MAPY*TXY-TXY-TXY-5]
spritesheet01 = Sprites.Sheet(32, 32, 128, 32, 'spritesheet03.png')
sprites = spritesheet01.clipSheet()
psprite = Sprites.Player(sprites[0])
clock = pygame.time.Clock()
counter = int(clock.get_fps())
ebullet = Sprites.eBullet(sprites[3])
allspriteslist = pygame.sprite.Group()
enemylist = pygame.sprite.Group()
ebulletlist = pygame.sprite.Group()
pbulletlist = pygame.sprite.Group()
allspriteslist.add(psprite)
pygame.init()
enemynum = 5
enemies = []
enemytorf = [False, False, False, False, False, False, False, False, False, False]
def pause():
os.system("pause")
def enemyCreate():
print("enemycreate called")
while len(enemylist) < 5:
randomindex = random.randint(0, MAPX-1)
if enemytorf[randomindex] == False:
enemy = Sprites.Enemy(sprites[1])
enemytorf[randomindex] = True
enemy.rect.x = randomindex
enemy.rect.y = 0
ebullet.rect.x = randomindex
ebullet.rect.y = 0
enemylist.add(enemy)
allspriteslist.add(enemy)
ebulletlist.add(ebullet)
allspriteslist.add(ebullet)
print("enemycreate done")
def eBulletCreate():
print("bulletpassed")
for wi in range(len(ebull)):
ebullappend = ebull[wi]
ebullets.append(ebullappend)
print("Got through function defining")
display = pygame.display.set_mode((MAPX*TXY, MAPY*TXY))
pygame.display.set_caption("Star Smasher")
print("created screen")
pygame.key.set_repeat(10, 10)
endgame = False
create_enemy = pygame.USEREVENT + 1
shootbullet = pygame.USEREVENT + 2
print("created events")
enemyCreate()
pygame.time.set_timer(create_enemy, 7500)
pygame.time.set_timer(shootbullet, 2500)
print("Got to the while")
while endgame == False:
print("got into while")
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_SPACE:
pbullet = Sprites.pBullet(sprites[2])
pbullet.rect.x = playerXY[0]
pbullet.rect.y = playerXY[1]
allspriteslist.add(pbullet)
pbulletlist.add(pbullet)
elif event.key == K_a:
if playerXY[0] > 5:
playerXY[0] -= 5
elif event.key == K_d:
if playerXY[0] < MAPX*TXY-TXY-7:
playerXY[0] += 5
if event.type == create_enemy:
enemyCreate()
if event.type == shootbullet:
eBulletCreate()
print("got through event handling")
for bullet in pbulletlist:
enemyhitlist = pygame.sprite.spritecollide(pbullet, enemylist, True)
for enemy in enemyhitlist:
pbulletlist.remove(bullet)
allspriteslist.remove(bullet)
score += 100
print(score)
if pbullet.rect.y < 0:
pbulletlist.remove(bullet)
allspriteslist.remove(bullet)
for bullet in ebulletlist:
playerhit = pygame.sprite.spritecollide(ebullet, psprite, True)
for player in playerhit:
ebulletlist.remove(bullet)
allspriteslist.remove(bullet)
gameover = True
if ebullet.rect.y > MAPY*TXY:
ebulletlist.remove(bullet)
allspriteslist.remove(bullet)
print("got through bullet handling")
display.fill(BLACK)
allspriteslist.draw(display)
if gameover == True:
font = pygame.font.Font(freesansbold.ttf, 20)
font.render("Game Over, press any button to continue!", True, BLACK, background=None)
display.blit(font, (160, 320, 200, 360))
pause()
pygame.display.update()
clock.tick(60)
print("Got to the display update")
pygame.quit()
Thanks in advance for the help!
It is the wrong way around for a start. playerhit = pygame.sprite.spritecollide(ebullet, psprite, True) - the function definition is spritecollide(sprite, group, dokill, collided = None) so the player should be first, and then the bullet group.
Also please post the Sprite.py code.